Django – Part 2


Django’s slogan is “The web framework for perfectionists with deadlines.” It accomplishes this in a few different ways, forced compartmentalization, built in development tools, and every feature you could ask for. Below we will discuss how to get started, and how see how Django handles MVC.

Getting started:

You first want to setup a virtual env. I am using Anaconda, so I would type in:

  1. conda create –name <your env name> django
  2. source activate <your env name>

Then you would use Django’s great command line tools to create your first project:

  • django-admin startproject <your app name>

Once you the command above you will have your very first Django app. However it won’t do very much. You can execute the following command to run the application:

  • python runserver

As you can see its pretty boring and does not due much. Django is built around the idea of applications, being different modules in your over all application. These modules are separate from the main project and encapsulate the different features of your application. You create a Django app by then running:

  • python startapp <app name>

By running the command you get a new directory generated in your folder structure.

Getting started with MVC (MTV):

Dajango does not use the MVC design pattern per say, rather it uses the MTV design pattern. MTV stands for:

M – model : This is a simple python classes.

from django.db import models
class Topic(models.Model):
top_name = models.CharField(max_length=264,unique=True)
def __str__(self):
return self.top_name
class Webpage(models.Model):
topic = models.ForeignKey(Topic) # notice how easy it is to take care of foreign keys
name = models.CharField(max_length=264,unique=True)
url = models.URLField(unique=True)
def __str__(self):

view raw
hosted with ❤ by GitHub

As you can see it is very easy to start building the inter model relationships. All models need to inherit from the Model class. This is all possible due to Djangos built in ORM. The ORM abstracts away the whole concept of having to work with a SQL DB, since it also provides a easy method revise your tables to reflect changes to your python models. This is simply done by using the:

  • python migrate
  • python make migrations < Dajango app name>

T – template : This is your html that displays model data through server side rendering.

<!DOCTYPE html>
{% load staticfiles %}
<meta charset="utf-8">
<title>Django Level Two</title>
<link rel="stylesheet" href="{% static "css/mystyle.css" %}"/>
<h1>YOLO LIFE</h1>
<h1>Here are your acces records</h1>
<div class="djangotwo">
{% if access_records %}
<th>Site Name</th>
<th>Date Accessed</th>
{% for acc in access_records %}
{{ }}
{{ }}
{% endfor %}
{% else %}
{% endif %}
<img src="{% static "images/b.jpg" %}" alt="Uh Oh, didn't show !">

view raw
hosted with ❤ by GitHub

Note that to serve these files, they need to be outside your main Django app, and they need to be reregistered in the Django settings file.

V – view : This is interestingly your controller.

from django.shortcuts import render
from django.http import HttpResponse
from first_app.models import Topic,Webpage,AccessRecord
# Create your views here.
def index(request):
webpages_list = AccessRecord.objects.order_by('date')
date_dict = {'access_records': webpages_list}
my_dict = {'insert_me':"This is coming from da Index.html!!!"}
return render(request,'first_app/index.html',context=date_dict)

view raw
hosted with ❤ by GitHub

As you can see above, you tie the data from your controller to your view by way of dictionaries. And tie your templates to your controllers to your views by specifying the url path name, and the file name.

A point of interest here, is that unlike some other frameworks your mapping a url to a method, rather then a whole class that contains different methods. This method mapping to is done using files that exist both in the directory of the main project and the django app.

The main project directory:

