Tutorials

Tutorials

Make your own Python business sales program with just the HyperionDev Free Trial basics

Tutorials

Make your own Python business sales program with just the HyperionDev Free Trial basics

Learn how to build a program that cleans up messy text file sales data, and returns clean information about profits and business activity.

In this series, we learn how to make simple Python programs for real-world problems using just the material taught in HyperionDev’s free trial. Today, we break down how to code a basic program that goes through a confusing, pages-long text document of sales information to give a business owner his total sales, total number of items sold, and tips payable to his workers.

The real-world problem: a broken sales machine

Let’s imagine the scene: your friend John runs a hot food stall at club rugby games on the weekend. His stand is doing very well, and food is flying off the shelf… when his point of sales machine suddenly breaks. Not wanting to stop trade to wait to fix the machine, he tells his staff to just write down their names, the items they sold, and whatever tips they made on a notepad on his tablet.

Of course, after a day of hectic sales, he checks the list and sees that it’s a dense mess, with 500+ sales made, and thousands of items in the note. He doesn’t have the time to sit there and do it all by hand, so he calls you, asking if you can somehow pull useful information from the confusing text mess. John wants to know the key info about how much his stall sold of each item, how much money he made, and how much he has to pay out to each person who manned the tills that day.

John is in luck, because this is exactly the kind of work that Python makes quick and painless.

Setting up what you need for the program

To start, let’s give John’s sales information to the program . We can do this by creating a string that is equal to the text of John’s iPad sales note (for brevity, the example we’re using is only 50 sales items long, but this code will work on a similar file that’s thousands of items long):

daily_sales = """Khatija, boerie, boerie, B&E, B&E,  chips,  chips, water, coke, coke, water, 20 ; Khatija,  chips, B&E, boerie,  chips, boerie,  chips, water, water, coffee, coke, coffee, water, 24 ; Khatija, burger, B&E,  chips, water, water, water, coke, coffee, coffee, coffee, 20 ; Noxi, burger, burger, boerie, B&E, B&E,  chips, burger, water, 16 ; Noxi,  chips, boerie,  chips, B&E, burger, water, water, coffee, 16 ; Khatija, boerie, boerie,  chips, burger,  chips,  chips, B&E, water, coke, 18 ; Fred, B&E,  chips, B&E, coffee, water, 10 ; Fred, B&E, burger, boerie,  chips, boerie, boerie, water, coffee, coffee, water, coffee, coffee, 24 ; Khatija, boerie, burger, B&E, burger, B&E, burger, water, coffee, coffee, 18 ; Khatija, burger, boerie, boerie, burger, burger,  chips, coke, coffee, coke, water, coke, coffee, 24 ; Khatija,  chips, B&E, B&E, B&E, boerie, B&E, water, coffee, coke, coffee, 20 ; Noxi, burger,  chips, B&E, boerie, burger, water, 12 ; Fred, boerie, boerie, boerie,  chips, boerie, boerie, B&E, coke, water, coke, coffee, water, coke, 26 ; Noxi, B&E, burger, B&E, boerie, burger, burger, burger, coke, water, coffee, 20 ; Noxi, burger, boerie, burger, burger, boerie,  chips,  chips, water, water, coke, coke, coffee, 24 ; Khatija,  chips, water, water, coke, coffee, coke, coke, water, 16 ; Noxi, B&E, boerie,  chips, boerie, burger, coffee, water, coffee, coke, coke, coffee, 22 ; Fred, boerie, boerie,  chips, boerie, B&E, B&E, coffee, water, coffee, 18 ; Fred, burger,  chips, burger, burger, coke, coke, coffee, water, 16 ; Noxi, boerie,  chips, burger, burger, burger, coffee, 12 ; Fred, burger,  chips,  chips, water, 8 ; Noxi, B&E,  chips, boerie, burger,  chips, boerie, water, coke, coke, coke, 20 ; Khatija, B&E,  chips, burger,  chips, B&E, boerie, coffee, coffee, 16 ; Fred, boerie, boerie, burger, boerie,  chips, water, coffee, coke, coke, water, coffee, water, 24 ; Khatija,  chips, B&E, B&E, boerie,  chips, boerie, boerie, water, water, coffee, water, coffee, 24 ; Noxi, B&E, B&E, coffee, coke, coke, water, coke, 14 ; Khatija, boerie, B&E,  chips,  chips,  chips, boerie, boerie, coke, water, 18 ; Fred, burger,  chips,  chips,  chips, burger, B&E, coffee, coffee, coke, 18 ; Khatija, burger, burger, coffee, coffee, coke, water, coffee, 14 ; Fred, burger, boerie, water, coke, coffee, coke, 12 ; Khatija, boerie, B&E,  chips, burger, B&E,  chips, B&E, coffee, coffee, coke, coke, water, coke, 26 ; Fred, boerie, boerie, B&E, water, water, 10 ; Fred, boerie, burger,  chips,  chips,  chips, water, water, coffee, water, coffee, 20 ; Noxi, burger, B&E, boerie,  chips, burger, coke, coffee, coffee, coffee, coffee, coffee, coke, 24 ; Khatija, B&E, boerie,  chips, water, coffee, water, water, coke, coke, 18 ; Noxi, boerie, B&E, coffee, coke, coke, coke, coke, 14 ; Fred, boerie, water, coffee, coffee, coke, 10 ; Noxi, B&E, water, coke, 6 ; Fred,  chips,  chips, boerie,  chips, coke, coffee, water, coffee, 16 ; Khatija,  chips, boerie, burger,  chips, coke, 10 ; Fred, burger, boerie, boerie, burger, burger, burger, B&E, water, coke, 18 ; Noxi,  chips, burger, burger,  chips, B&E, water, 12 ; Fred,  chips, B&E, coffee, coke, 8 ; Noxi, boerie, boerie, boerie, burger, coke, 10 ; Khatija, B&E,  chips, B&E, coffee, water, coke, 12 ; Fred, boerie, boerie, B&E, boerie, B&E,  chips, burger, coke, water, water, coke, coke, water, coke, 28 ; Khatija, B&E, coffee, coffee, coffee, 8 ; Noxi, B&E, boerie, burger, B&E, B&E, B&E, water, water, 16 ; Fred, boerie, boerie, coke, 6 ; Khatija, B&E, burger, boerie, burger, B&E, coke, water, coke, coke, water, 20 ; """

Next, we need to know what John was selling and how much each item was selling for, if we want to figure out how much money he made. For this, we’ll put the prices of the food and drink on sale into dictionary objects. Dictionaries – denoted by curly brackets “{}” – pair up two variables in a particular manner. This allows us to pair up items and their prices as key:value pairs. We can always update this dictionary if John’s prices ever change, or if he wants to add more items to his stall in future sales days!

ItemList = {"burger":35, "boerie":25, "B&E":20, "chips":20, "coffee":12, "coke":12, "water":10}

Get some clean data for the program

Now that we know what John’s stall sells, let’s clean up his sales info. While spaces are good for readability, we only care about the variables themselves and their values. Removing spaces will make the list easier to search and manipulate with our program.

One way to accomplish this is writing a loop that goes through the string one character at a time and replaces or removes characters that match one we provide, but that would take more space and lines of code. We always want to look for the most efficient way to write our code, so instead we’ll be using the integrated function that Python has for this, .replace(). We can tell it what to look for, and what to put in its place, all in a single line – plus, we can also use it to remove any accidental characters we don’t want in the sales receipt, or deal with the possibility that each salesperson would write a different character (other than a semicolon, say a ‘#’) after they write down a sale.

daily_sales = daily_sales.replace(" ", "")

Now we want to take that large, unwieldy wall of text from earlier, and make it a far more manageable list of sales. Remember that a list is just a group of variables combined in a single collection through the use of square brackets.

The sales team at the stall separated their individual sales info by using a semicolon. We can use this info in Python’s integrated .split() function, which takes a string and turns it into a list of items, splitting up the list elements according to a certain rule you provide.

all_sales = daily_sales.split(";")

This will give us a list of all individual sales transactions – but if you print this list, you’ll notice that each ‘sale’ is a string, and not a list object! That’s a problem, because we want to have each thing the sales person writes down be an item in a list we can easily examine and use. So, let’s combine another .split() function with a loop that goes through that list of strings, and turns each string into a list, splitting items wherever there is a comma (the punctuation the sales team used to separate each item they sold in a single sale.)

As a reminder, a for statement is a simple loop that allows you to do something with each element in a given collection of data.

all_sales_split = []
tempstring = ""
for x in all_sales:
tempstring = x.split(",")
all_sales_split.append(tempstring)

If you print this new list, you’ll notice that it’s a list that contains lists. You’ve just created a nested list – these are powerful programming objects that you’ll use in a lot of future programs.

Get each salesperson’s list of sales

Now that we have a list of individual sales lists, we can make those calculations John asked us for. Let us first create empty lists for each employee.

FredSales = []
NoxiSales = []
KhatijaSales = []

We will fill these with information from the main list.

Did you notice that the first item on every sale is the sales person’s name? We can use this to find which sales belong to who, and put those into their own personal sales lists using Python’s .append() method. Appending means adding a new item to the end of a list. As with the other integrated methods, it saves you time.

Remember that the Python language is zero-indexed, meaning we start counting list items from zero, and not from one (like a normal person would). So if we check to see which name is in the first element of the list – AKA index address 0 – we can find who made the sale.

We will create a function to do this. However, to avoid having to create a separate function to find each team member’s sales, we will create a single function that receives a parameter to do its work. A parameter is a special kind of variable that serves as a kind of input for the piece of code you’re executing. Imagine you’ve got a program that paints, and you give it a jar of red paint: it will paint, using the parameter of red paint.

Using a for statement, we will check each item in the list, using an if statement to check the name in the first list item (index 0). This if statement does something depending on a certain condition being true: here, if the first list element of each sale matches a person’s name, we add that list to their personal sales list.

def create_salesperson_lists(listitem):
for x in listitem:
if x[0] == "Fred":
FredSales.append(x)
elif x[0] == "Noxi":
NoxiSales.append(x)
elif x[0] == "Khatija":
KhatijaSales.append(x)

Calculate the total items sold and total sales revenue

Now we need a function to count the total number of individual items sold, tally them up, and calculate total revenues from all sales. This function will use John’s dictionary of items for sale and their prices.

We do the same thing as we did above: create a function that uses John’s dictionary object of items and prices as a parameter. Using another for statement, this function will run through the dictionary object, checking each key against our list of items sold. It then finds the price of that item using the integrated Python dictionary method .get(), which returns the value (the selling price of an item) of each key (the item for sale). For each key in John’s sales dictionary object, it gets the price of that item with .get(), counts the number of times that item appears in our sales info using the integrated .count() function, and then tallies it all up, printing the result to the user. We also keep a track of how many items we sold in total with an integer variable called TotalSales.

Remember: when you try to print something that isn’t a string, Python will display an error. To prevent this error, you have to convert that variable into a string first, by using the integrated str() function.

def total_items_sold_and_totals(list_of_all_things_on_sale):
TotalSales = 0
for key in list_of_all_things_on_sale:
price_of_item = list_of_all_things_on_sale.get(key)
total_items_sold = daily_sales.count(key)
food_item_subtotal = (total_items_sold*price_of_item)
print("Total sales for '"+key+"' were "+str(total_items_sold)+" for a total value of R"+ str(food_item_subtotal))
TotalSales += food_item_subtotal
print("The total revenue generated from all sales was R"+str(TotalSales))

Now that we have the main functions we need, let’s use them (also known as “calling the functions”), providing them the sales list and dictionary of sales items as their parameters. They’ll take those lists, and do what we told them to do with the information those lists contain.

total_items_sold_and_totals(ItemList)
create_salesperson_lists(all_sales_split)

Help John see who is working hard, and how much tips to pay out

John also wants to know how hard each employee was working so let’s tell him how many sales each person made. We can do this by checking how long each sales list is, using Python’s len() function.

print("The total number of Fred's sales is: " + str(len(FredSales)))
print("The total number of Nox's sales is: " + str(len(NoxiSales)))
print("The total number of Khatija's sales is: " + str(len(KhatijaSales)))

Finally, John wants to make sure he’s paying each person the tips they earned. We know from looking at the sales lists that the last thing each sales person wrote down was how much of a tip they made. In Python the first item in a list – as we said – is at address 0; because of something called negative indexing, the last item in that list will be at address -1. By using a negative index we can fetch the last element in a list even if we don’t know how long that list is, and tally up these values using a for statement.

Let’s create a function that takes a salesperson’s sales list as a parameter, and check the last item of each sale, each time adding the number we find to a running tips total.

def tip_calculator(sales_person_list):
Salesman_tip = 0
for x in sales_person_list:
tempstr = x[-1]
tempint = int(tempstr)
Salesman_tip += tempint
return Salesman_tip

Now we can call the function we just made, using each person’s sales list as a parameter. Print the result, and you’ll find out how much they made in tips.

FredTip = tip_calculator(FredSales)
NoxiTip = tip_calculator(NoxiSales)
KhatijaTip = tip_calculator(KhatijaSales)
print("The total tips earned by Fred were R" + str(FredTip))
print("The total tips earned by Noxi were R" + str(NoxiTip))
print("The total tips earned by Khatija were R" + str(KhatijaTip))

There you have it: using just the lessons learned in HyperionDev’s free trial, we’ve taken John’s messy note/text file and turned it into usable data that he can use to manage his business.

Of course, our free trial only teaches so much: to learn more advanced concepts and abilities – like being able to turn this simple code into an actual app John can use to manage his stall – you can sign up for the full bootcamp. Our bootcamps in web development, software engineering, and data science teach you practical skills for real-world applications like this. Best of all, you get your own personal mentor and frequent expert review of the code you write, all so you can graduate as a job-ready developer in less than 6 months.


Find out more about our bootcamps here, and sign up for your free trial today.

[Tutorial] Build a Python Decoder with HyperionDev’s Free Trial

Tutorials

[Tutorial] Build a Python Decoder with HyperionDev’s Free Trial

You don’t need to be an expert programmer to start making your own fun, silly, or quirky programs. Our Free Trial gives you what you need to get started on the journey to become a professional programmer – and with just the essentials it teaches, you can make your own secret message decoder in Python.

In this blog – a follow-on from our last Free Trial Beginner Coding Tutorial – we look at the kinds of programs that a newcomer to coding can make using just our free trial and the programming essentials. This time, we’re making a fun secret encoder/decoder program in Python, to write and decipher secret messages using just the basics that are taught in our HyperionDev free trial.

Let’s begin!

Step 1: Set up what you’ll need

First off, you and your secret accomplice need to decide on a secret codebook, which you’ll use to encrypt or decipher the meanings of your messages. We can do this by creating two lists: one with the normal alphabet, and another with random letters in a jumbled-up order. Remember that a list is just a group of variables combined in a single collection through the use of square brackets. We’ll use these two lists to create a secret codebook.

Let’s declare these lists in our program.

normal = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", " "]
secret = ["D", "N", "B", "M", "I", "F", "L", "Q", "H", "Y", "R", "P", "E", "V", "A", "W", "Z", "O", "K", "J", "T", "X", "U", "C", "S", "G", " "]

Now, lists are useful, but it can be clunky to iterate through a list to find one character, grab its index, and then fetch an address from a second list. It would be so much easier if each letter of the alphabet had a corresponding partner value… Luckily, Python does this, with a really useful thing called dictionaries! Dictionaries – denoted by curly brackets “{}” – pair up two variables in a particular manner. It’s simpler to just go through a dictionary, find the letter we’re looking for (which will be the ‘key’ in the dictionary) and return its associated value.

Let’s combine our alphabet list with our secret list into one single dictionary. We can do this by using a ‘for’ statement that creates key-value pairs by cycling through a zip object that combines both lists into one object. A ‘for’ statement is a simple loop that allows you to run a certain function or do something with each element in a given collection of data.

Of course, we’ll need to create two dictionaries, one to encrypt normal letters, and another to decrypt the secret letters.

EncryptionKeybase = {key:value for key, value in zip(normal, secret)}
DecoderKeybase = {key:value for key, value in zip(secret, normal)}

Step 2: Write your code for encrypting or decoding

Now that we have our secret codebook, let’s create the functions that will encrypt or decode your message.

We have a few options here. We could make a loop that runs twice to check each letter in each key-value assignment, however, running two separate loops can be confusing to keep track of, so it’s much easier to just run one single ‘for’ statement to iterate through the message the user types in and return the value from the appropriate corresponding key (here, a letter of the alphabet).

We will create two functions that we’ll use to encrypt or decode our secret message.

Both of these functions will receive a string as a parameter, here named “message”. We’ll get this “message” from the user later.

Step 3: Make sure you’re handling exceptions and errors

Now, before we type in any code, we have to imagine what kinds of messages the user might try to send – does our code account for all scenarios? What happens if they type a number, or a special character? We need to make sure that our code won’t miss these outliers, or break if the user includes them in their message. Also, the keys in a dictionary are case-sensitive, so let’s ensure that our code converts the inputted messaging into uppercase to match the list items we made at the very beginning. To do this, we’ll use an ‘if’ statement to check if the message is in the uppercase, with Python’s .isupper() method. If this returns as false, we make the inputted message uppercase.

def encrypt_message(message):
uppermessage = ""
if message.isupper() != True:
uppermessage = message.upper()
elif message.isupper() == True:
uppermessage = message

To prevent the code breaking when someone adds punctuation, special characters, or numbers, we’ll put the encryption and decoding function in a try-except block that will create a string out of whatever is throwing up an error, and insert it into the string that it sends back to us.

We use a simple ‘for’ statement in this bit of code, set to the length of the message the user typed in with Python’s handy range-length method, range(len()). That way, we don’t need to predict or restrict message lengths.

printedmessage = ""
for x in range(len(uppermessage)):
try:
printedmessage += EncryptionKeybase.get(uppermessage[x], 0)
except TypeError:
tempstring = str(uppermessage[x])
printedmessage += tempstring
return printedmessage

Let’s copy the code we wrote for the encryption function, and change it around so we can decode messages using our Decoder codebook.

def decode_message(message):
uppermessage = ""
if message.isupper() != True:
uppermessage = message.upper()
elif message.isupper() == True:
uppermessage = message
printedmessage = ""
for x in range(len(uppermessage)):
try:
printedmessage += DecoderKeybase.get(uppermessage[x], 0)
except TypeError:
tempstring = str(uppermessage[x])
printedmessage += tempstring
return printedmessage

There are ‘simpler’ ways to do this, for example you could use a loop inside of a loop to check each letter in the separate lists to return a result. However, that would be far less efficient. Always look at your code and think about how you could rewrite it to be shorter, simpler, and more efficient (that’s called refactoring).

Step 4: Create the main program code that uses what you’ve written

Now that we have the main body of our code, let’s write the main program that will use our decoding and encryption functions.

It would be irritating to have to restart the program every time you encrypt or decode one message, so let’s make the main body of our program work in a while loop that runs as long as we are sending messages. We can do this by using a boolean, which is a data type in Python which can be either ‘True’ or ‘False’. The program runs for as long our boolean value is set to ‘True’; as soon as ‘sending messages’ is changed to be = ‘False’, the program ends.

sending_secret_messages = True
print("Welcome to the secret messaging app. Decode and encrypt your secret messages here!\n")
while sending_secret_messages:

Now that the program is running, let’s get the message we want to encrypt or decode from the user.

message = input('\nType in the message you would like to be encrypted or decoded: ')

Let’s ask the user if they want to encrypt or decode this message. We’ll store their answer as a string, and then use an ‘if’ statement to determine which of our functions – decode or encrypt – to call.

encrypt_or_decode = input('\nWould you like to ENCRYPT or DECODE the message? [E/D]: ')

Now let’s make that ‘if’ statement. I’ve written in a version that checks both the uppercase and lowercase versions of their answer – you wouldn’t want to have a program fail just because you didn’t press caps lock!

This first piece of code will encrypt the user’s inputted message:

if encrypt_or_decode == "E" or encrypt_or_decode == "e":
print("\nYour encrypted message is:")
encrypted_message = encrypt_message(message)
print(encrypted_message)

And the second ‘elif’ statement will decode it:

elif encrypt_or_decode == "D" or encrypt_or_decode == "d":
print("\nYour decoded message is:")
decoded_message = decode_message(message)
print(decoded_message)

We also have to make sure we’re taking into account a possible situation where the user types in something we didn’t expect. This last ‘else’ statement will print a message asking them to type in the correct command, and just re-run the code.

else:
print("Enter 'E' or 'D' to Encrypt or Decode a message.")
continue

Finally, we can ask the user if they’d like to exit the secret coding app after every message. If they don’t want to keep sending messages, our boolean ‘sending secret messages’ is set to false, breaking the while loop and ending our program.

keep_sending_messages = input('\nWould you like to decode/encrypt another message? Y/N: ')
if keep_sending_messages == 'n':
sending_secret_messages = False

—

That’s it! You now have a program that converts messages using Python’s dictionaries. Give it a run, and test it out on this message written below:

QSWIOHAVMIX HK KATJQIOV DFOHBD’K PDOLIKJ JIBQ IMTBDJHAV WOAXHMIO. HJ UDK FATVMIM HV 2012, DK D KEDPP LODKKOAAJK EAXIEIVJ AF BAEWTJIO KBHIVBI KJTMIVJK UAORHVL JAUDOMK D KHVLPI LADP: JA NTHPM DVM MIPHXIO NIJJIO JIBQVHBDP IMTBDJHAV FAO DVSAVI UQA UDVJIM JA PIDOV MHLHJDP PHJIODBS DVM WOALODEEHVL KRHPPK.

Try writing out your own codebook, or encrypting your own message! Are there any other applications you think this program could be used for?

And remember that this is just beginner code written using what is taught in our free trials. You’ll learn much more complex and elegant solutions on the actual bootcamp – but it goes to show that with a bit of experimentation and the beginner essentials, you can make fun, useful, or just plain silly programs to keep you entertained.

Our bootcamps take you from these beginner basics, and help you grow to be able to produce professional-grade code in just 3 to 6 months. We do this through specialised bootcamps that teach you real, practical skills in web development, software engineering, or data science. While you study online, or at our campuses in Joburg and Cape Town, you’ll receive 1-on-1 mentor support from a coding expert to ensure that the code you’re writing is of the standard tech recruiters are looking for.

Sign up today for your free trial.

Full copy of code:

https://repl.it/@wheresmattynow/SecretCoderNDecoder#main.py

[Tutorial] Build Your Own Python Game – Try HyperionDev Free

Tutorials

[Tutorial] Build Your Own Python Game – Try HyperionDev Free

You don’t need years of previous experience coding to get the basics and start making your very own code. Our Free Trial gives you what you need to get started on the journey to become a professional programmer - and it certainly gives you enough info to make your very own short game.

Free trials have a bad rap. Often, the interesting and useful aspects of a product are hidden behind a paywall, with free content being merely surface level nonsense that’s aimed at luring you into paying a fee to get the information that’s actually of value.

That’s why our free trial is designed to get you started with useful basics and key beginner’s insights, so that you can get what you need to start your journey to becoming a fully-fledged professional programmer. It gives you a beginner’s guide to programming language essentials that let you get a feel for coding and prepare you for our intensive bootcamps which give you job-ready skills in three to six months.

However, a big question that we get a lot is, “is the HyperionDev free trial actually useful?”

The answer (from a copywriter with no professional experience in coding): yes!

Using just the information made available in the introductory lessons in the Software Engineer Bootcamp free trial, including introductions to variables, such as integers and boolean, and conventions that deal with turning numbers into printable strings, I was able to make a simple game for me and my office colleagues to play and compete in. It’s a very short piece of work, requiring only 40 lines of code to work properly.

The game is as simple as it is catchy, and you’ve probably played it in a junior school playground: try to guess if an unknown number the other player (here, the computer) makes is higher or lower than the last one it told you.

I chose Python because of its ease of use and its wide popularity, among other reasons. I also want to learn a language that allows me the freedom to do many different things from one platform, which Python allows as well. It’s an all-round strong programming language that’s perfectly suited to beginners and advanced coders alike.

Want to see how you can make it for yourself? A full version of the game code can be seen here, but we’ll also walk you through the process of understanding how the game itself was crafted line by line, so that you can make the game yourself and see how it works.

How to make the game

We’ll be making all our code in Repl.it. This is an online coding platform that allows you to code in multiple languages without installing a development kit onto your computer, or even without needing a registered account. Plus it’s also the embedded tool we use in all our free trial tasks.

You can follow along and paste or write the code yourself into your repl coding window.

First, the game will need to generate random numbers, print in colour for win/loss messages, and exit the game when we lose and don’t want to play again. Also, when you use a print command, it will print everything at once, so a short pause between print messages will give the player time to read.

Imagine you want to write a short letter on a piece of paper with a blue pen. It saves you time and effort to just get a blue pen from your storage room, rather than bring all your paints, oils, hammers, and the kitchen sink. Python can do a lot, efficiently and quickly, by doing only what you need it to, rather than load every single library/package in existence. So to do all the things mentioned above, we’ll need to import certain packages:

from random import randint
from termcolor import colored
import sys
import time

Now let’s make the actual game. We start by telling the player what the game is about and how to play. They play by entering their guess, “up” or “u” and “down” or “d” (we want it to be simple to play). Instinctively, you’d want to use the “up” and “down” arrows of your keyboard, but that kind of functionality (namely, a key listener) is of an intermediate level that you’d be able to learn during your HyperionDev bootcamp.

print("Welcome to UP or DOWN!")
time.sleep(1)
print("For this game, you'll guess if a computer's secret, random number is higher or lower than the last random number it told you.")
time.sleep(1)
print("For your answers, you can type 'up' or 'u', and 'down' or 'd'.")
time.sleep(1)

In this game, the computer will generate a random number and tell us what it is. It will then generate a second random number without showing it, and we have to guess whether this number is higher “up” or lower “down” than the first number.

If you guess correctly, the computer will tell you you were right, print what the number was, and keep score of your number of correct guesses in a row. It will then come up with another random number. Again, you have to guess whether this is higher or lower than the last number you guessed. Repeat this until the user guesses incorrectly.

If you lose the game, the computer tells you, ends the game, and then asks if you want to play again (after all, it’s irritating to have to re-run the game every time you lose!).

To run this game we will have a loop that runs while you’re still playing the game: ie, while playing is ‘true’, the game will run. In programming, a loop is a sequence of commands or actions that is continually repeated until a certain condition is met. Without a loop, we would have to write out the code dozens of times so that the code runs again each time the user wins; but with a loop, we can write the code once and use it repeatedly until the user loses. ‘True’ and ‘false’ values mean that we’re using a boolean, a variable type that can only have these two values. We can change this ‘true’ to ‘false’ later on to quit the game.

playing = True
while playing:

Inside that loop, we’ll have a loop that dictates the game mechanism itself.

This second loop uses a different method (which I used to practice different ways of running loops): you set a value and run the loop while that value is higher than a certain amount. If you lose, that value is decreased, which breaks the loop.

This is also the first time we’re playing the game, so we need to generate a random number between 0 and 1000 for the game, using the random number generator we imported in the opening lines of this program.

game = 1
startvalue = randint(0, 1000)
wincount = 0
while game > 0:

First of all we need the user to know what the first number the computer guessed is, so they can think about whether the new random number is probably higher or lower. As the HyperionDev Free Trial teaches you, you can’t just print a value that’s a number, you first have to turn it into a string, which we do with the str() function.

print("The base number is " + str(startvalue) + ("."))

The computer now makes a second, secret number, which we’ll call “guessvalue” (it’s good to call things specific names – if you use generic names like “number1” and “number2” it can be really difficult for later programs that use hundreds of numbers!).

guessvalue = randint(0, 1000)

Now we ask the user to type in their guess as to whether the secret number is higher or lower than the starting number. Remember to leave a space after the end of your sentence in quotation marks, so that the user can read what they’re typing.

answer = input("Up or down?: ")

Let’s check what their guess was. We’ll also include single-character answers like “u” and “d” to make the game quicker to play. The program checks which required answer the user enters, and then creates a ‘true’ or ‘false’ boolean depending on what answer you entered. If you enter “u”, and the secret number is higher than the starting number, then ‘check’ will be true. It will do the same for if you enter “d”, and the number is lower than the starting value.

if answer == "up" or answer == "u":
check = bool(guessvalue >= startvalue)
elif answer == "down" or answer == "d":
check = bool(guessvalue <= startvalue)

We want to make sure the game doesn’t crash if they don’t enter intended words. So here, if you don’t enter the exact game commands, it does nothing but start this loop again, keeping your current score and maintaining the last secret number (so you can still guess).

else:
print("You need to enter valid entry text to play this game.")
Continue

It needs to check if you’re right or wrong using the ‘true’ or ‘false’ we created for the “is this number higher than the starting number” IF statement we created. This is the meat of the game’s code.

if check:

We’re using a true/false value (a boolean) to check if you’re right. If you are correct (namely, if you guess “up”, and the secret number is higher than the starting value, or the opposite for “down”) the computer will add one to your score, tell you the secret number and make this the new starting point. The loop will then run again, coming up with another secret number that you have to guess is higher or lower than the last secret number. (Bonus – We’re also going to use our imported ‘color’ package to change the colour of the text so that you can make win messages green and lose messages red.)

wincount += 1
startvalue = guessvalue
print(colored('Wow you were right! ', 'green') + "That's " + str(wincount) + " correct guesses so far. Try again!")
time.sleep(1)

If you’re not right, then it’s gonna reduce the value we’re using to run our while loop that makes this game run. When this value decreases, the loop breaks, ending the game.

else:
game -=1

If you’re wrong, end the game and tell the person what the computer’s value was.

print(colored('You lost! ', 'red') + "You correctly guessed 'up or down' " + str(wincount) + " times!")
print("The computer's number was " + str(guessvalue))

Finally, we’ll end the game (if you lose, this is where you’ll end up) by asking the person if they want to play again. If they say no, the boolean-based loop we’re using for the game will break, and we’ll exit the game.

            playing_str = input('Would you like to play again? y/n: ')
if playing_str == 'n':
playing = False
print('GAME OVER')

Congrats, you now have a beginner-level game that uses a wide range of fundamental coding concepts! It’s harder than you think (the beauty of random numbers) – try to get to ten correct guesses in a row!

Full copy of code:

from random import randint
from termcolor import colored
import sys
import time
print("Welcome to UP or DOWN!")
time.sleep(1)
print("For this game, you'll guess if a computer's number is higher or lower than the last number it told you.")
time.sleep(1)
print("For your answers, you can type 'up' or 'u', and 'down' or 'd'.")
time.sleep(1)
playing = True
while playing:
game = 1
startvalue = randint(0, 1000)
wincount = 0
while game > 0:
print("The base number is " + str(startvalue) + ("."))
guessvalue = randint(0, 1000)
answer = input("Up or down?: ")
if answer == "up" or answer == "u":
check = bool(guessvalue >= startvalue)
elif answer == "down" or answer == "d":
check = bool(guessvalue <= startvalue)
else:
print("You need to enter valid entry text to play this game.")
continue
if check:
wincount += 1
startvalue = guessvalue
print(colored('Wow you were right! ', 'green') + "That's " + str(wincount) + " correct guesses so far. Try again!")
time.sleep(1)
else:
game -=1
print(colored('You lost! ', 'red') + "You correctly guessed 'up or down' " + str(wincount) + " times!")
print("The computer's number was " + str(guessvalue))
playing_str = input('Would you like to play again? y/n: ')
if playing_str == 'n':
playing = False
print('GAME OVER')

Go from beginner coder, to job-ready in six months or less

This code is beginner-level and isn’t fully optimised. However, that’s where our mentor-led bootcamp design comes in: some parts of this program were improved with hints and tips by HyperionDev’s mentors (the original version would have to be restarted every time you lost!). With a free trial and our mentor-guided support, you’d be able to create code that’s much cleaner than this: code that is industry-ready and up to the highest conventional coding standards.

If you’re curious about code, you can try it out yourself with one of our free trials, where you can get the basics and try your hand at a few practical code exercises – no previous experience necessary! HyperionDev offers online bootcamps in Full Stack Web Development, Data Science or Software Engineering. If online learning is not your thing, you could join a face-to-face Web Developer or Software Engineering course in Cape Town or Johannesburg. Start your new career in tech today.

[Tutorial] Building a responsive top navigation menu with HTML and CSS

Tutorials

[Tutorial] Building a responsive top navigation menu with HTML and CSS

A responsive top navigation menu is the cornerstone of a webpage. Here is tutorial that covers everything you need to know.

A responsive top navigation menu is the cornerstone of a webpage. Without it, we would just blindly navigate web pages to find what we want. That would increasingly become a problem when there are topics nested in sub-topics nested in sub-topics.

For example, you’re looking for a specific brand of laptop online, and you decide to visit the website of a particularly large store, that sells everything from furniture to clothing. You, however, don’t care about anything else besides the laptop. A “search” function could be useful to quickly find exactly what you are looking for. But what if you only know the vague details but don’t know the specific name of the laptop you want? A general category like “Tech and Gadgets” would be really useful in finding what you want. Enter the navbar….

When the word “navigation” or “navbar” is brought up in a conversation in the context of a web page, the picture that pops into your head is likely a top navigation or “topnav”. The reason for this is likely that most of the companies’ web-pages that we visit almost always include a topnav. They seem to pull it off so effortlessly and, most importantly, the experience across devices(Desktop, tablet and mobile) seems so smooth and uniform. The average user can have confidence that, for any given website, they can have an easy experience on almost any device. This is due to the “Responsiveness” factor. That, or the company has spent quite a hefty budget on building different views for different devices.

This tutorial is aimed at beginners to junior developers, who want to learn how to build a responsive top navigation menu and gain a strong grasp of the related concepts.

We will walk you through a specific implementation of the navbar, and you can further customise it from there.

Why not use a framework such as Bootstrap?

As a developer, you’ve probably heard of frameworks such as Bootstrap, which would have built-in, out of the box responsiveness, and can easily be tweaked for most of your purposes. However, we’re choosing to manually implement the responsiveness ourselves.

Some of the advantages of manually implementing it are:

  • You’d have more control on where to set your breakpoints (ie, the maximum places where the current view transitions into the next. e.g. 500px can be the maximum place where the mobile styling applies, before the tablet view is more appropriate). Related to this, you can add as much additional breakpoints as you want, wherever you want.
  • The learning curve is smoother, as you don’t need to learn a whole new framework. You’d just be using CSS.
  • There is no need to add the framework as an extra resource, which would cause extra overhead.
  • Your webpage would be distinctive from “Yet another bootstrap clone”.
  • Less cluttering of the html.

Some disadvantages of manually implementing navbar responsiveness would be:

  • It would likely take longer, as you’d have to spend more time implementing the views. With practice, this would be more and more reduced.
  • If you’re not as good with CSS to begin with, the final responsive product won’t look any better.
  • There is some additional complexity in the CSS.

What we’ll be using for the implementation:

  • Mobile-first approach
  • Font-awesome icons
  • jQuery (For brevity, you’re welcome to implement the solution in Vanilla JavaScript)

What the responsive top navigation menu will consist of:

  • A logo
  • The navigation links
  • A search-bar
  • A hamburger menu for the smaller views

Getting started

Before we begin, you’ll want your boilerplate code and links to font-awesome and jQuery set up:

‍

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Responsive navbar</title>
<!-- Font-awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css" integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ" crossorigin="anonymous" />
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<!-- Styling -->
<link rel="stylesheet" href="styles.css" />
<!-- Script -->
<script src="script.js"></script>
</head>
<body>
<!-- Navbar section -->
</body>
</html>

‍

I’ve generated this template using my text-editor (Visual-studio Code at this moment in time), but you can use what your text editor/IDE provides, or even type it from scratch. The first meta tag is particularly important, because it ensures the responsiveness applies to all devices. The other two links are CDN links I found on their official websites.

Next, we flesh out the HTML structure of the page:

<!-- Navbar section-->
<nav class="top_nav">
<logo><img src="logo_transparent.png" alt="" height="45px" /></logo><button id="hamburger"><i class="fas fa-bars"></i></button>
<ul id="nav_links">
<li><a href="">Home</a></li>
<li><a href="">Blog</a></li>
<li><a href="">Videos</a></li>
<li><a href="">About us</a></li>
<li><a href="">Contact</a></li>
</ul>
<div id="search_bar">
<input type="search" placeholder="search..." /><button><i class="fas fa-search"></i></button>
</div>
</nav>

Notice how we’re using icons for the hamburger menu button and the search bar, while making sure that each and every element is visible, and, as easily as possible, able to be uniquely selected. By now, we have:

Now that we have our basic skeleton setup, we can begin with the actual meat of the project: the different responsive views. We’ll split those views up into 3 sections, using a mobile-first approach.

Step 1: Mobile view

In general, mobile views consist of single-column layouts, and the navigation needs to be as unobtrusive as possible. Therefore, a common approach to the mobile view would be the hamburger menu, served as a dropdown list upon a user’s click. Also, since it’s a single-column layout, scrolling all the way towards the end of the page would take longer than if it was all in a compact, multi-column layout. So we’ll be making our navbar sticky, for easier access.

‍

/* Remove some default styling*/
* {
margin: 0;
padding: 0;
border: none;
}
.top_nav {
height: 50px; /* Give navbar fixed height */
background-color: black;
}
#nav_links,
#search_bar {
display: none;
background-color: rgba(0, 0, 0, 0.5); /* Transparent background */
padding: 10px;
}