from django.conf.urls import url
from django.contrib import admin
from django.conf.urls import include
from first_app import views
urlpatterns = [

view raw
hosted with ❤ by GitHub

The Django app:

from django.conf.urls import url
from first_app import views
# is key word needs to be right
urlpatterns = [
url(r'^$',views.index, name='index'),

view raw
hosted with ❤ by GitHub

As you can see your using regex, to find a specific url, then mapping it to a method. The main file contains the main urls for the whole project and imports the urls specifically for the Django app. Whereas the Django app just contains the sub urls for that particular app.

The “; would hit the “first_app” app, then it would then hit any of the sub urls stored in the Django app urls file.

As you can see Django is not that hard use at all, and in most ways is significantly easier then other frameworks, that don’t have all these built in features. In the next blog post I will be discussing Models, the Django admin console, and how the ORM handles model changes.

You can find part one here.


Machine Learning Explained – Part 1.2

Please note that I will not be covering the mathematical portions, but rather the big ideas.

Model Representation

Can come in different forms, however at the end of the day we are trying to learn a function in order to map or training. Such that it becomes a good predictor of an output given a inputs, this is a sort of regression problem. Where as functions who’s outputs are limited to a few discrete outputs, given various inputs are for classification problems.

Cost Functions

These functions are used to measure the level of accuracy of our hypothesis functions (the function we learned), by measuring the difference between our predicted value and the true output. And then computing the average error by way of the “Mean Squared Error” function. In a single variable regression problem the hypothesis function reduces to being the equation of a line.

The objective becomes to minimize the cost (or error) function. If you have ever taken Calculus before you can do that easily by taking the derivate of the function, setting it equal to zero, solving for the parameter, and using that value in your learned function.

However its not always easy when given a large set of parameters. Therefor you can also use contour plots, that act like maps to the values that reduce cost function to zero.

Gradient Descent

An easy way to think about gradient descent is by, imagining your a blind person trying to find a ball in a hilly area. You don’t know where the ball is, but you know the ball has rolled into the deepest valley in the area. However your blind so you can’t see the depth in your surroundings. Therefor you have to use your feet to feel for the steepness of the ground in front of you. By doing so you take little steps in the direction of the most steepness. This is exactly what the gradient descent algorithm does as well. It takes little steps, gauges the steepness, and then moves in that directions till it finds the global minimum of the cost function’s derivative.

You can find the first part of this series here.

Intro to Python ? – Part 2

You can find Part 1 here.


In this part of the series we are going to cover the very basics of Python. You may be asking: “Its Python, how hard can it get ? Its just sudo code” well that is both true and false to a degree.


Python is a dynamically typed language, however it is strongly typed. This just means that you can set a variable to any sort of data type you want without declaring it first. However it doesn’t implicitly convert types for you.

# dynamic typing in action below
a = 5
print(a) # 5
a = 'afasdadfs'
print(a) # afasdadfs
print(2 + 10 * 10 + 3) # python follows bedmass !
mystring = 'This is a basic string'
mystring = 'helloGoodBye'
print(mystring) # helloGoodBye
# Slicing Strings
# Strings are like char arrays
# Slicing aka getting what you need out of them
print(mystring[2:]) # it includes everything from 2 and onwards
# output "lloGoodBye"
print(mystring[:3]) # up to but not indluding the index 3
# output "hel"
print(mystring[2:3]) # that is way the output of this is just "l"
# cause its not including the 3rd index
# output "l"
print(mystring[:]) # graps the whole string
# output "helloGoodBye"
print(mystring[::2]) # graps every second character
# starts from the very beginning, and includes the last answer in each step count
# always starts the count from Zero !
# output "hloody"
print(mystring[::3]) # graps every third character
# output "hloB"
# strings do not support char re-assignment
# mystring[0] = "t" <- does not work
# Some string methods
newstring = "I had a nice day today, hope tommorow is just as good"
print(newstring.split()) # if you put nothing in there, it will just split along the spaces
# you also have string interpolation
emotion = "Happy"
color = "Blue"
print("The color of the sky is making me {}. I love the {} color of the sky".format(emotion,color))
# can also do it this way as well
print("The color of the sky is making me {x}. I love the {y} color of the sky".format(x=emotion,y=color))
# can use 0 or 1 to represent boolen values
sam = True
print(sam) # outputs "True"
max = False
print(max) # outputs "False"

view raw
hosted with ❤ by GitHub


Python also contains different types array like structures. And they are all get dynamically sized of course. You have Lists and Dictionaries, they all work the way you intuitively think do, coming from another programming language. The only new sort of collection type, you will encounter is the Tuple. A Tuple is pretty much the same thing as a List however they are immutable and can not contain repeats of the same value.

# Can have mixed data types
# lists are mutable, they can have any sort of data type, or a mixture of different data types
mylist = [1,2,3]
mylist = ['random',3,4,2,32323,True,23232323,[2,3,2]]
print(mylist) # output "['random', 3, 4, 2, 32323, True, 23232323, [2, 3, 2]]""
print(mylist[1]) # output "3"
print(mylist[:3]) # also supports slicing, also has the same rules as slicing
#output "['random', 3, 4]"
# can have assignemnts
mylist[0] = "Love you"
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2]]"
mylist.append("NewItem1") # adds a enity to the end
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1']"
# can also extend the list aka merging another list to the end
print(mylist) # output "['Love you', 3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1', 1, 2, 3, 4, 22, 1, 4]"
#taking things off the list
print(mylist.pop())# pop modifys the list
# output "4"
print(mylist.pop(0))# pop also taking in where you want to take something out
# output "Love you"
print(mylist) # now the list is one value short of what it used to be
# output "[3, 4, 2, 32323, True, 23232323, [2, 3, 2], 'NewItem1', 1, 2, 3, 4, 22, 1]"
print(mylist.reverse())# reverse modifys the list permenantly as well. It does not return anything
# output "[1, 22, 4, 3, 2, 1, 'NewItem1', [2, 3, 2], 23232323, True, 32323, 2, 4, 3]"
mylist2 = [1,4,"55555",56,73,23,4,[1,2,3]]
print(mylist2.sort()) # by default sorts from lowest to highest. It does not return anything
# output "[1, 4, 4, 23, 56, 73, [1, 2, 3], '55555']"
# Key is always first, value is always second
# Have no order
# Can have different data types in other data types
my_stuff = {"key1":"Value","key2":"Value2","key3":{"123":[1,2,3]}}
print(my_stuff["key1"]) # output "Value"
print(my_stuff["key3"]["123"][0]) # output "1"
# can reassign different values to different pairs
my_stuff2 = {'lunch':'pizza'}
my_stuff2['lunch'] = 'burger'
print(my_stuff2['lunch']) # output "burger"
# tuples are "immutable" sequences
# the syntax difference between this, and a list is that it uses "()"
# rather then "[]"
t = (1,2,30,30)
print(t) # output "(1,2,3)"
#sets are unordered collections of "unique" elements
# if they are the same, then it does not include them
x = set()
print(x) #output "set([1, 2, 3.4, 5, 4])"
# every time you look at them, they come in a new order
# converting a list into a set, takes out all the same numbers
converted = set([1,2,3,4,5,6,7,3,3,3,3,32,"2",2,2]) # cannot do this -> set([1,2,3,4,5,6,7,3,3,3,3,32,2,2,2,2],[12])
print(converted) # outputs "set([32, 1, 2, 3, 4, 5, 6, 7])"

view raw
hosted with ❤ by GitHub

Control Flow

It’s pretty basic.

x = 1
y = 1
# basic ifs
if x == y:
if 2 > 1:
print("Hello as well")
# an else if is a "elif"
if 1 == 1:
elif 2 == 3:

view raw
hosted with ❤ by GitHub


Python does not find “for” loops pythonic that is way it favors “For In” loops instead. maybe asking: “What if I just want to print something 3 times ? do I have to make a list with three elements ?” The answer is no, you can use a “generator” shown in the gists below. Python also has something called “list comprehension” its very nifty to write compact and concise code.

#For Loops
seq = [1,2,3,4,5,6,3]
for item in seq:
dick = {"SAM":1,"FRANK":2,"Dan":3}
for it in dick:
print(it) #outputs the keys
print(dick[it]) #outputs the values
myPairs = [(1,2),(3,4),(5,6)]
for item in myPairs:
print(item) # just prints the tuples in the list
# can also be used in: tuple1,tuple2
for (tuple1, tuple2) in myPairs:
#known as unpacking tuples
#While Loops
i = 0
while i < 5:
print("i is: {}".format(i))
i = i + 1
range(0,20) # generates up to, but not including 20
# is a generator
# have to convert it to a list, to properly use it
for s in list(range(0,22)):
# also stuff like "list comprehension"
x = [1,2,3,4,5]
# your taking each value in "x" and taking the power of 2 of it
# then you putting all results into a list by using the square braces
print([num**2 for num in x])