Firstly, I’ve added a small reset, so that some of the default styling from the browser doesn’t interfere with how we want it to look. The basic idea here was to give the navbar a fixed height, while hiding the search bar and navlinks for now. I added the background colors for the sole purpose of making the different sections distinctive.

Next, we’re styling the navlinks:

#nav_links li a {
/* Remove underlines from links */
text-decoration: none;
color: white;
font-size: 26px;
}
#hamburger {
width: 30px;
height: 30px;
float: right;
margin: 10px;
font-size: 20px;
border-radius: 4px;
}
#search_bar input,
#search_bar button {
padding: 5px;
font-size: 20px;
border-radius: 4px;
}

The links themselves have typical styling: the removal of the underlines on the links, etc. For the hamburger button, we float it to the right. This will put it at the absolute right edge of the page, as there aren’t any obstructions. Then, we give it an absolute width and height of 30px and a margin of 10px. You could alternatively give it padding, instead of a width and height, but then the margin wouldn’t work as effectively. The margin is 10px right around because it will not only take it slightly away from the absolute edge of the page, but it will also vertically align the button! This is because the navbar itself has a height of 50px, so the 10px on top and the 10px on the right would give it some breathing space.

Finally, we added some styling to the search bar. I selected both the text field and the button for this. Notice that while we’ve added styling to the navlinks and search bar, they are still not visible!

Next, we add the code that implements the actual showing and hiding of the navlinks and search bar:

$(document).ready(function() { $("#hamburger").click(function() { // alternate between showing and hiding navbar $("#nav_links, #search_bar").toggle(1000); // alternate between bars and times $("#hamburger i").toggleClass("fa-bars").toggleClass("fa-times"); }); });

$(document).ready(function () {
$('#hamburger').click(function () {
// alternate between showing and hiding navbar
$('#nav_links, #search_bar').toggle(1000); // alternate between bars and times
$('#hamburger i').toggleClass('fa-bars').toggleClass('fa-times');
});
});

For this to work, make sure that you’ve properly linked jQuery before you implement this code. Line 1 is a function that contains a built-in event listener for when the DOM loads. Then, on line 3 we have a click event listener for the hamburger button. You’d notice that jQuery generally follows that format, where “$(selector).functionName()” comes with a callback function as a parameter.

Nevertheless, we continue to line 4, where we’re calling the toggle function on the navlinks and searchbar respectively (notice how the selector syntax is the same as with CSS). The toggle function will take turns to hide and show the selected items, with the parameter being how long it takes to show and hide it in milliseconds. So it takes one second to fade in and out.

Line 5 is changing the bars icon to the times (a cross) icon, to show which button to click to hide the menu again.

That’s all we need for the mobile view, and it should look something like this:

Step 2: Tablet view

The advantage of using a mobile-first approach, is that you are minimising the amount of code you would have to rewrite for the other types of views. All that needs to change is the size and layout of the content. Tablet views can still make use of a single-column layout. In order to make your navbar responsive, you would wrap your view-specific code in a responsive media query, which is a declaration of what styling to apply to a specific view:

/* Tablet view starts here */

@media screen and (min-width: 780px) {

}

Don’t let the syntax scare you. All it means is that “when the width of the page is at least 700px, apply the following styling”. Within the media query, you would add:

.top_nav {
display: grid;
grid-template-columns: 1fr 1fr 2fr;
color: blue;
}
#nav_links {
position: absolute;
top: 50px;
width: 100%;
}
#search_bar {
display: block;
background: none;
}

You could have skipped the tablet view in favour of the mobile view for medium devices, but I’ve decided to keep the search bar on top (largely because of the extra space provided due to the viewport being wider).

Now we have 3 columns in the top_nav itself. I’ve used CSS-grids to position them. You can alternatively use any of the other technologies that handles positioning (‘Flex-box’, in particular, would stand out as an awesome alternative).

Due to the ordering of the elements in the html, this would put the navlinks in the third column, instead of the search bar. So I’ve used ‘position: absolute’ to make sure that it is placed below the navbar when it appears. This also removes it from the natural ordering of the elements. Also, the width is set to 100% to span the width of the page.

For the search bar, we’re simply making it visible again, and this would make it automatically be the third grid-item as defined in the “.top_nav”.

By now, you’d notice that the hamburger button isn’t working as expected, because both the navlinks and search bar still fade away when clicked. We would need to detect the device width when it reaches the tablet view, and ensure that only the navlinks are being toggled.

So we would add an if-else-statement to the original script such as below:

$(document).ready(function () {
if (window.innerWidth <= 700) {
// For mobile view
$('#hamburger').click(function () {
$('#nav_links, #search_bar').slideToggle(1000);
//alternate between showing and hiding navbar
$('#hamburger i').toggleClass('fa-bars').toggleClass('fa-times'); //alternate bars and times
document.getElementById('nav_links').style.display = 'block';
});
} else {
// For tablet view and beyond
$('#hamburger').click(function () {
$('#nav_links').slideToggle(1000);
$('#hamburger i').toggleClass('fa-bars').toggleClass('fa-times');
});
}
});

This works because ‘window.innerWidth property’ holds the current width of the screen. By now you’d have something such as the below:

Now all that’s left is to round it off with the desktop view.

Step 3: Desktop view

Here, you’d use pretty similar code to the tablet view with one important difference (and a few less important differences):

The hamburger button itself will not be displayed, while the navlinks will. This is because the user would have a wide-enough screen for a proper multi-columned layout. The absence of the hamburger button and presence of the navlinks means that the navlinks will take up the extra column in the topnav’s layout code. Due to the natural ordering of the elements in the html code, the navlinks will be in the middle.

You’d also notice that the code for the navlinks would need some overriding, as the positioning was absolute in the tablet view. Also, the display would be set to ‘inline’ to keep with the general theme of making it fully horizontal.

I’ve added a simple hover effect just for some spice, and the code looks like the following:

/* Desktop view starts here */
@media screen and (min-width: 1200px) {
.top_nav {
display: grid;
grid-template-columns: 1fr 4fr 2fr;
}
#hamburger {
display: none;
}
#nav_links {
display: block;
position: relative;
top: 0;
width: 80%;
height: 30px;
}
#nav_links li {
display: inline;
margin-right: 20px;
}
#nav_links li a:hover {
border-bottom: 1px solid white;
}
}

Your final desktop view would look something like this:

Closing remarks

So by now you likely have a working responsive top navigation menu on your site. From here, you can try your hand at customising it to have a different layout, better animations and transitions, etc. You would also have enough knowledge about responsive media queries by now to customise and make just about any web page responsive. Just note that converting a non-responsive webpage can often be more difficult than starting from scratch, so tread carefully there as not to break it.

The source code can be found here.

Happy coding 🙂

This post was written by Ridhaa Cupido, HyperionDev mentor and code reviewer.

Python machine learning: Introduction to image classification

Tutorials

Python machine learning: Introduction to image classification

Build an image recognition classifier using machine learning and scikit-learn, a popular and well-documented Python framework.

This tutorial is an introduction to machine learning with scikit-learn (http://scikit-learn.org/), a popular and well-documented Python framework. We’ll be using Python 3 to build an image recognition classifier which accurately determines the house number displayed in images from Google Street View. You’ll need some programming skills to follow along, but we’ll be starting from the basics in terms of machine learning – no previous experience necessary.

So what is machine learning? It’s an area of artificial intelligence where algorithms are used to learn from data and improve their performance at given tasks. For example, if we previously had wanted to build a program which could distinguish between an image of the number 1 and an image of the number 2, we might have set up lots and lots of rules looking for straight lines vs curly lines, or a horizontal base vs a diagonal tip etc. What machine learning allows us to do instead, is feed an algorithm with many examples of images which have been labelled with the correct number. The algorithm then learns for itself which features of the image are distinguishing, and can make a prediction when faced with a new image it hasn’t seen before.

Typically for a machine learning algorithm to perform well, we need lots of examples in our dataset, and the task needs to be one which is solvable through finding predictive patterns. There are different types of tasks categorised in machine learning, one of which is a classification task. This simply means that we are aiming to predict one of several discrete classes (labels). An example of this could be predicting either yes or no, or predicting either red, green, or yellow. This is in contrast to regression, a different type of task which makes predictions on a continuous numerical scale – for example predicting the number of fraudulent credit card transactions.

The dataset

For this tutorial, we’ll be using a dataset from Stanford University (http://ufldl.stanford.edu/housenumbers). It contains images of house numbers taken from Google Street View. Each one has been cropped to 32×32 pixels in size, focussing on just the number. Some examples are shown below.

Source: http://ufldl.stanford.edu/housenumbers

There are a total of 531131 images in our dataset, and we will load them in as one 4D-matrix of shape 32 x 32 x 3 x 531131. This represents each 32×32 image in RGB format (so the 3 red, green, blue colour channels) for each of our 531131 images. We’ll be predicting the number shown in the image, from one of ten classes (0-9). Note that in this dataset the number 0 is represented by the label 10. The labels are stored in a 1D-matrix of shape 531131 x 1. You can check the dimensions of a matrix X at any time in your program using X.shape.

Although this tutorial focuses on just house numbers, the process we will be using can be applied to any kind of classification problem. Autonomous vehicles are a huge area of application for research in computer vision at the moment, and the self-driving cars being built will need to be able to interpret their camera feeds to determine traffic light colours, road signs, lane markings, and much more. With this in mind, at the end of the tutorial you can think about how to expand upon what you’ve developed here.

The set-up

To set up our project, first, let’s open our terminal and set up a new directory and navigate into it. This is where we’ll be saving our Python file and dataset.

mkdir sklearn-tutorial
cd sklearn-tutorial

We’ll need to install some requirements before compiling any code, which we can do using pip. If you haven’t used pip before, it’s a useful tool for easily installing Python libraries, which you can download here (https://pypi.python.org/pypi/pip). Once you’ve got pip up and running, execute the following command in your terminal:

pip install numpy scipy scikit-learn

We also need to download our dataset from http://ufldl.stanford.edu/housenumbers/extra_32x32.mat and save it in our working directory. This is a large dataset (1.3GB in size) so if you don’t have enough space on your computer, try this one http://ufldl.stanford.edu/housenumbers/train_32x32.mat (182MB), but expect worse results due to the reduced amount of data.

Finally, open up your favourite text editor or IDE and create a blank Python file in your directory. From here on we’ll be doing all our coding in just this file.

Feature processing

Now let’s begin! To understand the data we’re using, we can start by loading and viewing the image files. First we need to import three libraries:

import scipy.io

import numpy as np

import matplotlib.pyplot as plt

Then we can load the training dataset into a temporary variable train_data, which is a dictionary object. The dictionary contains two variables X and y. X is our 4D-matrix of images, and y a 1D-matrix of the corresponding labels. So to access the i-th image in our dataset we would be looking for X[:,:,:,i], and its label would be y[i]. Let’s do this for image 25.

# load our dataset
train_data = scipy.io.loadmat('extra_32x32.mat')

# extract the images and labels from the dictionary object
X = train_data['X']
y = train_data['y']

# view an image (e.g. 25) and print its corresponding label
img_index = 25
plt.imshow(X[:,:,:,img_index])
plt.show()
print(y[img_index])

* Note that if you’re working in a Jupyter notebook, you don’t need to call plt.show(). Instead use the inline function (%matplotlib inline) just once when you import matplotlib.

As you can see, we load up an image showing house number 3, and the console output from our printed label is also 3. You can change the index of the image (to any number between 0 and 531130) and check out different images and their labels if you like.

However, to use these images with a machine learning algorithm, we first need to vectorise them. This essentially involves stacking up the 3 dimensions of each image (the width x height x colour channels) to transform it into a 1D-matrix. This gives us our feature vector, although it’s worth noting that this is not really a feature vector in the usual sense. Features usually refer to some kind of quantification of a specific trait of the image, not just the raw pixels. Raw pixels can be used successfully in machine learning algorithms, but this is typical with more complex models such as convolutional neural networks, which can learn specific features themselves within their network of layers.

from sklearn.utils import shuffle

X = X.reshape(X.shape[0]*X.shape[1]*X.shape[2],X.shape[3]).T
y = y.reshape(y.shape[0],)
X, y = shuffle(X, y, random_state=42)

We’re also shuffling our data just to be sure there are no underlying distributions. The library we’ve used for this ensures that the index pairings between our images in X and their labels in y are maintained through the shuffling process. You can use the parameter random_state=42 if you want to replicate the results of this tutorial exactly.

Machine learning algorithms

Now that we have our feature vector X ready to go, we need to decide which machine learning algorithm to use. We don’t need to explicitly program an algorithm ourselves – luckily frameworks like sci-kit-learn do this for us. Scikit-learn offers a range of algorithms, with each one having different advantages and disadvantages. We won’t be going into the details of each, but it’s useful to think about the distinguishing elements of our image recognition task and how they relate to the choice of algorithm. This could include the amount of data we have, the type of problem we’re solving, the format of our output label etc.

If you don’t have any prior experience in machine learning, you can use this helpful cheat sheet to guide you in which algorithms to try out depending on your data. But, I would really recommend reading up and understanding how the algorithms work for yourself, if you plan to delve deeper into machine learning. This will be especially useful for tuning hyperparameters. Hyperparameters are input values for the algorithm which can tune its performance, for example, the maximum depth of a decision tree.

For now, we will be using a Random Forest approach with default hyperparameters. You can learn more about Random Forests here, but in brief they are a construction of multiple decision trees with an output that averages the results of individual trees to prevent fitting too closely to any one tree.

First we import the necessary library and then define our classifier:

from sklearn.ensemble import RandomForestClassifier

clf = RandomForestClassifier()
print(clf)

We can also print the classifier to the console to see the parameter settings used. Although we haven’t changed any from their default settings, it’s interesting to take a look at the options and you can experiment with tuning them at the end of the tutorial.

RandomForestClassifier(bootstrap=True, class_weight=None, criterion='gini',
max_depth=None, max_features='auto', max_leaf_nodes=None,
min_impurity_split=1e-07, min_samples_leaf=1,
min_samples_split=2, min_weight_fraction_leaf=0.0,
n_estimators=10, n_jobs=1, oob_score=False, random_state=None,
verbose=0, warm_start=False)

Training the model

We’re now ready to train and test our data. But before we do that, we need to split our total collection of images into two sets – one for training and one for testing. You can also add a third set for development/validation, which you can read more about here.

Keeping the testing set completely separate from the training set is important, because we need to be sure that the model will perform well in the real world. Once trained, it will have seen many example images of house numbers. We want to be sure that when presented with new images of numbers it hasn’t seen before, that it has actually learnt something from the training and can generalise that knowledge – not just remember the exact images it has already seen.

Usually, we use between 70-90% of the data for training, though this varies depending on the amount of data collected, and the type of model trained. For example, neural networks are often used with extremely large amounts of data and may sample 99% of the data for training. In this tutorial, we’ll go with 80%.

from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf.fit(X_train, y_train)

Because of our large dataset, and depending on your machine, this will likely take a little while to run. If you want to speed things up, you can train on less data by reducing the size of the dataset. The fewer images you use, the faster the process will train, but it will also reduce the accuracy of the model.

Test results

Now we’re ready to use our trained model to make predictions on new data:

from sklearn.metrics import accuracy_score

preds = clf.predict(X_test)
print("Accuracy:", accuracy_score(y_test,preds))

_________________________________________________

Accuracy: 0.760842347049

So our model has learnt how to classify house numbers from Google Street View with 76% accuracy simply by showing it a few hundred thousand examples. Given a baseline measure of 10% accuracy for random guessing, we’ve made significant progress. There’s still a lot of room for improvement here, but it’s a great result from a simple untuned learning algorithm on a real-world problem. You can even try going outside and creating a 32×32 image of your own house number to test on.

Extensions

What can you do next? How can you expand upon this tutorial?

If you’re interested in experimenting further within the scope of this tutorial, try training the model only on images of house numbers 0-8. Then test it on images of number 9. Do you think we can transfer the knowledge learnt to a new number? Why or why not?

You could also perform some error analysis on the classifier and find out which images it’s getting wrong. Try to spot patterns in the errors, figure out why it’s making mistakes, and think about what you can do to mitigate this. Take a look at the distribution of different digits in the dataset, and you’ll realise it’s not even. Is this having an effect on our results?

If you want to go further into the realms of image recognition, you could start by creating a classifier for more complex images of house numbers. This dataset contains uncropped images, which show the house number from afar, often with multiple digits. Next you could try to find more varied data sets to work with – perhaps identify traffic lights and determine their colour, or recognise different street signs. Finding or creating labelled datasets is the tricky part, but we’re not limited to just Street View images! There are a ton of resources available online so go ahead and see what you can build next.

A Github repo with the complete source code file for this project is available here.

If you want to read more pieces like this one, check out HyperionDev’s blog. You might, for example, be interested in reading an Introductory Python piece. You can also register for a free trial on HyperionDev’s Data Science Bootcamp, where you’ll learn about how to use Python in data wrangling, machine learning and more.

This piece was contributed by Ellie Birbeck.

Editor’s note: This was post was originally published 11 December 2017 and has been updated 18 February 2019.

Android HTTP requests made easy

Tutorials

Android HTTP requests made easy

This tutorial shows you how to make Android HTTP requests using two different methods: custom classes, and using a third-party library.

If you’ve ever had to make an HTTP network request in Android, you know what a pain it can be. Making Android HTTP requests usually involves writing a lot of boilerplate code. You could make things a bit easier by creating some custom classes, but it can still be tedious.

In this tutorial I will show you how to make network requests using two different methods. The first method involves creating custom classes, which will aid in code reusability. The second method involves adding a library called the Android Asynchronous Http Client by loopj. This library will greatly reduce the amount of code you will need to write.

In addition, we will be making a network request to the BitcoinAverage API which returns a JSON string. You will learn how to handle the JSON string, both with and without the use of the Android Asynchronous Http Client library.

This tutorial is for those who:

  • are comfortable with the Android development environment;
  • want to learn an easier way to make HTTP requests in Android.

Note: you should also be comfortable with Java and how Object-Orientation works in Java.

Adding permissions

This step is relevant to both methods. Navigate to your AndroidManifest.xml file and add the following permission before the <application> tag:

<uses-permission android:name="android.permission.INTERNET" />

Method 1: Creating custom classes

The first class we will be creating is called the RequestPackage class. This class will accept three important values when making HTTP requests. First, it will receive the URL. Next, it will receive the request method (POST or GET). Last, it will receive any values that the server might need (e.g. product_id). The request package will then be sent to the HttpManager class that we will create later.

Create a class called RequestPackage and add the following code to the class:

public class RequestPackage {
private String url;
private String method = "GET"; //method is set to GET by default
private Map<String, String> params = new HashMap<>();//This will hold any values
//that the server may require
// e.g. product_id
public String getUrl() {
return url;
}

public void setUrl(String url) {
this.url = url;
}

public String getMethod() {
return method;
}

public void setMethod(String method) {
this.method = method;
}

public Map<String, String> getParams() {
return params;
}

public void setParams(Map<String, String> params) {
this.params = params;
}

public void setParam(String key, String value) {
params.put(key, value); //adds a single value to the params member variable
}

//The method below is only called if the request method has been set to GET
//GET requests sends data in the url and it has to be encoded correctly in order
//for the server to understand the request. This method encodes the data in the
//params variable so that the server can understand the request

public String getEncodedParams() {
StringBuilder sb = new StringBuilder();
for (String key : params.keySet()) {
String value = null;
try {
value = URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}

if (sb.length() > 0) {
sb.append("&");
}
sb.append(key + "=" + value);
}
return sb.toString();
}
}

HttpManager

Next, we will create the HttpManager class. As mentioned earlier, the HttpManager receives the RequestPackage that we created in the previous section. The HttpManager is responsible for making the actual request and receiving the response from the server.

Create a class called HttpManager and add the following code to it:

public class HttpManager {

public static String getData(RequestPackage requestPackage) {

BufferedReader reader = null;
String uri = requestPackage.getUrl();

if (requestPackage.getMethod().equals("GET")) {
uri += "?" + requestPackage.getEncodedParams();
//As mentioned before, this only executes if the request method has been
//set to GET
}

try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod(requestPackage.getMethod());

if (requestPackage.getMethod().equals("POST")) {
con.setDoOutput(true);
OutputStreamWriter writer =
new OutputStreamWriter(con.getOutputStream());
writer.write(requestPackage.getEncodedParams());
writer.flush();
}

StringBuilder sb = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(con.getInputStream()));

String line;

while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}

return sb.toString();

} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
}

Putting it all together

Finally, we can use the code we just implemented. Here we will be putting everything together within the MainActivity. We will have to create a private class within the MainActivity and we will call it Downloader.

The Downloader class is an AsyncTask, which is required when making network requests in Android. If you try to make network requests outside an AsyncTask, your UI will freeze until it gets the HTTP response from the server.

Create an activity called MainActivity and add the following code:

public class MainActivity extends AppCompatActivity {

private TextView mPriceTextView;
private String BASE_URL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mPriceTextView = (TextView) findViewById(R.id.priceLabel);
Button btnUSD = (Button) findViewById(R.id.btnUSD);
Button btnZAR = (Button) findViewById(R.id.btnZAR);
Button btnAUD = (Button) findViewById(R.id.btnAUD);

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in USD
btnUSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "USD");
}
});

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in ZAR
btnZAR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "ZAR");
}
});

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in AUD
btnAUD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "AUD");
}
});
}

private void requestData(String url) {
RequestPackage requestPackage = new RequestPackage();
requestPackage.setMethod("GET");
requestPackage.setUrl(url);

Downloader downloader = new Downloader(); //Instantiation of the Async task
//that's defined below

downloader.execute(requestPackage);
}

private class Downloader extends AsyncTask<RequestPackage, String, String> {
@Override
protected String doInBackground(RequestPackage... params) {
return HttpManager.getData(params[0])
}

//The String that is returned in the doInBackground() method is sent to the
// onPostExecute() method below. The String should contain JSON data.
@Override
protected void onPostExecute(String result) {
try {
//We need to convert the string in result to a JSONObject
JSONObject jsonObject = new JSONObject(result);

//The "ask" value below is a field in the JSON Object that was
//retrieved from the BitcoinAverage API. It contains the current
//bitcoin price
String price = jsonObject.getString("ask");

//Now we can use the value in the mPriceTextView
mPriceTextView.setText(price);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}

And we are done. The amount of code we needed to write in order to get those three small pieces of information is a lot. It gets even worse if you want to use something like a RecyclerView. That would involve creating an adapter, which would significantly increase the amount of code we need to write.

In the next section, I will show you how to do the same thing by making use of the Android Asynchronous Http Client.

Method 2: Android Asynchronous HTTP Client

Navigate to the app/build.gradle file and enter the code below in the dependencies section:

dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}

Android Studio will ask if you would like to sync your project. You should do this and the dependencies will be downloaded.

Creating the MainActivity

Next, you will need to add the code below to the MainActivity:

public class MainActivity extends AppCompatActivity {

private TextView mPriceTextView;

private String BASE_URL = "https://apiv2.bitcoinaverage.com/indices/global/ticker/BTC";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

mPriceTextView = (TextView) findViewById(R.id.priceLabel);
Button btnUSD = (Button) findViewById(R.id.btnUSD);
Button btnZAR = (Button) findViewById(R.id.btnZAR);
Button btnAUD = (Button) findViewById(R.id.btnAUD);

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in USD
btnUSD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "USD");
}
});

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in ZAR
btnZAR.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "ZAR");
}
});

//When clicking on this button, the bitcoin price is displayed in the
//mPriceTextView in AUD
btnAUD.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
requestData(BASE_URL + "AUD");
}
});
}

private void requestData(String url) {
//Everything below is part of the Android Asynchronous HTTP Client

AsyncHttpClient client = new AsyncHttpClient();

client.get(url, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
// called when response HTTP status is "200 OK"
Log.d("Bitcoin", "JSON: " + response.toString());

try {

//The "ask" value below is a field in the JSON Object that was
//retrieved from the BitcoinAverage API. It contains the current
//bitcoin price

String price = response.getString("ask");

//Now we can use the value in the mPriceTextView

mPriceTextView.setText(price);

} catch (Exception e) {

Log.e("Bitcoin", e.toString());

}

}

@Override
public void onFailure(int statusCode, Header[] headers, Throwable e,
JSONObject response) {

// called when response HTTP status is "4XX" (eg. 401, 403, 404)

Log.d("Bitcoin", "Request fail! Status code: " + statusCode);
Log.d("Bitcoin", "Fail response: " + response);
Log.e("ERROR", e.toString());

Toast.makeText(MainActivity.this, "Request Failed",
Toast.LENGTH_SHORT).show();
}
});
}
}

Run your app and, voila, you’re done.

Conclusion

Well done! You have completed this tutorial. As you can see, the amount of code needed when working with the Android Asynchronous Http Client is far less than making HTTP requests using no library.

You now have a choice to make: do you prefer method 1 or method 2?

To find out more about the Android Asynchronous Http Client, please visit: http://loopj.com/android-async-http/

To view and/or clone a similar project to the one in this tutorial – that also uses the Android Asynchronous Http Client – please visit: https://github.com/londonappbrewery/bitcoin-ticker-android-citispy

To find out more about the BitcoinAverage API, please visit: https://bitcoinaverage.com/

Find out more about our Certified Mobile Developer Bootcamp. You will cover the following modules: Java Programming Essentials, Introduction to Mobile Development and Advanced Mobile Developer.

This article was contributed by Yusuf Isaacs.

Editor’s note: This was post was originally published November 14th, 2017 and has been updated February 18th, 2019.

CSS tutorial 3: colour values

Tutorials

CSS tutorial 3: colour values

This CSS tutorial will show you how the different colour values work when styling your web page, covering RGB, HEX & HSL values, as well as saturation & lightness.

Cascading Style Sheets allow you to set the colour of your website text, background and borders. This CSS tutorial will show you how the different colour values work, and how to apply them. We’ll cover RGB, HEX and HSL values, as well as saturation and lightness. Understanding colour values will help you to enhance the appearance of the websites you build, and follow your clients’ brand identity.

A quick note before we get started: When coding CSS colours, always use the USA spelling, i.e. color. Whether you use UK/ SA or US spelling standards in your text will depend on your client’s preference.

RGB values

RGB stands for Red, Green and Blue – the three primary colours for web and digital design. RGB value indicates the red, green and blue intensity that make up a specific colour. Each of these three intensity values sits on a scale of 0 to 255 – 0 being the lowest intensity, and 255 being the highest.

As an example, set up a simple HTML folder and document as you have done in previous tutorials. Enter the following code, with two short paragraphs of “dummy text”, as follows:

<!DOCTYPE html>
<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>
<h1>My CSS Colour Value Test</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</body>
</html>

When you view your web page in the browser, it will look like this:

CSS tutorial

Now, you can add a style to each heading and paragraph in your document. Your code must appear in the opening tag of the text you want to style.

Add a different RGB colour value to your heading and both paragraphs, as follows:

<!DOCTYPE html>

<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>

<h1 style="color:rgb(255, 0, 0);">My CSS Colour Value Test</h1>

<p style="color:rgb(0, 255, 0);">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>

<p style="color:rgb(0, 0, 255);">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>

</body>
</html>

When you refresh your browser, you’ll see the changes reflected in the text.

CSS tutorial

See more RGB values here for future reference.

HEX values

HEX or hexadecimal values sit on a scale from from 00 to FF, with 00 being the darkest and FF being the lightest (e.g. the three primary colours red, green and blue combine to make “white light”).