view raw
hosted with ❤ by GitHub


You can go here to find all the relevant code, in order.

Machine Learning Explained – Part 1.1

You can see why I started this series here.

What is machine learning ?

  • My definition:
    • When you tell a machine to learn from experience rather then, explicitly giving it a bunch of instructions.
  • Course Definitions:
    • “the field of study that gives computers the ability to learn without being explicitly programmed.” – Arthur Samuel
    • “A computer program is said to learn from experience E with respect to some class of tasks T and performance measure P, if its performance at tasks in T, as measured by P, improves with experience E.” – Tom Mitchell

Supervised Learning:

You can think of this like teaching a small child how to do something you already know. Such as counting objects, or throwing a ball. Another way of thinking about it is that you give the machine the data, knowing that there is some relationship there. Then having the machine find it by its self.

This type of learning comes in two different flavours:


Given a bunch of data and asked to predict what will happen next. An example will could be: “given all the historical data about housing prices, what will be the price of a house in 2020 ?” We are mapping input data to a continuous function to.


Take the input data, and give me discrete outputs (classifications) . For example if you were to take data on students and predict which students would become engineers. Here we still know what factors really influence the result, which still makes it supervised learning.

Unsupervised Learning:

We have mountains of data that we think is random and has no structure. We have no idea what the relationships are between the variables. So we let our machine loose on the data to discover the relationships between the different variables. And it starts to cluster the data into different piles.

Django – Part 1

Django Reinhardt a jazz legend

No I am not talking about this guy to the left.

I am actually talking about the web framework written in Python. Now the reason that I have even started learning this, is cause I wanted to see what all the hype is about. Plus I wanted to get a better understanding of the Python language its self.

Now I come from the world of Express.js which is kinda of like Flask, in terms of its bare-bones nature. So when I first saw Django I was reminded of ASP.NET, and Ruby on Rails. You might be thinking what sort of nonsnese is this kid spouting ? How the can he put two of the most loved opens sourced projects next to, Microsofts evil ways. And to that I respond with: A) Microsoft is not evil, and B) I say that since all three of these frameworks have so much built in functionality, that they become opaque. Opaque as in not transparent as in have to use for along time to really understand how they work.

Anyways this is a post letting you guys or gals out there know, I am going to be making a tutorial series as I start to learn the framework.

Yes I know that all my posts are starting to seem like tutorials or updates. I promise they will eventually be about something else 😅

Getting Started with Express.js


Raise your hand if you already know the MVC design pattern ! … oh right you can’t.

You can look at one of my previous blog posts here. Now that we have gotten that out of the way. Express.js provides an incredibly simplistic and transparent way to develop APIs for your applications. It’s one of the most popular frameworks to run on the Node.js platform.

You simply define your routes, define what you want to send out and pull in, and your golden 👍

Setting it up:

var express = require('express')
var app = express()

view raw
hosted with ❤ by GitHub


app.get('/', function (req, res) {
res.send('hello world')

view raw
hosted with ❤ by GitHub

Here you can see the route in question is just a slash. That means that when ever anyone hits the https://”your domain”/, this route gets triggered (since it is a GET request). Once the route gets triggered it executes the function, that has the “req”, and “res” variables. The “req” is your request object, and the “res” is your response object. You can put different things in the res object and it gets passed along to be rendered in HTML.

This same sort of logic can be applied to POST and PUT requests.

Folder Structures:

You can use a variety of different folder structures. What ever folder structure you use, make sure its suited for the type of app your going to be building. You can checkout an example over here.

And your done ! Easy as that. You may be thinking WTF is that really it ? Why do people want to use Express.js if this is it ? Well the answer is that the frame work does not lock you into, using any specific way of doing things. Therefor you can use any sort of authentication, object relational mapper, session manager, or data base you want.

You can find the best 40 packages most commonly used here.