The code is known as a hex triplet, representing three separate RGB values that specify the intensity of the component colors: (#RRGGBB). The code begins with a hash sign (#) followed by six hex values, or three pairs of hex values.

For example, to code the colour black, you would use the HEX code #000000 which is the equivalent of the RGB code (0, 0, 0). The colour white would have a HEX value of #FFFFFF, the equivalent of RGB (255, 255, 255).

Similarly, to code the colour red, you would use the HEX code #FF0000. The RGB value is (255,0,0). Green would be #00FF00 (0, 255, 0) and blue would be coded as #0000FF (0, 0, 255).

Edit your code to include HEX values instead of RGB values, as follows:

<!DOCTYPE html>
<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>
<h1 style="color:#00FF00"">My CSS Colour Value Test</h1>
<p style="color:#0000FF"">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p style="color:#FF0000">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</body>
</html>

Your refreshed web page will reflect the colour changes.

CSS tutorial


These are quite simple examples, but when you’re looking for a very specific colour, you can use a colour picker tool to find the code for the perfect shade.

HSL values

HSL stands for Hue, Saturation and Lightness.

  • Hue is a degree of colour on the colour wheel, which goes from 0 to 360 degrees. On the colour wheel, 0 is red, 120 is green and 240 is blue.
  • Saturation can also be described as the intensity of a colour. It is written as a percentage value: 100% is pure, fully saturated colour. 50% is a shade of grey; the colour is half as intense but still visible. 0% is completely greyed out, meaning the colour is no longer visible.
  • Lightness refers to how much light you want to give a colour. It is also written as a percentage, with 0% being black (no light), 100% being white (full lightness), and 50% sitting halfway in between at neither light nor dark.

So for example, a fully saturated shade of blue would be coded using the following HSL value: (240, 100%, 50%).

Edit your HTML page to include three different shades of blue, with different levels of saturation and lightness:

<!DOCTYPE html>
<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>
<h1 style="color:hsl(240, 100%, 50%)">My CSS Colour Value Test</h1>
<p style="color:hsl(240, 50%, 50%)">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p style="color:hsl(240, 25%, 85%)">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</body>
</html>

Your refreshed page will show the three different shades of blue:

CSS tutorial

For easy future reference, you can check out this list of HSL values online.

Background colour

You can also set the background color for HTML elements, using the syntax background-color.

Add three different background colours to your code. Use one RGB value, one HEX code and one HSL value.

<!DOCTYPE html>
<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>
<h1 style="background-color:rgb(255, 50, 100);">My CSS Colour Value Test</h1>
<p style="background-color:#F0F0F0;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
<p style="background-color:hsl(255, 40%, 70%);">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.</p>
</body>
</html>

You will see the background colours have been altered once you refresh your web page:

CSS tutorial

Background colours and text colours can be written using RGB, HEX and HSL codes, but there is also a variety of pre-defined CSS colour names readily available to use. Here are some existing examples, which you can add to your headings, paragraphs and backgrounds:

<h1 style="background-color:Orange;">Orange</h1>
<p style="background-color:MediumSeaGreen;">MediumSeaGreen</p>
<h1 style="color:SlateBlue;">SlateBlue</h1>
<p style="background-color:Violet;">Violet</p>

You can see an extensive list of pre-defined colour names and codes here.

Take your CSS knowledge further

If you’re looking to apply your knowledge of HTML and CSS to a professional coding career, you might be interested in registering for an online web developer bootcamp. These online courses can be completed in just six months, with qualified mentors to make your learning journey easier and more rewarding.

CSS tutorial 2: internal, external & multiple style sheets

Tutorials

CSS tutorial 2: internal, external & multiple style sheets

This CSS tutorial will cover the key differences between internal, external and multiple style sheets, as well as how to create them.

In our previous CSS tutorial, we introduced the concept of Cascading Style Sheets and how they can be used to change and enhance the appearance of HTML web pages. This tutorial will cover the key differences between internal, external and multiple style sheets, as well as how to create them.

Internal style sheets

An internal style sheet is included directly in an HTML document. You would use internal style sheets in cases where you want to specify styles that apply to one web page only; for example, if one page has a unique visual style that’s different to the rest of your site.

Internal CSS code must be placed in the <head> section of the page you want to style. It must be enclosed between <style> and </style> tags.

To see an example, create a new folder called css-test, and set up a new HTML index page with the following code:

<!DOCTYPE html>

<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>

<h1>My CSS test</h1>

<p>Text goes here</p>

<p>Text goes here</p>

</body>
</html>

When viewed in the browser, your web page will appear with no styling, as follows:

CSS tutorial

Now add the following internal CSS code after the opening <head> tag:

<style>
body {
background-color: gray;
}

h1 {
color: green;
margin-left: 40px;
}
</style>
CSS tutorial

Save the document and refresh your page, and you’ll see the style has been applied.

CSS tutorial

Note: When using an internal style sheet for a particular page, you won’t be able to refer to that stylesheet from any other page.

An inline style is a piece of internal code you can use to narrow it down even further, and apply a unique style for a single element rather than a single page.

To use inline styles, you would add the style attribute containing the CSS property to the relevant element.

For example, to make visual changes to the <h1> element you would add the below code inside the <h1> opening tag.

<h1 style="color:blue;margin-left:150px;">My CSS Test</h1>
CSS tutorial

The element will reflect this style when you save and refresh:

CSS tutorial

External style sheets

An external style sheet is one that is created externally to the HTML document, and is “attached” to the document using code. This is used when you want to allow a single style sheet to control the appearance of multiple documents.

You can change the look of an entire website by editing just one file. This helps to save development time, download time and server space.

An external style sheet file only contains CSS syntax, with no document content or elements. You would use selectors, which were covered in the previous CSS tutorial, to specify what styles attach to which parts of the document.

Every HTML page must include a reference to the external style sheet file, which must be placed inside the <link> element, within the <head> section.

As an example, remove all the internal CSS code from your index page. The styling of the page will be removed.

Then, create and save a style.css file within your folder as you did in CSS tutorial 1.

CSS tutorial

Add this code to the CSS file:

body {
background-color: gray;
}

h1 {
color: green;
margin-left: 40px;
}

Then, apply this code to your HTML file that will link it to the CSS file:

<link rel="stylesheet" href="style.css">
CSS tutorial

When you save and refresh, you will see that the style is once again reflected on the page, this time using an external style sheet setup instead of an internal one.

CSS tutorial

Multiple style sheets

What happens in cases where one site has multiple style sheets? If some properties have been defined for the same selector or element in multiple different style sheets, the value from the last-read style sheet will be used.

So, say that an external style sheet states that the style for the <h1> element should be color:blue, while an internal style sheet states that the style for the same <h1> element should be color:green.

If the internal style is defined before the link to the external style sheet, the <h1> element will be appear as blue, as per the external code. On the other hand, if the internal style is defined after the link to the external style sheet, the <h1> element will follow the internal style sheet code and appear as green.

Using multiple CSS files instead of one big file can help you to keep things organised when working on a large site with a variety of style requirements. For example, you might want to style one website for multiple devices including mobile, and applying the different styles to separate CSS files can help to keep things tidy.

As a developer using multiple style sheets, it’s best practice to use different classes or id names in different CSS files, otherwise it will default to whichever was declared latest.

Find out more

Are you ready to step up your CSS game? Take a look at an online developer bootcamp, and enjoy the benefits of mentor-lead online learning at your own pace.

CSS tutorial 1: introduction and syntax

Tutorials

CSS tutorial 1: introduction and syntax

This CSS tutorial will introduce you to the concept of Cascading Style Sheets and CSS syntax, and explain how CSS can make coding that much easier for you.

This CSS tutorial will introduce you to the concept of Cascading Style Sheets, and how this styling language can make coding that much easier. Before beginning this tutorial, we recommend that you check out our HTML tutorial series. HTML and CSS work hand in hand, so understanding HTML is essential to getting the most out of CSS.

What is CSS?

CSS stands for Cascading Style Sheets. It’s a styling language that’s used to determine the visual presentation of a web page or document that’s been written in a markup language, such as HTML. CSS is used to define the layout and design of the HTML elements, and also determines the variations in display for a range of different screen sizes and devices.

Why use CSS?

CSS was created to solve a significant problem with HTML and to make life easier for developers. HTML was originally created to describe the content of a web page, not to format the content or apply styles to it. However, in later versions of HTML (specifically 3.2), new tags and attributes were added to define visual elements such as fonts and colours. This turned web development into a long, cumbersome and costly process, as coders were expected to add this visual information to every single page of a website. The World Wide Web Consortium (W3C) developed CSS as an answer to this issue, effectively removing the need for style formatting in HTML.

When working in CSS, you will typically save the style definitions in external .css style sheet files. This allows you to change the appearance of an entire website by simply editing one file. In other words, understanding CSS will save you a great deal of time and hassle as a developer.

CSS syntax

CSS code is made up of rule-sets. A CSS rule-set consists of two main parts: a selector and a declaration block.

Selector: The selector indicates the HTML element you want to style. CSS selectors are used to “find” or select HTML elements.

Declaration: The declaration block contains one or more declarations (separated by semicolons), and each of these declarations includes a CSS property name and a value (separated by a colon).

Property: The property is the part of the element’s appearance that you want to change; for example, the size, alignment, font, colour, and so on.

Value: The value describes what you want the property to look like; this is where you would specify that you want to change a colour to blue, or the text size to 12px, and so on.

Note that a CSS declaration must always end with a semicolon, and declaration blocks must be enclosed in curly brackets or braces: { and }.

CSS in action

To create a test CSS document, we first need to create a simple test HTML document. Before beginning, we do recommend that you go through our HTML tutorial and get to grips with the basics of Hyper Text Markup Language.

Open your text editor (like Notepad++) and add some simple HTML code to the document as follows:

<!DOCTYPE html>

<html>
<head>
<title>Learning How To Use CSS</title>
</head>
<body>

<h1>This is my CSS test</h1>

<p>This is paragraph one.</p>

<p>This is paragraph two.</p>

</body>
</html>

Create a new folder and name it “css-test”, then save your file in that folder, as “index.html”.

Open the HTML file in your browser, and it should appear as follows:

CSS tutorial

Now that we have our basic HTML file set up, let’s say we want to use CSS to change the appearance of the page heading. We want to change the colour to green, the font size to 20px, and the alignment to centred. Those are three properties that we want to add to the heading, each with its own value; so we will need three declarations in our declaration block.

In this case, the rule-set would be made up as follows:

  • h1 is the selector – the HTML element that we want to style.
  • The first declaration in the declaration block will be color:green; with color being the property and green being the value.
  • The second declaration in the declaration block will be font-size:20px; with font-size being the property and 20px being the value.
  • The third declaration in the declaration block will be text-align:center; with text-align being the property and center being the value.

Tip: Remember, properties and values are separated by a semi-colon.

To set this up, open up a new document in your text editor, and add the following code:

h1 {
color: green;
font-size: 20px;
text-align: center;
}

Now, save the document in your css-test folder, using the file name style and the extension .css – your style.css document should now appear in the folder with the index.html document.

CSS tutorial

The next step is to link the CSS file and the HTML file together – your CSS code can’t work its magic unless you tell the browser to load the stylesheet along with the HTML page.

To link the files, go back to your HTML document and add the following code, underneath the page title and above the </head> tag:

<link rel="stylesheet" href="style.css">

This code directly links to the saved file name.

CSS tutorial

Save the document and refresh the web page in your browser. You should see that the three visual changes have been implemented, and your page heading now appears in green, in the specified font size, aligned in the middle.

CSS tutorial

Different types of selectors

We mentioned before that CSS selectors are used to select HTML elements. Selectors can do this in a variety of different ways, based on the element’s name, id, class, attribute, etc. Let’s look in-depth at a few different types of CSS selectors you might use:

Element selector: Selects elements based on the element name. So for example, if you want to change all paragraphs on a page to blue, you can use the following code in your CSS file:

p {
color: blue;
}
CSS tutorial

All <p> elements in your HTML file will be selected, and will appear in blue. This saves you the hassle of having to apply code to every paragraph separately.

CSS tutorial

id selector: Selects a specific element based on its unique id attribute.

The id of an element should be unique within a page, so the id selector is used to select one unique element.

To select an element with a specific id, you would write a hash (#) character, followed by the id of that element.

For example, if you had one paragraph on the site that you wanted to style, without changing the others, you would give it an id attribute like id=”para1″ and begin your CSS rule-set code with #para1.

For example:

#para1 {
text-align: center;
}

Class selector: Selects elements with a specific class attribute.

To select elements with a specific class, you would write a period (.) character, followed by the name of that class.

For example, if you wanted to style all left-aligned paragraphs, you would give them the class attribute class=”left” and begin your CSS rule-set with .left.

You can group selectors together in your CSS document to minimise code, and separate them with commas.

For example:

.center {
color: yellow;
}

Ready to learn more?

In our next CSS tutorial, we’ll look at how to set up internal, external and multiple style sheets. If you’re interested in delving deeper into the world of HTML and CSS, sign up for a Web Developer Bootcamp for a convenient online learning experience.

HTML beginner tutorial 4: putting it all together

Tutorials

HTML beginner tutorial 4: putting it all together

The fourth HTML beginner tutorial in a series from HyperionDev will show you how to put together everything you have learned, to create your first HTML website.

In our HTML beginner tutorial series, we’ve covered the basics of creating a website using HTML code. We’ve talked about tags, attributes and elements, shown you how to set up headings and paragraphs, discussed images and links, and even touched on how to create forms and tables.

Here is a recap of the concepts covered in the past three tutorials:

General:

  • HTML stands for Hyper Text Markup Language, the standard markup language used by developers to create web pages.
  • HTML is typically used in conjunction with JavaScript and Cascading Style Sheets (CSS).
  • HTML files are simple text files. You can write HTML code using a text editor like Notepad++ or Wordpad.
  • HTML files must be saved as plain text, with the extension “.html”.

Tags:

Tags define the basic structure of your HTML document, surrounding the content in your document and applying meaning to that content. Tags can be used to define words, lines, paragraphs, or even an entire document.

Opening tags appear between these symbols: < > and closing tags appear between these symbols </ >.

Types of tags commonly used in HTML:

  • The <!DOCTYPE html> tag is a document type declaration, which tells the browser which type of HTML you’re using.
  • The <html></html> tag tells the browser that everything between those tags is an HTML document.
  • The <head></head> and <title></title> tags define the title of your document.
  • The <body></body> tag defines the main content of the document.
  • The tags <h1></h1> to <h6></h6> are used to define headings, with <h1> being the most important and <h6> being the least important.
  • The <p></p> tag defines a paragraph of text.
  • The <a></a> tag is used to define a link.
  • The <img> tag is used to define an HTML image. There is no closing tag needed for the <img> tag.

Attributes:

Attributes are extra bits of information that you can add inside opening tags, contained within quotation marks.

Tags with attributes are written in the format: <tag attribute=”value”>Text</tag>. Attributes usually come in name and value pairs, for example: name=”value”.

For example, an image with size attributes added to define its width and height would be coded as follows:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2018/10/Blog-Day-Life-HyperionDev-Student.jpg" width="450" height="200">

Types of attributes commonly used in HTML:

  • Link addresses are specified using the href attribute, together with the <a></a> tag. For example: <a href=”https://www.hyperiondev.com/”>Click this link to visit our website.</a>
  • Text and images can be linked.
  • HTML images are specified using the the src (image source filename) attribute, together with the <img> tag. For example: <img src=”https://blog.hyperiondev.com/wp-content/uploads/2018/10/Blog-Day-Life-HyperionDev-Student.jpg”>
  • You can set the height and width of an image in pixels, using size (width and height) attributes. The dimensions are specified in pixels.

Elements:

Elements are the individual parts that make up a web page. Your HTML tags mark the beginning and end of each element, e.g. the content that appears between the <body> and </body> tags is the body element.

Lists:

  • Lists are used in online articles, navigation menus, e-commerce website product features, etc.
  • The <li></li> tag is a list item tag, which contains an item or point you are listing.
  • Unordered lists (where the order does not matter) are coded using the <ul></ul> tag.
  • Ordered lists (where the order is significant) are coded using the <ol></ol> tags.
  • A nested list is a “list within a list” with a variety of different indentations defining points and sub-points.

Link targets:

  • A target attribute tells the browser where the link should open.
  • You can specify where to open a link by adding a target attribute to your code and applying a specific value.
  • This determines whether you want the link to open in a new window, the parent frame, a named frame, etc.

Below is an example of a link that’s been coded to open in a new tab:

<a href="https://www.hyperiondev.com/human-mentoring/" target="_blank">Click this link to learn about our mentoring process.</a>

Alt attributes:

  • The alt attribute provides alternate text for an image, informing your users (and search engines) what the image is about, which can be seen if there is a problem with loading the image.

The alt attribute would be added to the code following the image location URL, for example:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2017/10/Blog-Day-Life-HyperionDev-Student.jpg" alt="Happy Student" width="450" height="200">

Tables:

  • Tables can be a useful way of organising content on a web page.
  • The <table></table> tag is used to define the beginning and end of a table.
  • The <tr></tr> tag defines a row in a table.
  • The <th></th> table defines a table heading.
  • The <td></td> tag defines a cell of data in a table.
  • The <caption></caption> tag can be used to give the entire table a caption, telling the user what the table is about.
  • To add borders to your table and align the text, you would need to use CSS properties.

You can use HTML code to create tables with cells that span multiple columns, using the colspan attribute, or multiple rows, using the rowspan attribute.

Example of a table coded in HTML:

<table style="width:100%" border="1">
<caption>Daily Meeting Schedule</caption>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td>9AM conference call</td>
<td>12PM working lunch</td>
<td>2PM brainstorming session</td>
</tr>
<tr>
<td>10AM keynote address</td>
<td>1PM strategy session</td>
<td>4PM management team update</td>
</tr>
</table>

Forms:

  • The <form></form> tag is used to define a form to collect input from users.
  • There are various types of input elements like text fields, check boxes, radio buttons and submit buttons.
  • The <input> element and type attribute are used to define a specific type of form element.
  • Input types and names must appear inside quotation marks.
  • The <br> tag adds a line break, which allows you to display text on a new line.
  • The value attribute specifies the value of a form element.

Types of input commonly used in HTML forms:

  • <input type=”text”> defines a one-line text input field, where the user is required to type something like their name or e-mail address.
  • <input type=”radio”> defines a radio button, an icon representing a of a set of options. A user can only select one option at a time.
  • <input type=”submit”> defines a submit button, which allows the user to submit the form data to a form-handler (a server page that processes the data). The form-handler is specified using the action attribute.

Example of completed form code (with input fields, radio buttons and a submit button):

<form action="/action_page.php">
First Name:<br>
<input type="text" name="firstname"><br>
E-mail Address:<br>
<input type="text" name="email"><br>
<input type="radio" name="diet" value="vegan">Vegan<br>
<input type="radio" name="diet" value="vegetarian">Vegetarian<br>
<input type="radio" name="diet" value="none">No dietary restrictions<br>
<input type="submit" value="Submit">
</form>

Test your knowledge

Use your new knowledge of HTML code to recreate the basic web page below, with headings, paragraphs, a linked image, a list, a table and a form.

URL: https://www.hyperiondev.com/courses/

Image source: https://blog.hyperiondev.com/wp-content/uploads/2018/11/Blog-Programming-101.jpg

HTML beginner tutorial

If this HTML beginner tutorial has left you feeling inspired to go further, register for a Full Stack Web Developer bootcamp where you can learn HTML in more detail.

Check out our previous HTML tutorials:

HTML tutorial 3: tables & forms

Tutorials

HTML tutorial 3: tables & forms

The third HTML tutorial for beginners in a series from HyperionDev will show you how to set up HTML tables and forms for a web page, using HTML code.

If you’ve been following our HTML tutorial series, you’ll be familiar with how to create a basic HTML page with titles, headings and paragraphs. You’ll also have a basic understanding of Lists, links and images. By the end of our second tutorial, your document in Notepad++ should be displaying as follows:

HTML tutorial

In this next tutorial, you’ll be adding to the code to set up tables and forms in HTML.

HTML tables

Tables can be a useful way of organising content on a web page, particularly text.

  • A table is defined with the <table> tag.
  • Each row in the table is defined with the <tr> tag.
  • A table heading is defined with the <th> tag. (Headings are bold and centred by default.)
  • Each cell of data in the table is defined with the <td> tag.

Basic table: Set up a table with three headings to your page, by adding the following code to your document under the “ordered list” code. This is a real-life example that lists a weekly class schedule. The <th> tags will form the columns in this table, and the <td> tags will form the rows.

<table style="width:100%">
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td>9AM Lecture</td>
<td>12PM Lecture</td>
<td>Study Break</td>
</tr>
<tr>
<td>10AM Lecture</td>
<td>Study Break</td>
<td>2PM Lecture</td>
</tr>
</table>
HTML tutorial

When you refresh your page, the table will appear as follows:

HTML tutorial

To add borders to your table and align the text, you would need to use CSS properties.

To make our example more visually clear, we’ve added the CSS border property: border=”1″ to our table. You’ll be able to learn more about CSS properties and how to use them in future tutorials.

HTML tutorial
HTML tutorial

Captions: You can also add a caption to your table to tell the user what the content is about, using the <caption> tag. (For example, “Class Schedule” or “Client Details”.) This tag sits between the <table> tag and the first <tr> tag.

Add the caption “Weekly Class Schedule” to your table by adding the following code:

<table style="width:100%" border="1">
<caption>Weekly Class Schedule</caption>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td>9AM Lecture</td>
<td>12PM Lecture</td>
<td>Study Break</td>
</tr>
<tr>
<td>10AM Lecture</td>
<td>Study Break</td>
<td>2PM Lecture</td>
</tr>
</table>
HTML tutorial

When you refresh the page, you’ll see that your caption appears above the table headings:

HTML tutorial

You can use HTML code to create tables with cells that span multiple columns, or multiple rows.

Multiple columns: To make a cell span more than one column, we must use the colspan attribute. (Remember, attributes are what we use to provide additional information about a specific HTML element.)

The number of columns must appear between quotation marks, ie. “2”.

For example, let’s say we want to adjust this class schedule, to show that the same 9AM lecture takes place both on Monday and on Tuesday. Edit the table by adding the colspan attribute to the “9AM Lecture” cell, and removing the ”Study Break” cell.

<table style="width:100%" border="1">
<caption>Weekly Class Schedule</caption>
<tr>
<th>Monday</th>
<th>Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td colspan="2">9AM Lecture</td>
<td>12PM Lecture</td>
</tr>
<tr>
<td>10AM Lecture</td>
<td>Study Break</td>
<td>2PM Lecture</td>
</tr>
</table>
HTML tutorial

When you refresh, the appearance of the table will have changed, with the “9AM Lecture” cell spanning the Monday and Tuesday columns.

HTML tutorial

Multiple rows: To make a cell span more than one row, use the rowspan attribute. Again, the number of rows must appear between quotation marks. This is useful in cases where you have two rows that fall under one heading.

To change the “Tuesday” heading so that it spans two rows, edit the table by adding a rowspan attribute.

<table style="width:100%" border="1">
<caption>Weekly Class Schedule</caption>
<tr>
<th>Monday</th>
<th rowspan="2">Tuesday</th>
<th>Wednesday</th>
</tr>
<tr>
<td colspan="2">9AM Lecture</td>
<td>12PM Lecture</td>
</tr>
<tr>
<td>10AM Lecture</td>
<td>Study Break</td>
<td>2PM Lecture</td>
</tr>
</table>
HTML tutorial

When you refresh, the ”Tuesday” cell will span over two rows.

HTML tutorial

HTML forms

A form allows users on the site to enter information. You will need to use the <form> tag to define a form that will be used to collect user input.

An HTML form contains form elements, which are various types of input elements, including text fields, check boxes, radio buttons and submit buttons.

Add your opening and closing tags for your form, above the table:

<form>
.
.
</form>
HTML tutorial

You will now have space for the form on your refreshed page:

HTML tutorial

The <input> element is the most important of all the form elements. It can be displayed in a number of ways, depending on the type attribute used.

For example:

<input type=”text”> defines a one-line text input field.

<input type=”radio”> defines a radio button.

<input type=”submit”> defines a submit button.

Text fields: Add attributes into your form as follows, asking the user to input their name and e-mail address. The <br> tag adds a break, which allows you to display text on a new line. The input type and name must appear inside quotation marks.

<form>
First Name:<br>
<input type="text" name="firstname"><br>
E-mail Address:<br>
<input type="text" name="email">
</form>
HTML tutorial

Now the input fields will appear in the form on your page.

HTML tutorial

Radio buttons: A radio button is a graphical icon representing one of a set of options. A user can only select one option at a time.

HTML tutorial

You will also need to use a value attribute, which specifies the value of an <input> element. Again, input types and names must appear inside quotation marks.

Add three radio button options to your form, using this code:

<form>
First Name:<br>
<input type="text" name="firstname"><br>
E-mail Address:<br>
<input type="text" name="email"><br>
<input type="radio" name="role" value="softwareengineer" checked>Interested in Software Engineer Bootcamp<br>
<input type="radio" name="role" value="mobiledeveloper">Interested in Mobile Developer Bootcamp<br>
<input type="radio" name="role" value="fullstack">Interested in Full Stack Developer Bootcamp<br>
</form>
HTML tutorial

The updated page will display a choice of three clickable radio buttons.

HTML tutorial

Submit button: This button allows the user to submit the form data to a form-handler; a server page that processes the data.

The form-handler is typically a server page with a script for processing input data.

The form-handler is specified using the action attribute. This attribute defines the action that will be performed when the form is submitted. In this case, “/action_page.php” would contain a server-side script to handle the form data.

Add a submit button and action attribute to your form as follows:

<form action="/action_page.php">
First Name:<br>
<input type="text" name="firstname"><br>
E-mail Address:<br>
<input type="text" name="email"><br>
<input type="radio" name="role" value="softwareengineer" checked>Interested in Software Engineer Bootcamp<br>
<input type="radio" name="role" value="mobiledeveloper">Interested in Mobile Developer Bootcamp<br>
<input type="radio" name="role" value="fullstack">Interested in Full Stack Developer Bootcamp<br>
<input type="submit" value="Submit">
</form>
HTML tutorial

The submit button will appear in the browser.

HTML tutorial

Now that you’ve covered the basics of tables and forms, you can try your hand at some more complex layouts.

If you want to learn about the finer details of HTML coding, it’s time to go a little further than an HTML tutorial for beginners. Dive into an online coding bootcamp, complete with mentorship and code review.

5 Tips to Boost Video Performance on Your Website

Tutorials

5 Tips to Boost Video Performance on Your Website

How do you leverage the most from a video once you’ve added it to your website? You don’t want the performance of the video to negatively impact the load time of your webpage. This article lists out 5 tips you can use to optimize the videos on your WP blog

According to a study by Cisco, global video traffic will be 82 percent of all consumer Internet traffic by 2021. With Instagram Live, Periscope and other services, live video has been bubbling for a while. Add to that the fact that 64% of consumers are more likely to purchase a product on a retail website after watching a video, it is no surprise then that 70% marketers report videos to be a better conversion medium.

However, how do you leverage the most advantage from a video once you’ve added it to your website? You don’t want the performance of the video to negatively impact the load time of your webpage. This article lists out 5 tips you can use to optimize the videos on your WP blog. Right from technical details like codecs through to self vs. hosted videos to videos for multiple devices, we have you covered.

Uploading and Adding Video File Types to WordPress

After the latest WordPress update, uploading videos to your WP site has become much simpler. We’ve listed the steps below:

  1. Click ‘Add Media’ from within a post or a page. Click the ‘Upload Media’ tab on the top of the page –
  2. Next, click ‘Select Files’ button –
  3. Select the video file you wish to upload and follow the prompt
  4. After the file has been successfully uploaded, you can enter a title, caption, and description as needed towards the right of the page. You need to ensure that the Embed Media Player option is selected.

At the final step, click ‘Insert into post’ and your video will be added along with a thumbnail. You can use plugins to upload the video if you’re not going to store it on your WordPress server.

When it comes to encoding videos, there are specific file extensions that WordPress allows for video uploads. These include –

  • .MP4, .M4V (MPEG-4)
  • .WMV (Windows Media Video)
  • .OGV (Ogg)
  • .AVI
  • .MPG
  • .MOV (QuickTime)
  • .3GP (3GPP)
  • .3G2 (3GPP2)

In case you would like to add videos in formats not allowed by default, here is the code you would need to add to functions.php–

add_filter('mime_types', 'custom_upload_mimes');
function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes['extension'] = 'mime/type';
$existing_mimes['doc'] = 'application/msword';
return $existing_mimes;
}

In case you need to replace a file type from the pre-defined list of accepted file types, you can add this code –

add_filter('mime_types', 'custom_upload_mimes');
function custom_upload_mimes ( $existing_mimes=array() ) {
$existing_mimes['extension'] = 'mime/type';
$existing_mimes['doc'] = 'application/msword';
unset( $existing_mimes['exe'] );
return $existing_mimes;
}

Self Hosted Videos – Is it a Good Idea?

There are two options when it comes to choosing where your videos are stored – Self-hosted and hosted.

Self-hosted videos are those that are stored on your server that also hosts your WordPress site. Hosted videos, on the other hand, implies that your videos are stored in a different location and embedded or linked to your site.

There are a number of different reasons focused on video performance as to why you would choose one option over the other. Here are some pointers to help you make the decision.

In case you plan to display a number of HD videos, there is a possibility that you will exhaust the storage and bandwidth limit of your server pretty quickly. In this case, it might be best to host your videos at a different location. You could use video optimization plugins to compress the video before they are sent to the server. This would improve the video performance on your site.

What hosting options do you have?

The hosting option you choose is important. If you’re self hosting, you might have to use a dedicated hosting with sufficient bandwidth.

Shared Hosting & VPS hosting – Although it might be okay to store a few static video resources of smaller size on your shared/VPS hosting, you’ll be limited by the bandwidth offered by your host.

Dedicated Hosting – Depending on your infrastructure setup, you should be able to do quite a bit with your videos when using dedicated hosting. However, as you add to your video library, you may need to consider an upgrade in the future.

Optimize your Site and Server for Speed – Ensure that your server has sufficient RAM and a generous processor speed. As a general rule, a 1GB video should fit comfortably in your hosting plan as long as it has 2.5 GB of RAM and a dual-core processor with 1500 MB of storage space.

Ensure you have Sufficient Bandwidth – The amount of bandwidth depends on the number of visits you expect. If you foresee a spike in visits, you need to consider the amount of bandwidth your site can leverage. Typically, a 1GB video played or downloaded 1000 times requires 1TB of bandwidth.

Hosting Your Videos in the Cloud

A popular alternative to hosting your own videos is hosting it on Youtube, Dailymotion and other video sharing platforms. They have unlimited bandwidth and you don’t have to pay a dime. You can them embed the videos on your pages using WordPress’ HTML5 player or a third-party player.

If you’re not happy sharing your videos on social video platform like Youtube, you can instead host it over at a video cloud hosting solution like Cloudinary, JW Player etc. You can then embed the video using an HTML5 video player plugin offered by these vendors. These cloud solutions offer dynamic video transcoding functionality too. For instance, you can customize the quality of the video on the fly so that the users with slower connections can load a version of the video with smaller file size.

Furthermore, if you have expertise with AWS or a similar cloud platform, you can use an object storage service like AWS S3 or Google Firebase storage. You can add additional modules for video optimization and video tagging. Firebase for instance has a ML-Kit that covers many of the everyday AI requirements like video tagging and classification.

Displaying Responsive Videos in WordPress

If you use the default WordPress player, your videos would usually be fully responsive. However, this can be a problem, especially when using untested players on iframe to display videos.

The initial step to ensure your iframes support responsive videos is to download the FluidVids.js script by Todd Motto on GitHub. It’s particularly optimized for video performance.

Next, upload a copy to your media library, to each page file you plan to use for your theme – or, at a minimum, the type of page where you wish to display videos.

You can add this script to your /wp-content/themes/your-theme/page.php file to display responsive videos embedded with iframes on your WordPress pages. You can edit the file and call the script toward the top of the page, after all the initial page notes.

<script src="dist/fluidvids.js"></script>

What Settings Should You Use?

The settings you need to use to ensure your videos display well might be different for different users, especially when using a video hosting service as each service comes with their own recommended settings.

In case of self-hosted videos though, a general rule applies. Here are some recommended settings –

MP4 H.264 (AAC or MP3)

The MP4 container format with the H.264 video codec and the AAC audio codec is natively supported by desktop/mobile Internet Explorer, Safari, Chrome and Firefox.

Video

  • Codec: H264 (High profile)
  • Frame Rate: 24, 25 or 30 (Constant)
  • Frame Size / Resolution: 1280 x 720 (720p)
  • Fields: Progressive
  • Bitrate: 5000 – 10000 kbps

Audio

  • Codec: AAC-LC
  • Bitrate: 320 kbit/s
  • Sample Rate: 44.100 OR 48,000 kHz (retain original sample rate)

WebM

The WebM format uses the VP8 or VP9 video codec and the Vorbis or Opus audio codec. WebM is sponsored by Google and supported natively on Firefox, Opera, Chrome, and VLC Media Player.

Video

  • Filename Extension: .webm
  • MIME-type: video/webm
  • Audio-only MIME-type: audio/webm
  • Video Codec Name: VP8 or VP9
  • Audio Codec Name : Vorbis or Opus

Audio

  • Ogg Theora Vorbis
  • Ogg Opus

Summary

In this article, we’ve covered the steps that you need to follow to improve the performance of videos on WordPress. Next time you’re about to add videos, give it thought whether your host is capable of providing you bandwidth and storage space that meets your requirements.

If you have any thoughts to share, let us know in the comments.

HTML beginner tutorial 2: lists, links & images

Tutorials

HTML beginner tutorial 2: lists, links & images

The second HTML tutorial in a series from HyperionDev will show you how to set up HTML page titles, headings and paragraphs for a web page, using HTML code.

Welcome to part 2 of a 4-part series by HyperionDev showcasing an HTML tutorial for beginners. We hope you enjoy this upcoming tutorial, focusing on lists, links and images. By the end of our first HTML tutorial, your document in Notepad++ should be displaying as follows:

HTML beginner tutorial

In this next tutorial, you’ll be adding to the code to create lists, links and images in HTML.

HTML lists

Lists are very common in web pages. They’re used in online articles, navigation menus, and product features on e-commerce websites.

There are a few different types of lists you can use, depending on the content you want to display.

Unordered list:

An unordered list is a simple HTML list that you can use when the order of the items you’re listing isn’t important, and rearranging the order wouldn’t cause confusion or change the hierarchy of the list.

The <ul> and </ul> tags define the beginning and end of an unordered list. The <li> and </li> tags are list item tags, which contain the items or points you are listing.

Add an unordered list to your document, by inserting the following code underneath the “My first paragraph” code.

<ul>
<li>Item A</li>
<li>Item B</li>
<li>Item C</li>
</ul>
HTML tutorial

When you save and refresh, the list will appear as follows:

HTML tutorial

Ordered list:

Ordered lists are used when the order of the items is important, for example, a list of instructions that must be followed in order. The syntax is the same as for unordered lists, except that the <ol> and </ol> tags are used to define the beginning and end of the list, instead of the <ul> and </ul> tags which are used for unordered lists.

Add an ordered list to your document, by inserting the following code underneath the “Heading 2” code.

<ol>
<li>Step 1</li>
<li>Step 2</li>
<li>Step 3</li>
</ol>
HTML tutorial

When you save your document and refresh your browser, you’ll see the list appear as follows:

HTML tutorial

Nested list:

A nested list is a little more complex, because it’s essentially a “list within a list” with a variety of different indentations and bullet point types used to denote points and sub-points.

Add a nested list by typing this code into your document, under Heading 3.

<ul>
<li>Point A</li>
<ul>
<li>Sub-point A.1</li>
<li>Sub-point A.2</li>
</ul>
<li>Point B</li>
<ul>
<li>Sub-point B.1</li>
<li>Sub-point B.2</li>
</ul>
HTML tutorial

Your updated web page will appear as follows:

HTML tutorial

A real-world example of this would be something like a gym or exercise studio listing their daily schedule. The points would be the days of the week, and the sub-points would be the classes taking place each day.

If you want to see this real-world example on your web page, you can edit the text as follows:

<ul>
<li>Monday Schedule:</li>
<ul>
<li>9am - Hatha Yoga</li>
<li>1pm - Spinning</li>
</ul>
<li>Tuesday Schedule:</li>
<ul>
<li>10am - Water Aerobics</li>
<li>2pm - Pilates</li>
</ul>

When building a real website, you would be able to add as many points and sub-points as you need, depending on the site content.

Remember that HTML isn’t presentational, and in order to add styling to your lists (e.g. defining the font used for the list), you will need to use Cascading Style Sheets (CSS).

HTML links

HTML links are hyperlinks which allow the user to click and navigate to another page or document. When a piece of text is hyperlinked, a mouse cursor will turn into a hand icon to show the user that it is clickable.

In our first HTML beginner tutorial, we covered how to insert a simple HTML link using the <a> and </a> tags and the href attribute, as follows:

<a href="https://www.hyperiondev.com/">Click this link to visit HyperionDev</a>
HTML tutorial

HTML also allows you to define the behaviour of your links in a bit more detail, such as creating targets and linking images.

Targets:

You can use a target attribute to specify where to open the link. You can do this by adding a target attribute to your link code and applying one of the following values:

  • _self opens the link in the same window or tab as it was clicked
  • _blank opens the link in a new window or tab.
  • _parent opens the link in the parent frame
  • _top opens the link in the body of the window
  • framename opens the link in a named frame

Go back to the link in your document, and edit it as follows:

<a href="https://www.hyperiondev.com/" target="_blank">Click this link to visit HyperionDev</a>

This example will open your link in a new browser window or tab. This is useful, because it allows the user to open the link without clicking away from the original web page or site.

When you refresh your page and click the link, the content will open in a new tab.

HTML tutorial

By default, an unvisited link will be underlined and appear as blue text. A visited link will be underlined in purple text, and an active link will be underlined in red text. To change these default colours, you would need to use CSS to style them further.

Linking images:

Images can be hyperlinked as well as text.

Go back to your image in your document, and add your <a> </a> tags and href attribute, as you would for a text link.

<a href="https://www.hyperiondev.com/">

<img src="https://blog.hyperiondev.com/wp-content/uploads/2018/10/Blog-Day-Life-HyperionDev-Student.jpg" width="450" height="200">

</a>
HTML tutorial

When you refresh your page, the image will look the same, but your mouse cursor will change to a hand when you hover over it – showing that the image is now clickable.

HTML tutorial

Clicking the image will open your link in the same browser tab. You can change this to open in a new tab, by using a target attribute as you would for a text link.

HTML images

In the first tutorial, you learned how to add an image to your HTML page, using the <img> tag.

The <img> tag contains attributes only, and does not have a closing tag. The src attribute, which you’ve already learned how to use, specifies the location (web address or URL) of the image.

The alt attribute provides alternate text for an image, in case the user isn’t able to view the image itself. This could be caused by a slow Internet connection or an error in the src attribute.

Let’s say for example the url you were using was incorrect. Go back to the image in your document, and change it to a purposely incorrect url, as follows:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2017/10/Blog-Day-Life-HyperionDev-Student.jpg" width="450" height="200">
HTML tutorial

When you refresh the page, you’ll see a broken image with no description of what ought to be displaying there.

HTML tutorial

Putting alt attributes in place for your images ensures that your users (and search engines) can see what’s meant to be there, even if there is a problem with loading the image.

Add an alt attribute to your image using the following text:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2017/10/Blog-Day-Life-HyperionDev-Student.jpg" alt="Happy Student" width="450" height="200">
HTML tutorial

When you reload the page, the alt attribute value will display where the image should be:

HTML tutorial

Note: Be sure to fix your image url before continuing. Ideally, the images should display, and alt attributes should be in place as a back-up.

Part 3 of our HTML tutorial will show you how to set up tables and forms.

This tutorial will give you a simple introduction to the popular web language, but if you want to learn more about HTML code in-depth, why not sign up for a mentor-led full stack web development course?

HTML beginner tutorial 1: getting started, tags, attributes & elements

Tutorials

HTML beginner tutorial 1: getting started, tags, attributes & elements

The first HTML beginner tutorial in a series from HyperionDev - getting started with HTML, tags, attributes & elements. Part 1 of 4.

HTML stands for Hyper Text Markup Language. It is the standard markup language used by developers to create web pages. It is a simple, useful way to structure content. HTML is typically used together with JavaScript and Cascading Style Sheets (CSS). These three technologies are the cornerstone of web development. This HTML beginner tutorial will introduce you to a few basic concepts, including tags, attributes and elements.

Getting started with HTML

HTML files are simple text files. To write your first code in HTML, all you need is a text editor, like Notepad++ or Wordpad.

To create a basic HTML page, you need to follow these steps:

  • Open a text editor and type a few words, for example “My first web page”.
  • Create a folder named “html”.
  • Save the file to this folder as a plain text file with html extension, for example “myfirstwebpage.html”.
  • Be sure to save the file as plain text, not rich text.
  • Be sure to use the “.html” extension, as some text editors will automatically save the file as “.txt” otherwise.

To view the HTML file, open your web browser and type the location of the file you just saved into the address bar. For example,“c:\html\myfirstpage.html”. Then press Enter. (You can also go to the File menu of the browser, select Open, and browse for the file you saved.)

You will now be able to view the file as a web page.

The next stage of our HTML beginner tutorial will look at how to start adding structure to your web page, using tags.

HTML tags

A tag is a piece of code that helps to define the basic structure of your HTML document. Tags will surround the content in your document, and apply specific meaning to that content. For example, do you want to define a document, a heading, a sub-heading or a paragraph? You’ll use tags to show these definitions.

  • An opening tag between these symbols: < >
  • A closing tag appears between these symbols </ >

Tags can be used to define a few words of content, a few lines, a few paragraphs, or even an entire document.

Tags in action

To start off with a few simple tags, add this text to your document, before and after your first line of copy:

<!DOCTYPE html>
<html>

<head>
<title>My first web page</title>
</head>

<body>
My web page content...
</body>

</html>

The <!DOCTYPE html> tag is a document type declaration, which tells the browser which type of HTML you’re using. HTML5 is the most updated version.

The <html> tag tells the browser that everything between that opening tag and </html> closing tag is an HTML document. You need to ensure that there is an opening tag and a closing tag, to mark the beginning and end of the code.

The <head> and <title> tags define the title of your document. Title tags are required for all HTML documents, because they determine the title that appears in the browser toolbar, and in search engine results.

The <body> tag defines the main content of the document, which will appear in the browser window and will be coded between that opening tag and the </body> closing tag.

If you save the file and reload it in your web browser, you’ll see that the title “My first web page” now appears in the browser, and the main body “My web page content…” appears on the page.

Next, you can add headings and paragraphs to your document using tags.

Headings are defined using <h1> to <h6> tags, with <h1> being the most important heading and <h6 > being the least important.

Add a series of heading tags as shown below, between the <body> and </body> tags. Then save your document and refresh your page.

<!DOCTYPE html>
<html>

<head>
<title>My first web page</title>
</head>

<body>
My web page content…

<h1>Heading 1</h1>

<h2>Heading 2</h2>

<h3>Heading 3</h3>

<h4>Heading 4</h4>

<h5>Heading 5</h5>

<h6>Heading 6</h6>
</body>

</html>

The web page will show a list of headings in different sizes, depending on their importance.

Paragraphs are defined using the <p> tag. The browser will automatically add some space before and after each paragraph.

Add a short paragraph of text with opening and closing tags under the first heading in your document. Then save and refresh.

<!DOCTYPE html>
<html>
<head>
<title>My first web page</title>
</head>
<body>
My web page content…
<h1>Heading 1</h1>
<p>My first paragraph of text</p>
<h2>Heading 2</h2>
<h3>Heading 3</h3>
<h4>Heading 4</h4>
<h5>Heading 5</h5>
<h6>Heading 6</h6>
</body>
</html>

The paragraph will appear under the first heading, with space (margins) before and after the text.

These are the essential tags you will need to set up the basic structure of a web page. Have a look at some other common HTML tags here.

HTML attributes

Attributes are extra bits of information, which appear inside opening tags inside quotation marks. They usually come in name and value pairs, for example: name=”value”.

Tags with attributes are written in a format as follows: <tag attribute=”value”>Text</tag>.

Attributes in action

Links: HTML links are written using the tag <a>, and the actual URL (link address) is specified using an attribute called the href attribute.

For example, you can add a link to your first paragraph using the following tag and attribute:

<a href="https://www.hyperiondev.com/">Click this link to visit HyperionDev</a>

When you save and refresh, there will be a clickable link on your web page.

Images: HTML images are coded using the tag <img>, and the image source filename is specified using an attribute called the src attribute. Note that the image URL must be written inside quotation marks.

The image must be stored on an HTML page online – not on a local computer. Note that the <img src> tag doesn’t require a closing tag.

For example, you can add an image to your first paragraph using this code:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2018/10/Blog-Day-Life-HyperionDev-Student.jpg">

When you save and refresh, the image will display.

Dimensions: You can set the height and width of an image in HTML using size attributes. The dimensions are specified in pixels. Note that the pixel number must always be written inside quotation marks.

For example, you can resize the image in your first paragraph by using the following code:

<img src="https://blog.hyperiondev.com/wp-content/uploads/2018/10/Blog-Day-Life-HyperionDev-Student.jpg" width="450" height="200">

When you save and refresh, the resized image will display.

HTML elements

When we talk about elements, we’re referring to the individual parts that make up a web page. Your HTML tags mark the beginning and end of each element.

For example, the content that appears between the <body> and </body> tags is the body element. And the text that appears between the “<title>” and “</title>” tags, “<title>My Page Title</title>” would be called the title element.

Part 2 of our HTML beginner tutorial will show you how to set up lists, links and images. In the meantime, if you’re interested in learning more about HTML code, check out our mentor-led online coding courses.

Building a website: a how-to guide for your first site

Tutorials

Building a website: a how-to guide for your first site

An essential guide to the admin behind building a website - everything you need to do before launching your first site, from choosing your platform to adding your site content.

As a developer building a website, you might be tempted to dive straight into the code and get the creative side of things rolling. But before you do, it’s important to go through the less exciting steps first, to make sure your site is set up correctly.

Here is an essential guide to the admin behind building your first website.

  1. Define the Type of Site You Need

First, you need a clear understanding of what you want to achieve with the website. This will determine the functionality you’ll need on the site. Your website may be one of the following types (or a combination of types):

  • Blog: A blog can be a standalone website, or an extra feature for a larger website. Blogs are usually arranged in chronological order, with the most recent entry at the top of the main page.
  • E-commerce site: Showcases products or services, and allows visitors to purchase them online.
  • Business card site: A simple one-page website for a small business. The site typically includes the name, description, contact information and company logo.
  • Portfolio site: Similar to business card website, but with an additional section that showcases a portfolio of work. This format is typically used by design companies, photography studios and other creative businesses.
  • Product brochure site: A more detailed site used to market a business. This site setup allows visitors to browse through the goods and services offered by the company. It may include some pricing guidelines, but unlike an e-commerce site, a product brochure site doesn’t enable customers to make purchases online.
  1. Choose the Right Platform for your Site

There are many different site-building platforms and tools available to choose from. Certain platforms are better suited to specific site types, so defining the purpose of your website will help you choose the right platform.

A platform (also called a Content Management System or CMS) is the “skeleton” of your website. This is where you make changes and additions to the site. The right platform will make it easy to maintain and update your site regularly.

There are two main types of CMS: hosted and self-hosted.

  • A hosted platform gives you a quick, easy way to start publishing content without touching a server or managing upgrades. However, hosted platforms are more limited when it comes to what you can change.
  • A self-hosted platform gives you more accessibility, with free reign to customise the functions and style of your website.

The most popular CMS choices for 2018 are:

  • #1: WordPress
  • #2: Joomla
  • #3: Drupal

WordPress is widely considered the easiest platform to use, and is therefore ideal if you’re building your first website.

  1. Choose a Domain Name and Hosting Provider

The next step in building a website is choosing the right name and web hosting provider.

Ideally your domain name should be something like yourname.com or companyname.com. You will need to find which domain names are available, and reserve the one you want. This domain identifies your site and gives you administrative control of it in the online sphere.

The web hosting provider is where your files are stored online. The purpose of your hosting provider is to make sure your domain is available to potential viewers at all times. A reliable host means good website functionality and performance.

Compare the top web hosting services of 2018 to decide which one best suits your needs.

  1. Get Your SSL Certificate

SSL stands for Secure Socket Layer, which is a standard security technology used to set up an encrypted link between a server and a client (such as a web server and a browser).

A secure certificate is a document used to certify that an individual or business is who they say they are. It lists details like the official company name, the full web domain name, creation date and expiration date.

Your certificate will transmit data on the Secure Socket Layer, which encrypts the data to protect you against identity theft and credit card fraud.

  1. Install and Set Up your CMS

This step will vary depending on which CMS you’ve chosen. Install your selected content management system (e.g. WordPress), following the prescribed steps for that CMS. The it’s time for the creative stuff to start!

  1. Design Your Site

This is the part you’ve been waiting for – the actual code and design that goes into building a website. When a visitor lands on your site, it will take them less than three seconds to decide whether to stay or move on. You need good, clean design and functionality to keep their attention.

Here are some basic points to keep in mind:

  • Avoid a cluttered layout and clashing colours
  • Make the site easy to navigate (a smooth user experience)
  • Make sure the design is responsive (works across mobile devices)
  1. Add Your Site Content

Once the design is complete, add the written information (content) that needs to appear on your site. It’s important to make sure your content is useful, unique and updated regularly.

Clear, well-written content ensures your visitors can easily understand your marketing message. Search engines also reward sites with quality content, with higher rankings.

  1. Test Your Website

After all the time and effort that goes into building a website, you’ll undoubtedly be eager to launch it. But there’s one more crucial step you need to take before going live. Test, test and test again!

Launching a site with numerous errors will reflect poorly on the company, and on you as a developer. Be sure everything is in good working order before the site becomes available to the public.

Carefully check the following points:

  • Web development items (live URLs, broken links etc.)
  • Search engine optimisation (title tags, meta data etc.)
  • Network admin (hosting, backup system etc.)
  • Content-related issues (spelling & grammar)
  • Design elements (images, fonts & layout)

A Crash Course in Site Building

Looking to build websites professionally, but not sure where to start? Take an online coding bootcamp and find out exactly what’s involved in coding, designing and building a top-notch website.

Setting up a GPU for Accelerated Cloud Computing

Tutorials

Setting up a GPU for Accelerated Cloud Computing

In this tutorial, we will be looking into setting up a GPU for cloud computing – what it is, why we might want to use it, and how to set it up.This tutorial is based on using Amazon Web Services.

Introduction

In this tutorial we will be looking into accelerated cloud computing – what it is, why we might want to use it, and how to set it up. All code for this tutorial is provided, but we will assume some familiarity with basic shell commands.

Cloud computing in general refers to using compute power, storage, applications and/or resources through a remote platform, which you can access on-demand and scale to your personal requirements. Using cloud computing service providers means we don’t need to deal with this kind of infrastructure or maintenance ourselves, and can instead focus on how to best utilise the extra compute capacity for our needs. There are certain tasks where accelerated computing, using GPUs rather than CPUs, is a more efficient approach in terms of time and cost. This is often the case with tasks that are massively parallel, meaning the work can be distributed in parts to execute simultaneously. We will be setting up our GPU for one example of such a task: deep learning.

There are a number of different cloud service providers, including Microsoft, Google, Oracle, and IBM. We will be using the market-leader, Amazon, to set up our GPU with Amazon Web Services (AWS).

Account Setup

To sign up for an account with AWS, we need to head to this link and fill in all our details. We will then arrive at the AWS Console – the dashboard showing all available services and tools.

Before we can get going with our GPU setup, we first need to request a service limit increase. AWS accounts are initialised with a limit of 0 instances for certain configurations, and one of those is the p2.xlarge instance which we require. So, from the main dashboard click on EC2 instances and then limits:


On this page you need to scroll down until you reach the ‘Running On-Demand p2.xlarge instances’ row of the table. Here you should click ‘Request limit increase’.

If you do not see p2.xlarge as an option – don’t worry. There are many different server farms used by Amazon all around the globe, and not all of them support GPUs. You have to select a region to associate your account with, which is usually the closest one to your personal location. The list below states which regions currently support GPU instances, so change your region settings (at the top right of the screen, next to your account name) to one of the below locations. Selecting the closest one to your actual location will reduce latency.

  • US East (Ohio)
  • US East (N. Virginia)
  • US West (Oregon)
  • Asia Pacific (Seoul)
  • Asia Pacific (Sydney)
  • Asia Pacific (Tokyo)
  • Asia Pacific (Singapore)
  • Asia Pacific (Mumbai)
  • China (Beijing)
  • Europe (Ireland)
  • Europe (Frankfurt)

Once we have clicked ‘Request Limit Increase’ for the p2.xlarge instance, we can fill out the form details as follows:

Any reasonable example can be entered for the use-case, such as ‘deep learning’. Once submitted, the response time for our request can vary, but we will receive an email update once it has been accepted.

Security Keys

We also need to configure some security settings for our account, so head back to the main dashboard by clicking on the AWS logo at the top left.

From the main dashboard, scroll down to the subsection titled ‘Security, Identity, & Compliance’ and in this column click on ‘IAM’ which stands for ‘Identity and Access Management’. Then on the left hand side click on ‘Users’, and then the blue ‘Add User’ button.

Here we create a username for ourselves, and select to give both programmatic access and AWS management console access to this user. We can choose the password details depending on personal preference.

To set the permissions for this user, we want to attach existing policies directly. Here we select ‘Administrator Access’ which should be the first row of the table, and continue to the final review stage.

After confirming the details, our administrator user is now created. Two key pieces of information will be displayed at this stage: the Access Key ID and the Secret Access Key. You should save both of these for later steps in our setup.

Command Line Interface

So far, we have been exploring what is known as the AWS Console – the web-based user interface displayed as a dashboard. We can also access AWS through their Command Line Interface (CLI). The AWS CLI is Python-based, so it can be installed using the package manager pip. Let’s open up our terminal to check whether pip is installed (and if not, install it here), and then execute the following command:

pip install awscli

Next we need to configure the CLI with the correct settings for our account:

aws configure

The CLI will ask us for our Access Key ID (which you should have noted down earlier), along with the region name, and output format. For region name, choose the one corresponding to your selected region earlier (ours is ‘eu-west-1a’ for Ireland), and for output format use ‘text’.

AWS Access Key ID [********************]: your-access-key-ID-here
AWS Secret Access Key [********************]: your-secret-access-key-here
Default region name [eu-west-1a]: eu-west-1a
Default output format [text]: text

Our CLI is now configured to the correct user settings.
The amount of tools and services available through AWS is vast, so naturally the CLI has many possible commands. A full reference point for navigating your way around is available here, but we will be mostly using the Console for our setup.

Elastic Compute Cloud

The main AWS product that we will be using in this tutorial is known as the Elastic Compute Cloud (or EC2). EC2 is a service that allows us to configure and use virtual servers in the cloud, extending our compute capacity beyond our own personal machines.

Each instance we choose to set up can be configured in a number of different ways, and there is also the option to use Amazon Machine Images (AMIs) to speed this process up. AMIs are pre-configured setups with popular libraries, frameworks, drivers, and other options included for us.

To set up our first instance, head to the EC2 dashboard and click the large blue ‘Launch instance’ button. This takes us to the first stage of setting up our instance – selecting the AMI. Here you could choose to set up with your own AMI using the ‘My AMIs’ option on the left hand side, but we will be using one of the Deep Learning AMIs which are pre-configured with everything we need.

We want to select ‘Deep Learning AMI (Ubuntu)’:

As stated, this comes with some useful frameworks such as Keras and TensorFlow. Other settings for this configuration include EBS (Elastic Block Storage), which provides persistent storage for our instance, and HVM (Hardware Virtual Machine) virtualization which is fully virtualized rather than the lighter PV (Paravirtual). Other options such as Microsoft or Linux over Ubuntu are available if you would prefer.

At the next stage we will select the p2.xlarge instance:

And then we are ready to ‘Review and Launch’.

SSH Key Pair

Once you have clicked the button to launch your instance, you should get a popup window prompting you to assign a key pair to the instance. This is referring to a public key stored with AWS and a private key stored on your personal machine, which we will now create. The key pair is used as a security measure, to authorise access to the instance.

Select ‘Create a new key pair’, and name it anything you like, such as ‘GPU-key’. Download the key and ensure it is saved with the file extension ‘.pem’.

Now we can go to the EC2 dashboard and view our instances by selecting ‘Running Instances’. Make a note of the Instance ID and Public DNS name displayed here. Initially the instance state will be displayed as ‘pending’, and after a short while it will update to ‘running’. Our instance is now ready to use!

Using Instance

Now let’s go to our back to our terminal and use the CLI to navigate to the directory where our private key is stored. For security, we will first make sure that the file permissions on our private key are actually private:

chmod 400 GPU-key.pem

And now we are ready to SSH into our running GPU instance:

ssh -i GPU-key.pem ubuntu@ec2-34-244-87-180.eu-west-1.compute.amazonaws.com

Make sure the .pem file for our key is the correct filename, and that the user_name@public_dns_name uses your own details. The username section will be ‘ubuntu’ if you followed our exact configuration and selected the Ubuntu AMI, but other options include ‘ec2-user’ for Linux, RHEL, and Fedora, or ‘centos’ for CentOS. The DNS name is what you should have noted earlier from the instance page.
Once executed, we should get an authenticity warning to which we can respond ‘yes’.
The terminal should now display a welcome entry:


If you see:

*** System restart required ***

Then use:

sudo reboot

…to restart the system, and then SSH back in again.

Deep Learning

Now lets see how we can perform some tasks that would actually require the compute power of a GPU, such as deep learning. Here we will activate the specific environment we want to use, which for this example use case is the last option with Python 3.

source activate python3

We want to be able to run some code with a Jupyter notebook, so we first need to open a port for this on our instance’s firewall. From the EC2 dashboard scroll down to the ‘Network & Security’ section and click on ‘Security Groups’:

From the list of security groups, select the one with name ‘launch-wizard-1’, then click on the ‘Inbound’ tab, and the ‘Edit’ button:

Here we want to add a new rule with the following specifications:


Next we will be configuring our Jupyter server by updating the config file and creating a Secure Sockets Layer (SSL) to establish an encrypted link between our server and the browser we will use to access the notebook.
Back in the terminal, execute the following commands (making sure we are still SSHed into the running instance):

mkdir ssl
cd ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout "cert.key" -out "cert.pem" -batch

This generates an RSA private key and saves it to ‘cert.key’. Next we can create a password for logging into our Jupyter notebook server from the browser:

ipython
from IPython.lib import passwd
passwd()
Enter password: your-password-here
Verify password: your-password-here

We will be presented with a hash of our password similar to this:

'sha1:d148aca0…………………….'

Save this hash, and exit the iPython terminal (with the command ‘exit’).
Then open the config file and add the following to the end of the file:

c = get_config()
c.NotebookApp.certfile = u'/home/ubuntu/ssl/cert.pem'
c.NotebookApp.keyfile = u'/home/ubuntu/ssl/cert.key'
c.IPKernelApp.pylab = 'inline'
c.NotebookApp.ip = '*'
c.NotebookApp.open_browser = False
c.NotebookApp.password = 'sha1::d148aca0……………………..'

We are finally almost ready to start using our notebook. In the current terminal, lets get our notebook up and running:

jupyter notebook

And then in a separate terminal, we need to use the following command to forward all requests on a local port (8080, or any local unused port of our choice) to the port of our GPU instance (8888):

ssh -i GPU-key.pem -L 8080:127.0.0.1:8888 ubuntu@ec2-34-243-47-75.eu-west-1.compute.amazonaws.com

Now if we open up a browser and head to http://127.0.0.1:8080 we will see the Jupyter login page where we can use the password created earlier to securely gain access.
Once logged in, we are now ready to run some example code using the Jupyter notebook! If you are new to deep learning you can find some examples of projects to step through by clicking on the tutorials link, or you may have some of your own personal code that you would like to run on the GPU. But please note, doing anything time-consuming here will begin to charge your account. The fees are $0.90 per hour (pro-rata) for the exact configuration we used in this tutorial, but larger instances will cost more.
Here’s an example of the Hello TensorFlow tutorial available:

Analysing GPU performance

Once the GPU is put to use and some code is running, we can check up on its performance – determine which programs are executing, how much memory is being used etc. We will use the NVIDIA System Management Interface to take a look at these statistics.
In the CLI, run:

nvidia-smi

We are presented with an interface similar to the one below, which provides details such as whether the nvidia driver is running successfully, what processes are using the GPU, how much memory is being used, and the fan temperature, etc.

Increasing Compute Power

When more compute power is required, there are two approaches to consider. The first is referred to as ‘scaling up’ and involves upgrading to a larger, more powerful instance (the largest AWS currently offers is p2.16xlarge with 16 GPUs). The alternative approach of ‘scaling out’ involves creating a cluster of instances and distributing the workload among them. There are different advantages and disadvantages to each method. For example, 8 p2.xlarge instances and 1 p2.8xlarge instance provide the same compute power. With 8 instances running, the likelihood of an instance failing is higher than with 1 instance, however the impact of 1 failure out of 8 is much less than the impact of our 1 and only instance failing.

We will not step through the process of adding further instances or increasing our current instance in this tutorial, but doing so is as simple as repeating the steps taken so far. If you want to scale up, just select a more powerful instance, such as p2.8xlarge, when you are configuring the new instance. To scale out, just repeat our exact steps multiple times, creating new instances of the same configuration. In both cases, you will first need to request a further service limit increase.

Cloud Storage

AWS has a huge span of tools and services, but one other worth mentioning in relation to GPU usage is their storage service. Often if we are executing compute-heavy tasks such as deep learning, we may be reading to and writing from large stores of data. Our running instance already has some amount of storage (our configuration has 50GiB), but this lives and dies with the instance. We can copy files to and from our instance using two commands.
To transfer a file to our instance:

scp -i GPU-key.pem my-file.txt ubuntu@ec2-34-244-87-180.eu-west-1.compute.amazonaws.com:~

And back in the other direction, from the instance to our machine:

scp -i GPU-key.pem ubuntu@ec2-34-244-87-180.eu-west-1.compute.amazonaws.com:~/my-file.txt

But for a more persistent method, we can store data separately in the cloud, using Amazon’s Simple Storage Service (also known as S3). This storage system refers to uploaded objects as ‘buckets’. Here we can save an example csv file as a bucket called ‘mybucket’.

aws s3 cp my-file.csv s3://mybucket/

Storing our data separately from the instance means it is accessible from multiple instances (and other sources), and is still accessible when the instance is not running.

Shutting down

The final step (and perhaps the most important step) for this post is to shut down your instance. As the GPU instances incur hourly charges, we don’t want to accidentally leave one running overnight! You can set up billing alerts here if you are worried you might forget.

To shut down an instance head to the EC2 instances dashboard, select the instance, and then Actions > Instance State > Stop.

Conclusion

We have now successfully set up, launched, and shut down an instance of a GPU in the cloud, and can easily restart our configured instance any time we would like to access the accelerated compute power or resources it provides.

Deep learning is just one example of a task which may require such power, but many other compute-heavy tasks such as graphics rendering, or bitcoin mining, can be executed much more efficiently with this approach.

If you are interested in using the AWS cloud computing services for smaller-scale tasks that do not require a GPU, it is worth mentioning that other instances can be configured for free, using CPUs and with less memory and processing power.

Deploy a Machine Learning Model with Flask

Tutorials

Deploy a Machine Learning Model with Flask

This tutorial will demonstrate how to create an API for a machine learning model, using Python along with the light-work framework Flask. This API will act as an access point for the model across many languages, allowing us to utilize the predictive capabilities through HTTP requests.

In a previous post we built a machine learning model which could classify images of house numbers from Google Street View. Since then you may have worked to improve this model, or developed your own model for a different kind of task. Often when we are getting started in machine learning we learn how to build a model and how to improve it – but how do we go from this stage, to getting it working in the real world?

Python is the language of choice for many machine learning systems, but when it comes to the application in which we want to use our model, it is more common to encounter other languages – such as Javascript for web apps. We need to be able to access the model from within its intended application, and when these are coded in different languages, it seems like a problem. It is possible to program for machine learning using a language like Javascript, but you are more limited in what you can achieve, and the process is much harder as it doesn’t have all the useful libraries developed for Python.

This tutorial will demonstrate how to create an API for a machine learning model, using Python along with the lightwork framework Flask. This API will act as an access point for the model across many languages, allowing us to utilise the predictive capabilities through HTTP requests.

Requirements and Setup

For this tutorial we will be using the Python 3 language, so check that this is installed by opening up your terminal and running the following command.

python -v

Now we can set up a new directory for our project and navigate into it.

mkdir flask-tutorial
cd flask-tutorial

You can also optionally use a virtual environment for this project, with the following two lines of code which create our virtual environment and then activate it.

virtualenv flask-tutorial-env
source flask-tutorial-env/bin/activate

The libraries that we will be using include Flask to build our API, scikit-learn and numpy for our model, and scipy for reading new image files. We can install all of these with pip, a tool for simple installation of Python packages.

pip install flask scikit-learn numpy scipy

Before we begin, we also need a machine learning model to work with. We will be using the model created in our previous image classification tutorial – but don’t worry if you haven’t completed this. In the previous post, we built a working model and were using it to output predictions for test images. But, our model only existed inside the Python file. We can use the file format .pkl to pickle our model, which means to persist it by saving to disk. You can pickle any kind of object within Python such as lists, dataframes, and dictionaries, and then unpickle them to load them back from memory, exactly as they were. This is useful with machine learning models, as it means we do not need to constantly retrain our models each time we want to use them.

Open the Python file from our previous tutorial (If you didn’t follow along previously, you can get the complete source code here) and add the following lines to save your model as a .pkl file

from sklearn.externals import joblib
joblib.dump(clf, 'model.pkl')

Once you have run the file and generated a model.pkl file, make sure it is saved in the working directory for this project.

Building an API

Now we’re ready to build our API. Let’s start with a simple skeleton Flask application. Create a new Python file api.py with the following code:

import flask
from flask import Flask

app = Flask(__name__)

if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)

The first two lines import our library, and then we create an instance of this class using the parameter __name__ because this will be the only module in our application, and this defines where the application should look for related files (such as templates, which we will create shortly).

The last two lines are what gets our API running. We will run our app on host 0.0.0.0 as we want to run it locally on our machine, and you can use any available port, in this case we have chosen 8000. You can also set the debug parameter to True if you would like to see the debugger statements printed to the terminal. These two lines should remain at the bottom of our code in this file, with everything else going in between.

You can now go back to the terminal and start running the API with the following command:

python api.py

You should get the following output:

* Running on http://0.0.0.0:8000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 103-316-823

Now you could open a web browser and navigate to http://localhost:8000 where you will see a ‘404 URL not found’ page, as our application doesn’t do anything yet!

So let’s set up an index page for the application to open with. In our api.py file we can add the following code to route our application to the file ‘index.html’ upon entry. We also need to import ‘render_template’ which is what we use to return the html files.

import flask
from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
@app.route("/index")
def index():
return flask.render_template('index.html')

if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=True)

In our project directory we will add a folder called ‘templates’ and within this create our ‘index.html’ file. This can contain a simple header for now.

<html>
<head>
<title>SVHN Model as a Flask API</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h1>Google Street View House Number Predictor</h1>
</body>
</html>

Our api.py file detects saved changes by itself so we do not need to restart it manually when testing again. We can simply refresh our page in the browser and now see our loaded webpage.

So we have a basic app serving a simple webpage. Now we need to create an endpoint to which our web page can send an image file uploaded by the user, to then process and make a prediction for, before sending this back to be displayed to the user.

API endpoint for predictions

Let’s head back into our file api.py. The first thing we want to do is to load our saved model when the app starts running.

from sklearn.externals import joblib

if __name__ == '__main__':
model = joblib.load('model.pkl')
app.run(host='0.0.0.0', port=8000, debug=True)

Then, underneath our index routing section, we can create the endpoint for predictions.

from flask import Flask, render_template, request

@app.route('/predict', methods=['POST'])
def make_prediction():
if request.method=='POST':
return render_template('index.html', label="3")

What we have done here is create an endpoint ‘/predict’ for HTTP POST requests. We will be sending this request from our index page. Currently we just return the label “3” for simplicity, though we will be building our actual predictor shortly. We’ve also added one more element to our list of imports, for requests.

Now going over to our index.html file, we need to add some code which will execute our HTTP request. Currently we have a blank page with just a header. Let’s add a form which will contain a file chooser, and a ‘Predict’ button. The user can upload a 32×32 .png file and click ‘Predict’, to then receive the predicted label.

<form action="/predict" method="post" enctype="multipart/form-data">
<input type="file" name="image" value="Upload">
<input type="submit" value="Predict"> {% if label %} {{ label }} {% endif %}
</form>

Our form action routes our application to the ‘/predict’ endpoint, with the POST method. We are using the ‘multipart/form-data’ format to send our data, and this helps us know how to deal with the data when receiving it back in the API.

The two inputs within our form are firstly the file chooser, and secondly the ‘Predict’ button.

We also have some code using syntax not normally found in HTML files: {% if label %} {{ label }} {% endif %}. This is jinja syntax, and it is used to access the variables returned from our HTTP request within the HTML file. Here we are checking that the label exists, and if it does we display it next to the ‘Predict’ button.

Now you can refresh the page in your browser, click ‘Predict’ and your page should look like this, with the label 3 displayed.

House number prediction
House number prediction

Now we want to make a real prediction. In our api.py file, we need to access the image file uploaded by the user and use our model to make a prediction for its label.

import numpy as np

from scipy import misc

@app.route('/predict', methods=['POST'])
def make_prediction():
if request.method=='POST':
file = request.files['image']

if not file:
return render_template('index.html', label="No file")
img = misc.imread(file)
img = img[:,:,:3]
img = img.reshape(1, -1)

prediction = model.predict(img)
label = str(np.squeeze(prediction))
if label=='10':
label='0'
return render_template('index.html', label=label, file=file)

The first thing we do is look for the image file in the data received from the HTTP request. If it doesn’t exist, we will return the label “No file” to be displayed in our index page.

If the image does exist, we use the imread function to read it in as an array of pixels (as this is how we represented images when building the model). As .png files are often stored with 4 colour channels instead of the 3 we were using for the RGB representation, we will only take the first 3. The fourth channel is an Alpha channel for transparency, but this is irrelevant here, so we can just exclude it. Then we reshape our matrix as its a single image, and make our prediction on the image.

The prediction is generated as a 1D array holding 1 value, so we use the squeeze function to get the actual number out, and convert it to a string before we return it to the index page. We also need to perform one last check to test whether the label is ‘10’. As you may remember, the Street View House Number dataset used the label ‘10’ to represent the number ‘0’, so our model did the same. But when displaying the label to the user, if their image contained the number ‘0’ we want the label to match.

Let’s refresh our web page one more time and test it with a real image. You can find some examples to use in the GitHub repo for this project. Let’s test it by uploading ‘test-2.png’, and as you will see, it accurately predicts the label 2. The model we created was around 76% accurate on our testing data, so it will not generate the correct labels all of the time.

We have now created an end-to-end machine learning application. With a little bit of styling you could turn it into a nice looking web app which shows the uploaded image along with the prediction. The complete working source code is available at this repository.

Find out more about the courses offered at HyperionDev, including our popular online bootcamps in Full Stack Web Development, Mobile Development and Software Engineering. For more articles like this once, take a look at the HyperionDev blog.

This post was contributed by Ellie Birbeck.

GitHub for Beginners

Tutorials

GitHub for Beginners

GitHub for beginners. If you have just learnt to code or want to learn to code, find out about GitHub. Here’s a simple guide to GitHub for beginners.

You might have heard the terms ‘GitHub’ or ‘git’ used before, but perhaps you don’t know what they mean. If you have just learnt to code or are wanting to learn to code, you should learn about GitHub. Here’s a simple guide to GitHub for beginners.

Git and GitHub: What are they?

Git is a version control system for tracking changes in computer files and coordinating work on those files among a number of people. It’s mostly used for managing the source code in software development. It’s free and open source.

GitHub is a software development platform based on how git works. With GitHub, you can host and review code, manage projects, and build software alongside millions of other developers. Add your existing code to share with prospective employers or start new projects to keep yourself relevant. GitHub accounts are free, and it’s the best place to swap ideas and code with other programmers online.

What is version control?

GitHub and Git use version control. This mean it tracks the history of changes of the source code of a project, including what has been changed, by whom and when.

How many developers are involved in GitHub?

It’s the largest host of source code in the world, as of April 2017, with almost 20 million users and 57 million repositories. Think of GitHub as a social network rather than just a tool for developers.

Why do developers like GitHub?

‘GitHub is a good place to collaborate and meet with other developers,’ says Gareth Dwyer, software and operation developer at HyperionDev. ‘Personally, I publish the code for my tutorials there, and it makes it easy for others to submit any corrections or improvements.’ To check out Gareth’s code and his profile (he has 43 repositories available) on GitHub, look here.

Basically, the advantage is that groups of developers can work together on the same documents (often referred to as the source code) simultaneously without destroying previous versions of each other’s work.

The ‘Git Repository’, or project folder if you like, is a place where developers can host their files so that people can collaborate. The collaboration can be open source (or public), or closed for a specific group. The idea is similar to Google Docs, which allows for the collaboration on word processing and spreadsheet files.

GitHub for beginners: how do I get started with GitHub?

The first step is to set up a GitHub account – you can sign up on the front page. You’ll then be taken to an empty newsfeed pages, states LifeHacker. In the middle of the page there’s a bootcamp, which helps you set up your account. One of the first things you’ll do will be to set up a repository – on the top right of your account, there’s a ‘New Repository’ button.

If you want to read more simply-written technical articles like GitHub for beginners, check out the HyperionDev blog.

HyperionDev offers three 6-month part-time Online Bootcamps in Web, Mobile and Software Development. Book a free trial now!

Python NLP tutorial: Using NLTK for natural language processing

Tutorials

Python NLP tutorial: Using NLTK for natural language processing

This NLP tutorial will show you how to implement some key natural language processing techniques, using Python and NLTK including tokenization and stemming.

In the broad field of artificial intelligence, the ability to parse and understand natural language is an important goal with many applications. Online retailers and service providers may wish to analyse the feedback of their reviews; governments may need to understand the content of large-scale surveys and responses; or researchers may attempt to determine the sentiments expressed towards certain topics or people on social media. There are many areas where the processing of natural language is required, and this NLP tutorial will step through some of the key elements involved in Natural Language Processing.

The difficulty of understanding natural language is tied to the fact that text data is unstructured. This means it doesn’t come in an easy format to analyse and interpret. When performing data analysis, we want to be able to evaluate the information quantitatively, but text is inherently qualitative. Natural language processing is the process of transforming a piece of text into a structured format that a computer can process and begin to understand.

Requirements and Setup

For this tutorial we will be using Python 3, so check that this is installed by opening up your terminal and running the following command.

If you get stuck at any stage during this tutorial, get your own personal mentor to help you learn coding and switch careers.

python -v

Now we can set up a new directory for our project and navigate into it.

mkdir nlp-tutorial
cd nlp-tutorial

You can also optionally use a virtual environment for this project, with the following two lines of code which create our virtual environment and then activate it.

virtualenv nlp-tutorial-env
source nlp-tutorial-env/bin/activate

We’re now ready to install the library that we will be using, called Natural Language Toolkit (NLTK). This library provides us with many language processing tools to help format our data. We can use pip, a tool for installing Python packages, to install NLTK on our machine.

pip install nltk

We also need to download the necessary data within NLTK. As it’s a large library, we only need to download the parts of it which we intend to use. To do this, first open an interactive Python shell or new file, import the NLTK library, and then open the download window:

import nltk
nltk.download()

A window should open which looks similar to the one below. Here we want to select the book collection, and click download.

The download screen from NLTK

The download screen from NLTK
The download screen from NLTK
The download screen from NLTK

Our setup is now complete and we can begin the tutorial.

Dataset

To perform natural language processing, we need some data containing natural language to work with. Often you can collect your own data for projects by scraping the web or downloading existing files. The NLTK library helpfully comes with a few large datasets built in and these are easy to import directly. These include classic novels, film scripts, tweets, speeches, and even real-life conversations overheard in New York. We will be using a set of movie reviews for our analysis.

After importing a selected dataset, you can call a ‘readme’ function to learn more about the structure and purpose of the collected data.

from nltk.corpus import movie_reviews
movie_reviews.readme()

We can start trying to understand the data by simply printing words and frequencies to the console, to see what we are dealing with. To get the entire collection of movie reviews as one chunk of data, we use the raw text function:

raw = movie_reviews.raw()
print(raw)
plot : two teen couples go to a church party , drink and then drive .
they get into an accident .
one of the guys dies , but his girlfriend continues to see him in her life , and has nightmares .
what's the deal ?
watch the movie and " sorta " find out . . .
critique : a mind-fuck movie for the teen generation that touches on a very cool idea , but presents it in a very bad package .
which is what makes this review an even harder one to write , since i generally applaud films which attempt to break the mold , mess with your head and such ( lost highway & memento ) , but there are good and bad ways of making all types of films , and these folks just didn't snag this one correctly .
they seem to have taken this pretty neat concept , but executed it terribly .
so what are the problems with the movie ?
well , its main problem is that it's simply too jumbled .
it starts off " normal " but then downshifts into this " fantasy " world in which you , as an audience member , have no idea what's going on .
there are dreams , there are characters coming back from the dead , there are others who look like the dead , there are strange apparitions , there are disappearances , there are a looooot of chase scenes , there are tons of weird things that happen , and most of it is simply not explained .
now i personally don't mind trying to unravel a film every now and then , but when all it does is give me the same clue over and over again , i get kind of fed up after a while , which is this film's biggest problem .
it's obviously got this big secret to hide , but it seems to want to hide it completely until its final five minutes .
.....

As you will see, this outputs each of the reviews with no formatting at all. If we print just the first element, the output is a single character.

print(raw[0])
p

We can use the ‘words’ function to split our movie reviews into individual words, and store them all in one corpus. Now we can start to analyse things like individual words and their frequencies within the corpus.

corpus = movie_reviews.words()
print(corpus)
['plot', ':', 'two', 'teen', 'couples', 'go', 'to', ...]
print(corpus[0])
plot

We can calculate the frequency distribution (counting the number of times each word is used in the corpus), and then plot or print out the top k words. This should show us which words are used most often. Let’s take a look at the top 50.

freq_dist = nltk.FreqDist(corpus)
print(freq_dist)
print(freq_dist.most_common(50))
freq_dist.plot(50)
<FreqDist with 39768 samples and 1583820 outcomes>

[(',', 77717), ('the', 76529), ('.', 65876), ('a', 38106), ('and', 35576), ('of', 34123), ('to', 31937), ("'", 30585), ('is', 25195), ('in', 21822), ('s', 18513), ('"', 17612), ('it', 16107), ('that', 15924), ('-', 15595), (')', 11781), ('(', 11664), ('as', 11378), ('with', 10792), ('for', 9961), ('his', 9587), ('this', 9578), ('film', 9517), ('i', 8889), ('he', 8864), ('but', 8634), ('on', 7385), ('are', 6949), ('t', 6410), ('by', 6261), ('be', 6174), ('one', 5852), ('movie', 5771), ('an', 5744), ('who', 5692), ('not', 5577), ('you', 5316), ('from', 4999), ('at', 4986), ('was', 4940), ('have', 4901), ('they', 4825), ('has', 4719), ('her', 4522), ('all', 4373), ('?', 3771), ('there', 3770), ('like', 3690), ('so', 3683), ('out', 3637)]
Frequency Distribution
Frequency Distribution

The first line of our output is telling us how many total words are in our corpus (1,583,820 outcomes), and how many unique words this contains (39,768 samples). The next line then begins the list of the top 50 most frequently appearing words, and we can save our plotted graph as a .png file.

We can start to see that attempting analysis on the text in its natural format is not yielding useful results – the inclusion of punctuation and common words such as ‘the’ does not help us understand the content or meaning of the text. The next few sections will explain some of the most common and useful steps involved in NLP, which begin to transform the given text documents into something that can be analysed and utilised more effectively.

Tokenization

When we previously split our raw text document into individual words, this was a process very similar to the concept of tokenisation. Tokenisation aims to take a document and break it down into individual ‘tokens’ (often words), and store these in a new data structure. Other forms of minor formatting can be applied here too. For example, all punctuation could be removed.

To test this out on an individual review, first we will need to split our raw text document up, this time by review instead of by word.

reviews = []
for i in range(len(movie_reviews.fileids())):
reviews.append(movie_reviews.raw(movie_reviews.fileids()[i]))

The movie reviews are stored according to a file ID such as ‘neg/cv000_29416.txt’, so this code loops through each of the file IDs, and assigning the raw text associated with that ID to an empty ‘reviews’ list. We will now be able to call, for example, review[0] to look at the first review by itself.

print(reviews[0])
plot : two teen couples go to a church party , drink and then drive .
they get into an accident .
one of the guys dies , but his girlfriend continues to see him in her life , and has nightmares .
what's the deal ?
watch the movie and " sorta " find out . . .
critique : a mind-fuck movie for the teen generation that touches on a very cool idea , but presents it in a very bad package .
which is what makes this review an even harder one to write , since i generally applaud films which attempt to break the mold , mess with your head and such ( lost highway & memento ) , but there are good and bad ways of making all types of films , and these folks just didn't snag this one correctly .
they seem to have taken this pretty neat concept , but executed it terribly .
so what are the problems with the movie ?
……………………

Now taking the first review in its natural form, we can break it down even further using tokenizers. The sent_tokenize function will split the review into tokens of sentences, and word_tokenize will split the review into tokens of words.

from nltk.tokenize import word_tokenize, sent_tokenize

sentences = nltk.sent_tokenize(reviews[0])
words = nltk.word_tokenize(reviews[0])
print(sentences[0])
print(words[0])
plot : two teen couples go to a church party , drink and then drive .

plot

There are lots of options for tokenizing in NLTK which you can read about in the API documentation [here](http://www.nltk.org/api/nltk.tokenize.html). We are going to combine a regular expression tokenizer to remove punctuation, along with the Python function for transforming strings to lowercase, to build our final tokenizer.

from nltk.tokenize import RegexpTokenizer
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(reviews[0].lower())
print(tokens)
['plot', 'two', 'teen', 'couples', 'go', 'to', 'a', 'church', 'party', 'drink', 'and', 'then', 'drive', 'they', 'get', 'into', 'an', 'accident', 'one', 'of', 'the', 'guys', 'dies', 'but', 'his', 'girlfriend', 'continues', 'to', 'see', 'him', 'in', 'her', 'life', 'and', 'has', 'nightmares', 'what', 's', 'the', 'deal', 'watch', 'the', 'movie', 'and', 'sorta', 'find', 'out', 'critique', 'a', 'mind', 'fuck', 'movie', 'for', 'the', 'teen', 'generation', 'that', 'touches', 'on', 'a', 'very', 'cool', 'idea', 'but', 'presents', 'it', 'in', 'a', 'very', 'bad', 'package', 'which', 'is', 'what', 'makes', 'this', 'review', ...]

Stop Words

We’re starting to head towards a more concise representation of the reviews, which only holds important and useful parts of the text. One further key step in NLP is the removal of stop words, for example ‘the’, ‘and’, ‘to’, which add no value in terms of content or meaning and are used very frequently in almost all forms of text. To do this we can run our document against a predefined list of stop words and remove matching instances.

from nltk.corpus import stopwords

tokens = [token for token in tokens if token not in stopwords.words('english')]
print(tokens)
['plot', 'two', 'teen', 'couples', 'go', 'church', 'party', 'drink', 'drive', 'get', 'accident', 'one', 'guys', 'dies', 'girlfriend', 'continues', 'see', 'life', 'nightmares', 'deal', 'watch', 'movie', 'sorta', 'find', 'critique', 'mind', 'fuck', 'movie', 'teen', 'generation', 'touches', 'cool', 'idea', 'presents', 'bad', 'package', 'makes', 'review', 'even', 'harder', 'one', 'write', 'since', 'generally', 'applaud', 'films', 'attempt' ...]

This has reduced the number of tokens in the first review from 726 to 343 – so we can see that nearly half the words in this instance were essentially redundant.

Lemmatization and Stemming

Often different inflections of a word have the same general meaning (at least in terms of data analysis), and it may be useful to group them together as one. For example, instead of handling the words ‘walk’, ‘walks’, ‘walked’, ‘walking’ individually, we may want to treat them all as the same word. There are two common approaches to this – lemmatization and stemming.

Lemmatization takes any inflected form of a word and returns its base form – the lemma. To achieve this, we need some context to the word use, such as whether it is a noun or adjective. Stemming is a somewhat cruder attempt at generating a root form, often returning a word which is simply the first few characters that are consistent in any form of the word (but not always a real word itself). To understand this better, let’s test an example.

First we’ll import and define a stemmer and lemmatizer – there are different versions available but these are two of the most popularly used. Next we’ll test the resulting word generated by each approach.

from nltk.stem import PorterStemmer, WordNetLemmatizer

stemmer = PorterStemmer()
lemmatizer = WordNetLemmatizer()

test_word = "worrying"
word_stem = stemmer.stem(test_word)
word_lemmatise = lemmatizer.lemmatize(test_word)
word_lemmatise_verb = lemmatizer.lemmatize(test_word, pos="v")
word_lemmatise_adj = lemmatizer.lemmatize(test_word, pos="a")
print(word_stem, word_lemmatise, word_lemmatise_verb, word_lemmatise_adj)
worri worrying worry worrying

As you can see, the stemmer in this case has outputted the word ‘worri’ which is not a real word, but a stemmed version of ‘worry’. For the lemmatizer to correctly lemmatize the word ‘worrying’ it needs to know whether this word has been used as a verb or adjective. The process for assigning these contextual tags is called part-of-speech tagging and is explained in the following section. Although stemming is a less thorough approach compared to lemmatization, in practise it oftens perform equally or only negibly worse. You can test other words such as ‘walking’ and see that in this case the stemmer and lemmatizer would give the same result.

Part-of-Speech Tagging

As briefly mentioned, part-of-speech tagging refers to tagging a word with a grammatical category. To do this requires context on the sentence in which the word appears – for example, which words it is adjacent to, and how its definition could change depending on this. The following function can be called to view a list of all possible part-of-speech tags.

nltk.help.upenn_tagset()

The extensive list includes PoS tags such as VB (verb in base form), VBD (verb in past tense), VBG (verb as present participle) and so on.

To generate the tags for our tokens, we simply import the library and call the pos_tag function.

from nltk import pos_tag
pos_tokens = nltk.pos_tag(tokens)
print(pos_tokens)
[('plot', 'NN'), ('two', 'CD'), ('teen', 'NN'), ('couples', 'NNS'), ('go', 'VBP'), ('church', 'NN'), ('party', 'NN'), ('drink', 'VBP'), ('drive', 'JJ'), ('get', 'NN'), ('accident', 'JJ'), ('one', 'CD'), ('guys', 'NN'), ('dies', 'VBZ'), ('girlfriend', 'VBP'), ('continues', 'VBZ'), ('see', 'VBP'), ('life', 'NN'), ('nightmares', 'NNS'), ('deal', 'VBP'), ('watch', 'JJ'), ('movie', 'NN'), ('sorta', 'NN'), ('find', 'VBP'), ('critique', 'JJ'), ('mind', 'NN'), ('fuck', 'JJ'), ('movie', 'NN'), ('teen', 'JJ'), ('generation', 'NN'), ('touches', 'NNS'), ('cool', 'VBP'), ('idea', 'NN'), ('presents', 'NNS'), ('bad', 'JJ'), ('package', 'NN'), ('makes', 'VBZ'), ('review', 'VB'), ('even', 'RB'), ('harder', 'RBR'), ('one', 'CD'), ('write', 'NN'), ('since', 'IN'), ('generally', 'RB'), ('applaud', 'VBN'), ('films', 'NNS'), ('attempt', 'VB'), ('break', 'JJ'), ('mold', 'NN'), ('mess', 'NN'), ('head', 'NN'), ('lost', 'VBD'), ('highway', 'RB'), ('memento', 'JJ'), ('good', 'JJ'), ('bad', 'JJ'), ('ways', 'NNS'), ('making', 'VBG'), ('types', 'NNS'), ('films', 'NNS'), ('folks', 'NNS'), ('snag', 'VBP'), ('one', 'CD'), ('correctly', 'RB'), ('seem', 'VBP'), ('taken', 'VBN'), ('pretty', 'RB'), ('neat', 'JJ'), ('concept', 'NN'), ('executed', 'VBD'), ('terribly', 'RB'), ('problems', 'NNS'), ('movie', 'NN'), ('well', 'RB'), ('main', 'JJ'), ('problem', 'NN'), ('simply', 'RB'), ('jumbled', 'VBD'), ('starts', 'NNS'), ('normal', 'JJ'), ('downshifts', 'NNS'), ('fantasy', 'JJ'), ('world', 'NN'), ('audience', 'NN'), ('member', 'NN'), ('idea', 'NN'), ('going', 'VBG'), ('dreams', 'JJ'), ('characters', 'NNS'), ('coming', 'VBG'), ('back', 'RB'), ('dead', 'JJ'), ('others', 'NNS'), ('look', 'VBP'), ('like', 'IN'), ('dead', 'JJ'), ('strange', 'JJ') ...]

Vocabulary

So far we’ve mostly been testing these NLP tools on the first individual review in our corpus, but in a real task we would be using all 2000 reviews. If this were the case, our corpus would generate a total of 1,336,782 word tokens after the tokenization step. But the resulting list is a collection of each use of a word, even if the same word is repeated multiple times. For instance the sentence “He walked and walked” generates the tokens [‘he’, ‘walked’, ‘and’, ‘walked’]. This is useful for counting frequencies and other such analysis, but we may want a data structure containing every unique word used in the corpus, for example [‘he’, ‘walked’, ‘and’]. For this, we can use the Python set function.

corpus_tokens = tokenizer.tokenize(raw.lower())
vocab = sorted(set(corpus_tokens))
['plot', 'two', 'teen', 'couples', 'go', 'to', 'a', 'church', 'party', 'drink', 'and', 'then', 'drive', 'they', 'get', 'into', 'an', 'accident', 'one', 'of', 'the', 'guys', 'dies', 'but', 'his', 'girlfriend', 'continues', 'to', 'see', 'him', 'in', 'her', 'life', 'and', 'has', 'nightmares', 'what', 's', 'the', 'deal', 'watch', 'the', 'movie', 'and', 'sorta', 'find', 'out', 'critique', 'a', 'mind', 'fuck', 'movie', 'for', 'the', 'teen', 'generation', 'that', 'touches', 'on', 'a', 'very', 'cool', 'idea', 'but', 'presents', 'it', 'in', 'a', 'very', 'bad', 'package', 'which', 'is', 'what', 'makes', 'this', 'review', …]

This gives us the vocabulary of a corpus, and we can use it to compare sizes of vocabulary in different texts, or percentages of the vocabulary which refer to a certain topic or are a certain PoS type. For example, whilst the total size of the corpus of reviews contains 1,336,782 words (after tokenization), the size of the vocabulary is 39,696.

print("Tokens:", len(corpus_tokens))
print("Vocabulary:", len(vocab))

Conclusion

In this NLP tutorial, we have been able to transform movie reviews from long raw text documents into something that a computer can begin to understand. These structured forms can be used for data analysis or as input into machine learning algorithms to determine topics discussed, analyse sentiment expressed, or infer meaning.

You can now go ahead and use some of the NLP concepts discussed to start working with text-based data in your own projects. The NLTK movie reviews data set is already categorised into positive and negative reviews, so see if you can use the tools from this tutorial to aid you in creating a machine learning classifier to predict the label of a given review.

A Jupyter notebook with the complete running code can be found here.

Find out more about the courses offered at HyperionDev, including our popular online bootcamps in Full Stack Web Development, Mobile Development and Software Engineering. For more articles like this once, take a look at the HyperionDev blog.

This post was contributed by Ellie Birbeck.

Course Setup: Installing Python and Notepad++

Tutorials

Course Setup: Installing Python and Notepad++

Installing Python and Notepad - this tutorial will take you through the process of installing Python and Notepad on your computer

This article is intended to supplement the courses offered by HyperionDev. Whilst they can be used on their own if you’re interested in getting your own development environment set up, some of the steps mentioned are specifically for those taking our Python courses. On that note, if you haven’t already, why not sign up for one of our courses? (Full-time students learn for free!)

This tutorial will help you set up your Python development environment, which consists of the Python core which has all the files, programs and libraries needed to power your Python experience; as well as Notepad++ and IDLE, a Text editor and compiler respectively, for Python.

If you’re already taking a course with us or even if you’re reading for interest, follow the instructions below as written to fire up Python on your PC.

Instructions

  1. First we’ll install the Python core. These are all the libraries to allow you to write and compile Python on your PC. Click here to head to the Python download page.
Installing Python and Notepad
  1. You’ll see two options offered to you. There are some syntax and library differences between the 2.7.x and 3.x versions of Python, and so they’re offered separately for you to choose from. Our courses have been redesigned to work with the newest 3.x core so choose that option to download the Python installer.
  2. If you use Mac or Linux, you can find other downloads below the buttons. See the links for Linux and Mac OS X. Please choose appropriately if you are not using Windows.
  3. Once the download has completed, please open the Python installer and continue with the simple installation.
  1. For Notepad++, head on over to their site and you’ll be greeted with their download page.
  2. Note: If you’re not running Windows, this package isn’t relevant to you. In fact, as a Linux user, you’ll be able to use your favourite default text editor (gedit on Ubuntu, Kate on KDE and so on). If you’re on Mac, the OS’s default text editor will do just as well for the purpose of writing code.
  3. For Windows users: the easiest method is to choose the installable package for Notepad++. Choose the link as seen at the red arrow, download the package, and install it by following the prompts. There’s no difference based on which version of Windows you’re running.

That’s it! You’re all ready to get started developing in Python. Comment on this tutorial if you’re having problems or if you’re taking a course with us, the Portal has details of your trainer should you need help.

Author: Matthew de Neef

Date originally published: 24/03/16

Course Setup: Installing C++ and DevC++

Tutorials

Course Setup: Installing C++ and DevC++

Installing C++ and DevC++ - learn how to set up your C++ development environment, which consists of an Integrated Development Environment  for C++.

This article is intended to supplement the courses offered by HyperionDev. Whilst they can be used on their own if you’re interested in getting your own development environment set up, some of the steps mentioned are specifically for those taking our C++ courses. On that note, if you haven’t already, why not sign up for one of our courses? (Full-time students learn for free!)

This tutorial will help you set up your C++ development environment, which consists of an Integrated Development Environment for C++. This IDE allows you to write, compile and run C++ code. Unlike Python or Java, for Windows, the core C++ language files and libraries come packaged together with the IDE (in our case Dev C++) so you’ll only need to install a single program to get the full debug and coding features provided by the language. You can use an alternative compiler if you’d like such as Clang or Cygwin, but the easiest way to get going fast is to let Dev C++ handle the grunt work for you.

Note: If you’re not on Windows, read on to find out how to set up your C++ development environment.

If you’re already taking a course with us or even if you’re reading for interest, follow the instructions below as written to fire up C++ on your PC.

Instructions

Installing C++ and DevC++
  1. All you need to do is head over to SourceForge, where Orwell’s Dev C++ client is located.
  2. Click the green download button to get the setup files for Dev C++ and follow the installation instructions. It’s as simple as that

If you’re not on Windows:

We recommend downloading Code::Blocks, a full-featured IDE which automates the below process. Download and install it from here. If you’d like to code and compile manually, follow the steps below.

​

  1. Most distributions of Linux actually come with the core C++ language and compiler pre-installed. We’ll consider Ubuntu, which uses gcc to compile your C++ code.
  2. To access Linux’s C++ compilers, use your favourite text editor (such as gedit) to open the file you’d like to run (usually has a “.cpp” extension).
  3. Open your Ubuntu Terminal and change directory to the location of your “.cpp” file. (click here to learn how)
  4. Execute gcc /o <executable_filename> <yourcode>.cpp where <executable_filename> is the name of the file created upon compiling your code which you’ll run, and <yourcode> is the name of the file with your C++ code.
  5. To run your code execute gcc /<executable_filename>

That’s it! You’re all ready to get started developing in C++. Comment on this tutorial if you’re having problems or if you’re taking a course with us, the Portal has details of your trainer should you need help.

Author: Matthew de Neef

Date originally published: 24/03/16

The most important tool for any software development team

Tutorials

The most important tool for any software development team

Version Control System (VCS) - Git is an open-source platform for version control.

Working on any software project, especially within the context of an organisation that manages big software projects, will almost certainly expose you to the concept of a Version Control System (VCS). Knowledge of how to use a VCS is essential in any software developer role, as it’s the only real way to effectively build software collaboratively. Once you understand the full power of Git (the VCS discussed here) in code collaboration within teams, and versioning to prevent catastrophe, you’ll wonder why you haven’t been using it all along if you’re only starting out with it now.

VCS (Version Control System)
Source: Google

Git is an open-source platform for version control. It’s a smart modern way of collaborating on and developing software. These days there are two main proponents using the Git VC system, namely GitHub (by the company of the same name) and Bitbucket, by Atlassian.

What makes Git different to other version control software out there, and what makes a VCS preferable to use in the first place, aside from potentially saving you hours of work doing regression bugfixes? Let’s examine the reasons.

Snap Happy

When you’re working on code, each time you implement a new feature, fix a bug, or write modified code, you’d want those changes to be recorded somewhere. Those changes should also be a running stream, that each change is cumulatively saved over the previous one. This is what Git does, but with a difference. Instead of saving only the base version of each file plus a set of changes, each time you make a commit, Git takes a ‘snapshot’ of the file that’s changed, plus all the links and dependencies to other files, so it knows how the whole “filesystem” fits together. You might think this wastes data, but Git cleverly links to the previous identical stored file, if its contents haven’t changed. Doing things this way comes in very handy when considering how branching and the like works (discussed in the terms section.)

Remember that Git is the platform, GitHub is the service, and there are then any number of GUI clients that will do the Git-ing for you, including Visual Studio, Atlassian’s excellent SourceTree utility, and also SyntEvo’s great equivalent for Linux called SmartGit. To use Git, you can either choose to go hardcore and use console commands, or manage your projects using any of these Windows/Linux clients instead.

Data-Conscious

Git and internet
With Git, there’s no need to be connected to the internet

Us South Africans struggle with data usage problems; those of us that have uncapped ADSL generally laud it over the people having to make do with capped packages or, worse still, mobile 3G dongles. That’s why you’d think that a version control system nannying over your code each time it’s modified is sounding incredibly data-hungry. In the case of Git, however, you’ll have a database of your project’s entire history stored on your local computer. What’s more, new changes you make are appended into this changelog locally too. This means you can compare your current code to a historical copy, and make changes to your code as you go, without having an internet connection at all.

As soon as you do connect to the internet, all your local changes are synchronised to your repository in the cloud. It’s much faster this way, and doesn’t bind you to constantly needing a connection, so coding with version control when Eskom turns the lights out, or you’re somewhere in the Drakensberg without signal, is a definite possibility!

Git-speak

Before we examine the workflow in Git, it’s important to understand some key terms used when considering Git and version control:

  • Repository, or repo: This is the collection of files that defines a project. It has the code files, any of their dependencies, and Git-specific files to help it keep track of what’s what and what’s where. There are two types of repos, one offline, stored on each user’s computer, and a (mostly) identical version of it linked online. The whole point of the Git client is to keep these separate offline instances (of each collaborator to a project repo) in sync and playing nice with the one online repo.
  • Push/Pull: Pull is the action that updates your local repo with changes made by others in the online repo, and Push is the opposite of it. To avoid confusion, Git generally mandates pulling before pushing, to make sure that if more than one person has made changes to the same file, things don’t get overwritten.
  • Sync: Some Git GUI clients use this option, the “smart” Pull/Push.

​

  • Commit: The action of “applying” changes to code in a project. Usually accompanied by a statement you’d write, identifying what these changes have achieved (i.e. “Fixed bug where program would hang” or “Implemented saving feature”). The commit makes the snapshot of the changed files and the rest of the project, so you can roll back to historical ones should you mess up later.

​

  • Branch: The part of Git for fiddling. Say you’d like to take your current codebase, and design new features, or fiddle with the code, or work on different features of a project from other developers in your team, without affecting the current codebase by committing things that could potentially break it down the line. That’s what a branch is for: a parallel development “line” where you can make your own commits on the side without affecting the so-called master release. On most software projects, the rule of thumb is that any code in master should always be working.

​

  • Merge: When a branch’s code is reintegrated into the master branch (or another branch is reintegrated into the first branch). This usually happens once feature development has been tested. It’s also for merging code with others, and working on different features with others on different branches. See Pull Request below.

​

  • Pull Request: When the programmer of the code in the branch wishes to integrate their code into the main master branch of the project, a pull request is opened. This allows other collaborators to check the code, discuss any issues and make sure it’s ready before the merge to the main branch is done. This kind of thing often happens if you’re helping to add features to big open-source projects; you’d open a pull request and the main developers would check your code to make sure it was OK before it was merged into the main branch.
  • Fork: Creates a new repo with as basis, the repo you choose to fork. This allows you to use existing code as a base and develop on top of that. Any development on top of a forked repo is not considered for merging back into the original project. On a large scale, forking is often used with Linux distros, where new development is continued as a forked distro from an older, unmaintained distro or codebase.

​

  • Release: For most of its life, a Git repo consists of raw source code all over the place. Making a release is the way of “freezing” the code at a certain point and packaging it into a nice ZIP file for others to download. This release ZIP doesn’t get updated and is stored with info on what the release contains. Application version releases work this way.

Three Stages of Git

Let’s explain the concept of states in Git, to help make sense of all the jargon. This defines how things get done when you’re working with Version Control in the background.

Let’s examine a scenario:

  1. You’re wanting to start work on an existing project, but one that you haven’t got on your local device yet. You checkout the project from the remote server repository.
  2. The code is downloaded, into your working directory ready for you to start working.
  3. You make code edits to the project files yourself, and now you’re ready to integrate them back into the project that everyone else can see. You stage the files that have changed into the staging area.
  4. A commit action, well, commits, the changes you’ve made into the project, to the repository directory.
  5. Up to this point, this could all have been offline. You can sync to make the changes you’ve stepped through “stick” to the code in the remote repository.

​

Git-ting Creative

This is a very basic introduction to the workings of a version control system, and knowing this will allow you to keep your work organized, and save potential breakdowns if you end up breaking something. Git is much more powerful than this, enough to fill a large book, but this primer should help get you started.

Comment with your views on this article in the comments section below, and follow Hyperion Hub developments in the future if you’d like to see more articles like these for the South African market.

VirtualBox Installation Tutorial

Tutorials

VirtualBox Installation Tutorial

VirtualBox Tutorial - This tutorial will guide you through the steps of virtualising Ubuntu within your current Windows installation.

This tutorial will guide you through the steps of virtualising Ubuntu within your current Windows installation. (If virtualisation is new to you, Get the low-down on the concepts here)

VirtualBox – the free choice

There are a number of great virtualisation packages on the market. Oracle’s VirtualBox takes the cake because it’s free, compatible with Mac, many Linux distros and Windows hosts, and supports basically any OS you can think of as a guest. This tutorial shows you how to install and configure VirtualBox on Windows and how to install an Ubuntu 14.04/15.10 VM using VirtualBox. (Readers of our Ubuntu tutorial, this one is for you!).

  1. Download the Ubuntu of your choice from the site . The “LTS” edition is somewhat older, but is supported longer and can be more stable than the latest release. Choose 64-bit unless you’re running a PC with 2GB or less of RAM.
  1. Download and install the VirtualBox client that’s applicable for your OS. On the download site, choose the “VirtualBox for Windows hosts” link to get the installer. Once you’ve installed, launch the VirtualBox application, and you’ll see a UI similar to the one below (except yours will be empty!).
VirtualBox Tutorial

The VirtualBox UI.

  1. Now we’ll create a virtual machine. Click the blue “New” star and you’ll be presented with the Create Virtual Machine dialogue. If you see the screen below, choose the “Guided Mode” button and move to the next step.
VirtualBox Tutorial

The Expert Mode VirtualBox UI

Choose Guided Mode here.

  1. We’ll be asked to enter a VM name and choose what OS and type it is. VirtualBox is generally intelligent this way — it’ll detect the name you give the VM and try to infer the OS from that. For Ubuntu, Type should be “Linux” and Version “Ubuntu” as shown. Depending on whether you’ve chosen 32 or 64-bit ISOs in step 1, you’ll need to select the right option in “Version” as well. We’ve downloaded a 64-bit ISO so Version is “Ubuntu (64-bit)”.

Choosing a virtual machine name in VirtualBox

Setting up VM name.

  1. Next, we’ll specify how much of our computer’s RAM will be allocated to the VM. Bear in mind we need at least 1GB and on average 2GB+ RAM for our host system to work, so the general rule is always to allocate less than one and a half times the total system RAM we have to our VM. Unless your host PC has less than 4GB of RAM, we’d recommend choosing 1GB of RAM. You can always change this later in the settings should you need to.

Choosing a virtual machine RAM amount in VirtualBox

Choosing RAM allocation.

  1. Now for the interesting part; hard drive setup. Once again, the magic of VMs is that the hard drive “seen” by the VM is in fact just a file on your host PC. Any files we create on the VM will stay within this hard disk file. 8GB is fine if you’re using it to test. Choose 10GB or more if you’d like to install lots of extra programs. We’ll click “create a virtual hard disk” and adjust the size as mentioned. Be generous now as it’s tough to resize disks later.

Choosing a virtual machine hard disk size in VirtualBox

Choosing hard disk allocation.

  1. Click “create” and we’ve created a VM configuration. However, this is the equivalent of a blank computer without any data on it, so we’ll need to tweak a few more settings by choosing the orange “Settings” wrench icon.
  1. System settings let you control exactly which parts of your hosts hardware are available to the guest, and also how they are visible. To make sure the system will boot, check “Enable I/O APIC” in the “Motherboard” tab of the “System” settings.

Choosing a virtual machine setting in VirtualBox

Choosing system options.

  1. Also, we’ll choose “Enable PAE/NX” in the “Processor’ tab, and drag the “Processor” slider to the right to determine how many CPU cores the VM will get to “see” and use from your host machine. If your slider maxes out at “2 CPUs” leave the slider set to 1. If it’s max is “4 CPUs” or “8 CPUs”, move the slider to 2 or 3 respectively.

Choosing a virtual CPU core setting in VirtualBox

Choosing CPU core allocation.

  1. Importantly, we choose “Enable VT-x/AMD-V” in the Acceleration tab. This makes sure the virtualisation support in hardware from Intel or AMD CPUs is used. If this isn’t checked some VMs won’t boot. Ubuntu is forgiving with VT-x support though, so if the option is greyed out it’s likely not supported by your CPU or may be disabled in the BIOS, but Ubuntu will probably still boot.

Choosing a virtual machine VT-x setting in VirtualBox

Enabling VT-x support.

  1. Finally, for 3D graphics support, we’ll choose Display, drag the “Video Memory” slider to the far right and select “Enable 3D acceleration”. This allows the VM to make use of the hardware acceleration (read: graphics processing) abilities of the host. This works even if your PC doesn’t have a dedicated graphics chip.

Choosing a virtual machine GPU setting in VirtualBox

Choosing graphics memory allocation.

  1. To be able to boot and start installing on our new blank Ubuntu VM, we’ll need to tell VirtualBox to mount and use the downloaded Ubuntu ISO as an attached CD. For this, choose Storage and use the plus sign to create a new controller in either the SATA or the IDE columns. Now we’ll choose the disc image by pointing VirtualBox to its location. Once it’s mounted, the virtualiser instructs the VM into installing from the CD.

Choosing a virtual machine virtual CD setting in VirtualBox

Choosing the virtual CD ROM file for the Ubuntu installation.

  1. Once the CD is mounted, we’ll fire up the VM by choosing “Start” and follow the usual process to install Ubuntu. Click here to check out our Ubuntu installation guide. This time, we can easily minimize it and do some Windows work in the meanwhile.
  2. Once it’s done, you’ll be asked to reboot to complete installation, and you’ll see the Ubuntu VM launch, running as an application window inside of Windows:
  1. When the OS install is complete, you’ll probably notice the resolution being quite low and other problems with missing drivers. To solve this, whilst the VM is running after installation, click the “Devices” menu and choose the option to “Insert Guest Additions CD Image”. This will auto-mount utilities which you can install which, on reboot, will fix the resolution and other issues found without device drivers in place.

Installing VirtualBox Guest additions on Ubuntu

Use this command to install Guest Additions. (liberiangeek.com)

You’ve successfully set up an Ubuntu virtual machine, and our VM should now be ready for use, to use as you would a native installation of Ubuntu. Don’t forget that when ending your VM session, choose “Shut Down”, as this only closes the VM instance and won’t shut down your host OS.

Have you gotten to using Ubuntu in a VM? How do you find the concept? Comment with your views on this article in the comments section below, and follow Hyperion Hub developments in the future if you’d like to see more articles like these for the South African market.

An introduction to the Unix terminal – part 1

Tutorials

An introduction to the Unix terminal – part 1

Unix terminal - The terminal (or console/shell) is a core part of the Ubuntu distribution and other Unix-based operating systems.

A huge majority of the users of Microsoft Windows often won’t dare to venture near the command prompt; for them, a symbol of the dark days of DOS. In the world of software development, the terminal is an indispensable part of working with the OS and developing advanced software. This tutorial will introduce you to using the shell – using the Ubuntu terminal as an example – and the basics of making it useful to you.

Why Terminal?

The terminal (or console/shell) is a core part of the Ubuntu distribution and other Unix-based operating systems such as OSX, Debian, and even SteamOS, and it’s in fact really powerful. Most of the GUI-based interaction you have with the OS can be done via (and often just is automated by the GUI from) the terminal instead. It includes a vast number of additional libraries and packages compared to the Windows command prompt and new packages are simple to install. The terminal is even loaded with compiler tools for Python and C, and can host text editors in the mix (see later). It also simply isn’t possible to use certain tools needed for software development without the terminal. Let’s see how this all works.

This first part in a two-part tutorial series is an introduction to the terminal, and some basic commands. Follow along to part 2 for more advanced commands and options.

The Basics – launching, commands and manual pages

Let’s begin by launching the terminal.

  1. Click the Ubuntu Launcher icon in the top-left corner of your screen or press the “Super Key” (That’s the, ahem, Windows button)

Launching Ubuntu terminal.

  1. Type “Terminal” and click the first result to launch the terminal. You’ll see a prompt similar to the one shown. It’ll be in the form username@PC-name:~$. The Dollar symbol at the end denotes the user state (either normal ($) or superuser (#)) which is discussed later.​

The Ubuntu terminal prompt.

Any command you type will be in the form <command> <argument> <flags> for the most part. The command is the instruction to the terminal; the “verb” if you will. The argument is the “object” – what file/folder/object the command will act on. Some commands have no arguments, others take many. Finally, the flag is the “adjective” – how the command will execute on the file/folder/object specified by the argument. Note that the flag might be before the argument. In each of these examples, when typing terminal commands, press enter at the end of each one.

  1. For example, type ifconfig -v eth0. We’ll explain what this means later. You should see something similar to below. The command is “ifconfig”. The flag is “-v” and the argument is “eth0”. This means the ifconfig command is acting on ‘interface’ –help with the verbose (-v) flag. Don’t worry if this is confusing for now.

​

Executing ifconfig.

The easiest way to get help is by the –help flag. Issue this after a command to get written help or to find out what the command is for. Manual pages are even more useful, and offer detailed explanations on commands. To access it, prepend the command you’re using with man.

  1. Try this out. Type ifconfig –help and man ifconfig once you’ve tried the first command. You’ll see the help and man pages explain command usage as shown. Press “q” once you’re done reading the man pages to go back to the terminal prompt.

​

Extract of the –help result.

Extract of the man pages for ifconfig.

This gives you an idea of what the ifconfig command does, but we’ll return to give you a full explanation in part 2 of the tutorial.

File & folder management

Let’s look at some basic file and folder editing commands that are the bread and butter of the Terminal.

  1. Let’s show the contents of the folder or directory which we’re currently in. Make sure you’re back at the :~$ prompt, and type ls . You’ll see Terminal list the folder contents like in the image below. The colour-coding matters: Dark blue are folders, light blue are links, white are images, red are Ubuntu archives and green means the file can be executed.

​

Using ls on a folder to see its contents.

  1. Let’s switch from one folder to another. We want to go into the “Downloads” folder. To do this type cd Downloads. The terminal is case sensitive so watch your spelling. You’ll see the terminal prompt become username@PC-name:~/Downloads$ to tell you which folder you’re in. Issue ls in Downloads and you’ll see this folder’s contents.

​

Using cd to switch to the downloads folder.

  1. To go straight to a subdirectory (a folder in a folder, say) you’d type cd ~/main_folder_name/sub_folder_name/ replacing the folder names with your desired folder names. This saves having to issue cd for each subdirectory. To go up one directory, type cd .. which will, for example take you from your Downloads folder back to your Home folder.
  1. Now let’s do some folder gymnastics. We’ll create a folder called “test”. Make sure you’re back in your home folder (username@PC-name:~$). Type mkdir test and press enter.
  1. Nothing should appear to happen, but the directory has been created, and we can confirm this by issuing ls:

​

Confirming the existence of the “test” directory

  1. The rm command is basically the opposite of mkdir. We’ll show this by deleting our test folder. From your home folder (use ls to confirm that the “test” folder is there) type rm -r test and press enter.
  2. Again nothing should appear to happen but the folder is now gone. Type ls to check this.

That’s a very small sliver of the useful commands Linux offers, but after this, at least the principle of working in the terminal should be familiar to you. To see more configuration commands, follow along to our next tutorial where we discuss further commands.

Have you tried the Linux terminal? Thought of any other useful commands that would be good for a Linux starter? Comment with your views on this article in the comments section below, and follow Hyperion Hub developments in the future if you’d like to see more articles like these for the South African market.

Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Still have questions?

Contact our Admissions Team, and a real person will get back to you.

Events

Stay tuned for live online sessions and in-person events. Discover more from our bootcamps experience with insights from our team and dedicated spaces to ask questions. Lucky attendees might get a chance to get a hold of limited discount codes.

No items found.