Data Structures

Array, Objects, List, Dictionary

Data structures are built on primitive data structures like STING and BOOL

ARRAY is a way to give you a lot of VARS in one block

var = averageTemp = [];
averageTemp[0] = 79
averageTemp[1] = 82
averageTemp[2] = 68

When you push to an array it puts the value at the end

When you want to add a value to an array at the beginning it has to push all data one place.
This is very inefficient

Stacks and Queues

Stack is a list that you put something on the top and pushes all values down.
This is the fundamental of how program languages order function returns.
Like when you push a tray down in a buffet line, the last one in is the first one out.
It only allows access to the top element.
“LIFO” – last in first out.
Stack Overflow is when you run too many functions.
Peak is a way to see whats on top without removing it

Queues is a list where everything gets added to the end. Like a line, first in first out. Just like lining up to get to iPhone.
Amazon SQS – simple queuing service = good for messanging

Linked List
Each element uses 2 pieces of memory.
One piece is the actual value, the 2nd is a pointer that points to the next item in the array.
An original array requires that the next value be next to the previous one in an array.

Dictionaries
Key value pairs
Key = MyAddress
Value = Los Angeles

An object is essentially a dictionary

var myPets = {
cat: “Mr. Hyena”,
lizard: “Mr. Big Big”,
goat: “Wolf Who Ate Wall Street”
}

Array for loops are O(n2)

Dictionary allows you to map the “array”
console.log(map.keys());

Trees
When you do a lot of searching
A way of structuring an array so you can split values.
Uses 3 pieces of memory per value
Binary search tree
There are NPM tools to use this type of data structure in Javascript

Graphs
Helps GPS maps find the shortest routes.
Facebook uses their data ordering
Anything using AI utilizes graphs.

Algorithm Complexity

Head – O(1) grows like 2x input size x running time

List Items – O(n) – more scalable, less time

O(n2) –

“Quadratic time complexity”

3 nest for loops ~ O(n3)

Binary search

array = [ 1,2,3,4,5,6,7,8,9,10 ]
Search for 3 takes 3 steps
Search for 9 takes 3 steps

Even if we double the input we only add 1 step
array = [ 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20 ]

This is the most durable to change
O(log n) – faster than a linear algorithm

Example of O(n)

function solution(k, arr){
    var map = {};
    for (var i=0; i < arr.length ; i++){
        var tmp = k - arr[i];
        if (temp > 0 && map[tmp] == 1)
            console.log("Found the pair :", temp, arr[i]);
        else
            map[arr[i]] = 1;
    }
}

Technical Debt = using bad code or inefficient code now saying you will fix it later.

# Big O Analysis

Express the running times of the following algorithms in Big O notation. Justify your responses.

Some of these are just review. A few apply Big O to algorithms we saw before.

Assume the _worst case_ running time—i.e., consider only the _maximum_ number of instructions the algorithm could take.

What is the running time of…

* Selection sort?

* Insertion sort?

* Linear search?

* Binary search?

* Finding duplicates in an array?

### BONUSES

If you’re mathematically inclined, you might find these interesting. If not, feel free to take a stab anyway, but don’t worry too much about proving your solution.

What is the running time for an algorithm that—

* Finds all triplets `(x, y, z)` such that `x + y + z = n`, where `n` is specified by the user?

* E.g.: `threeSum(list, search)` will find all possible triplets of numbers in `list` that sum to `search`.

* Same question, but for doubles?

* In general, what is the running time for finding n-tuples in `list` that sum to `search`?

Using Handlebars.js

Handlebars.js is a great templating framework that gives you the latitude to create single page applications that are modular and quick to implement. The structure can be a bit confusing so I’ve included my source code from an example project I created.

This example also uses sequelize for MySQL queries. I launched the app using Heroku so you can see it in action as well.

Github: https://github.com/sethmh82/seq-eat-da-burger

Heroku Live Demo: https://quiet-river-66814.herokuapp.com

Here’s an example of handlebars being used to dynamically generate content.

    <div class="row" id="burgersDiv">
        <div class="col-lg-4" id="burgerList">
            <table>
                {{#each burgers}}
                    {{#unless this.devoured}}
                        <tr><td>
                            <div style="margin-right: 10px; font-size: 19px; font-weight: 400; background-color: #FFF; padding:5px 8px;">
                            {{this.burger_name}}
                            </div>
                            </td><td>
                            <form action="burgers/update/devour/{{this.id}}?_method=PUT" method="POST">
                                <input type="hidden" name="devoured" value="1" >
                                <button type="submit" class="btn btn-info btn-xs" id="devourBtn">EAT IT</span></button>
                            </form>
                            </td></tr>
                    {{/unless}}
                {{/each}}
            </table>
        </div>

Google Material Design Input Boxes

What is Google Material Design?

Google Design Elements
Google continues to expand the capabilities of web design with their “Google Material Design” a CSS3 styling technique utilizing Polymer allowing you to create rich animated applications.

Test out this CSS code on your next input box.

Check out Google’s Polymer design elements here.

Here is a list of dynamic references inside of Polymer:

8 Polymer Elements

paper-checkbox : User can tap the checkbox to check or uncheck it. Usually you use checkboxes to allow user to select multiple options from a set. If you have a single ON/OFF option, avoid using a single checkbox and use paper-toggle-button instead.

paper-dropdown-menu : is similar to a native browser select element. paper-dropdown-menu works with selectable content.

paper-input : is a single-line text field with Material Design styling.

paper-listbox : implements an accessible listbox control with Material Design styling. The focused item is highlighted, and the selected item has bolded text.

paper-radio-button : is a button that can be either checked or unchecked. User can tap the radio button to check or uncheck it. Use a to group a set of radio buttons. When radio buttons are inside a radio group, exactly one radio button in the group can be checked at any time.

paper-radio-group : A group of Material Design radio buttons

paper-slider : A Material Design slider

paper-toggle-button : Paper-toggle-button provides a ON/OFF switch that user can toggle the state by tapping or by dragging the switch.

Example Code

* { box-sizing:border-box; }

/* basic stylings ------------------------------------------ */
body 				 { background:url(http://scotch.io/wp-content/uploads/2014/07/61.jpg); }
.container 		{ 
  font-family:'Roboto';
  width:600px; 
  margin:30px auto 0; 
  display:block; 
  background:#FFF;
  padding:10px 50px 50px;
}
h2 		 { 
  text-align:center; 
  margin-bottom:50px; 
}
h2 small { 
  font-weight:normal; 
  color:#888; 
  display:block; 
}
.footer 	{ text-align:center; }
.footer a  { color:#53B2C8; }

/* form starting stylings ------------------------------- */
.group 			  { 
  position:relative; 
  margin-bottom:45px; 
}
input 				{
  font-size:18px;
  padding:10px 10px 10px 5px;
  display:block;
  width:300px;
  border:none;
  border-bottom:1px solid #757575;
}
input:focus 		{ outline:none; }

/* LABEL ======================================= */
label 				 {
  color:#999; 
  font-size:18px;
  font-weight:normal;
  position:absolute;
  pointer-events:none;
  left:5px;
  top:10px;
  transition:0.2s ease all; 
  -moz-transition:0.2s ease all; 
  -webkit-transition:0.2s ease all;
}

/* active state */
input:focus ~ label, input:valid ~ label 		{
  top:-20px;
  font-size:14px;
  color:#5264AE;
}

/* BOTTOM BARS ================================= */
.bar 	{ position:relative; display:block; width:300px; }
.bar:before, .bar:after 	{
  content:'';
  height:2px; 
  width:0;
  bottom:1px; 
  position:absolute;
  background:#5264AE; 
  transition:0.2s ease all; 
  -moz-transition:0.2s ease all; 
  -webkit-transition:0.2s ease all;
}
.bar:before {
  left:50%;
}
.bar:after {
  right:50%; 
}

/* active state */
input:focus ~ .bar:before, input:focus ~ .bar:after {
  width:50%;
}

/* HIGHLIGHTER ================================== */
.highlight {
  position:absolute;
  height:60%; 
  width:100px; 
  top:25%; 
  left:0;
  pointer-events:none;
  opacity:0.5;
}

/* active state */
input:focus ~ .highlight {
  -webkit-animation:inputHighlighter 0.3s ease;
  -moz-animation:inputHighlighter 0.3s ease;
  animation:inputHighlighter 0.3s ease;
}

/* ANIMATIONS ================ */
@-webkit-keyframes inputHighlighter {
	from { background:#5264AE; }
  to 	{ width:0; background:transparent; }
}
@-moz-keyframes inputHighlighter {
	from { background:#5264AE; }
  to 	{ width:0; background:transparent; }
}
@keyframes inputHighlighter {
	from { background:#5264AE; }
  to 	{ width:0; background:transparent; }
}

Connecting to MySQL Database in Node.js

Connecting Node.js to your MySQL database is extremely important to know for any system you will build where data storage is necessary. You can setup a local MySQL database on your system using MAMP and MySQL Workbench.

var mysql = require("mysql");

var connection = mysql.createConnection({
  host: "localhost",
  port: 3306,
  user: "root",
  password: "root", 
  database: "database_name"
});

Example of NodeJS with Geocoder, Inquirer, and Weather-js

First install your 3 dependencies in the same folder.

// Install Geocoder
$ npm install geocoder
// Install Inquirer
$ npm install inquirer
// Install WeatherJS
$ npm install weather-js

Then, you’ll need to have both userprompt.js, geocode.js and package.json in the same folder you are running the terminal command line from.

USERPROMPT.JS

The userprompt.js file should look like this:

var inquirer = require("inquirer");

inquirer.prompt([

  {
    type: "input",
    name: "name",
    message: "Who are you???"
  },

  {
    type: "list",
    name: "doingWhat",
    message: "What are you doing in my house??",
    choices: ["I made you cookies!", "No lie dude. I'm here to rob you.", "Uh. This is my house... Who are YOU???"]
  },

  {
    type: "checkbox",
    name: "carryingWhat",
    message: "What are you carrying in your hands??",
    choices: ["TV", "Slice of Toast", "Butter Knife"]
  },

  {
    type: "confirm",
    name: "canLeave",
    message: "Can you leave now?"
  },

  {
    type: "password",
    name: "myPassword",
    message: "Okay fine. You can stay. But only if you say the magic password."
  }

]).then(function(user) {

  
  if (user.myPassword === "myPassword") {

    console.log("==============================================");
    console.log("");
    console.log("Well a deal's a deal " + user.name);
    console.log("You can stay as long as you like.");
    console.log("Just put down the " + user.carryingWhat.join(" and ") + ". It's kind of freaking me out.");
    console.log("");
    console.log("==============================================");
  }
  else {

    console.log("==============================================");
    console.log("");
    console.log("Sorry " + user.name);
    console.log("I'm calling the cops!");
    console.log("");
    console.log("==============================================");

  }
});

the geocode.js file looks like this:

var geocoder = require("geocoder");
var inquirer = require("inquirer");
inquirer.prompt([
  {
    type: "input",
    name: "userInput",
    message: "Which location or landmark would you like to geocode?"
  }
]).then(function(location) {
  geocoder.geocode(location.userInput, function(err, data) {
    console.log(JSON.stringify(data, null, 2));
  });
});

Finally, run the following command, note that node does not require you to put the .js at the end of a file.

node userprompt

node geocode

C# Example of Math Expressions, Variables, and If Statements

Anyone getting into C# and ASP.NET development will likely be starting with basic expressions, variables, and if statements. Get familiar with these concepts:


private void radioButton1_CheckedChanged(object sender, EventArgs e) 
{ 
    string x = this.textBox1.Text; 
    string y = this.textBox2.Text; 
    if (x == "") //See if x has no value 
    { 
        x = "0"; //Set x to 0 
    } 
    if (y == "") //See if x has no value 
    { 
        y = "0"; //Set y to 0 
    } 
    int x_number = Convert.ToInt32(x); //Converts the string x to a number then stores it in x_number 
    int y_number = Convert.ToInt32(y); 
    int random = x_number + y_number; //Sets the integer variable random to the value of x_number plus y_number 
    string random_string = Convert.ToString(random); //Converts the integer random to the string random_string 
    this.label3.Text = random_string; 
}

SQL INNER JOIN and Full OUTERJOIN

The INNER JOIN keyword selects records that have matching values in both tables.

SELECT column_name(s)
FROM table1
INNER JOIN table2 ON table1.column_name = table2.column_name;

/// EXAMPLE ///

SELECT Orders.OrderID, Customers.CustomerName
FROM Orders
INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;

SQL FULL OUTER JOIN

The FULL OUTER JOIN keyword return all records when there is a match in either left (table1) or right (table2) table records.

Note: FULL OUTER JOIN can potentially return very large result-sets!

SELECT column_name(s)
FROM table1
FULL OUTER JOIN table2 ON table1.column_name = table2.column_name;

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
FULL OUTER JOIN Orders ON Customers.CustomerID=Orders.CustomerID
ORDER BY Customers.CustomerName;

What Are The C# Access Modifiers

public
The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.

What is MVC or Model, View, Controller

In object-oriented programming development, model-view-controller (MVC) is the name of a methodology or design pattern for successfully and efficiently relating the user interface to underlying data models. The MVC pattern is popular when coding with Java, C, and C++.

A Model : Represents the underlying, logical structure of data in a software application and the high-level class associated with it. This object model does not contain any information about the user interface.

A View : Is a collection of classes representing the elements in the user interface (all of the things the user can see and respond to on the screen, buttons, display boxes, etc.)

A Controller : Represents the classes connecting the model and the view, and is used to communicate between classes in the model and view.

More Basic:
Model = Handles data and business logic.
View = Presents data to the user in any layout form.
Controller = Receives user requests and calls appropriate resources to execute them.

MVC Follows This Basic Flow:

Let’s take the program Spotify

1. The user interacts with the user interface in some way, say they press the button to add a song to the playlist.

2. A controller handles the input event from the user interface, often via a registered handler or callback.

3. The controller notifies the model of the user action, possibly resulting in a change in the model’s state. In this instance the song is added to a playlist.

4. A view uses the model (indirectly) to generate an appropriate user interface (i.e. the view produces a screen displaying your music list made in Spotify). The view gets its own data from the model. The model has no direct knowledge of the view.

5. The user interface waits for further user interactions, which begins the cycle again.

Example of a MVC pattern : A calculator

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
// Note: The view should not send to the model but it is often useful
// for the view to receive update event information from the model. 
// However you should not update the model from the view.
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        frmCalcView view = new frmCalcView();
        CalculatorModel model = new CalculatorModel();
        CalcController controller = new CalcController(model, view);
        Application.Run(view);
    }
}
/// <summary>
/// The controller process the user requests.
/// Based on the user request, the Controller calls methods in the View and
/// Model to accomplish the requested action. 
/// </summary>
class CalcController : IController
{
    ICalcModel model;
    ICalcView view;

    public CalcController( ICalcModel model, ICalcView view)
    {
        this.model = model;
        this.view = view;
        this.view.AddListener(this); // Pass controller to view here.
    }

    public void OnClick( int number )
    {
        view.Total = model.SetInput(number).ToString();
    }

    public void OnAdd()
    {
        model.ChangeToAddState(); 
    }
}

Example of a MVC pattern : IController

/// <summary>
/// Windows Form that will host our MVC based functionality.
/// 
/// </summary>
public partial class frmCalcView : Form, ICalcView
{
    IController controller;
    public frmCalcView( )
    {
        InitializeComponent();
    }
    /// <summary>
    /// The view needs to interact with the controller to pass the click events
    /// This could be done with delegates instead.
    /// </summary>
    /// <param name="controller"></param>
    public void AddListener( IController controller )
    {
        this.controller = controller;
    }
    private void lbl_Click(object sender, EventArgs e)
    {
        // Get the text out of the label to determine the letter and pass the
        // click info to the controller to distribute.
        controller.OnClick((Int32.Parse(((Label)sender).Text)));
    }
    private void lblPlus_Click(object sender, EventArgs e)
    {
        controller.OnAdd();
    }

#region ICalcView Members
    public string Total
    {
        get
        {
            return textBox1.Text;
        }
        set
        {
            textBox1.Text = value;
        }
      }
#endregion
}

Here is a look at the model

 /// <summary>
    /// Calculator model, The model is independent of the user interface.
    /// It doesn't know if it's being used from a text-based, graphical, or web interface
    /// This particular model holds the state of the application and the current value.
    /// The current value is updated by SetInput
    /// </summary>
    class CalculatorModel : ICalcModel
    {
        public enum States { NoOperation, Add, Subtract };
        States state;
        int currentValue;
        public States State
        {
            set { state = value; }
        }
        public int SetInput ( int number )
        {
            if (state == States.NoOperation)
            {
                currentValue = number;
            }
             else if (state == States.Add)
            {
                currentValue = Add(currentValue , number );
            }
            return currentValue;
        }
        public void ChangeToAddState()
        {
            this.state = States.Add;
        }
        public int Add( int value1, int value2 )
        {
            return value1 + value2;
        }
        public int Subtract(int value1, int value2)
        {
            throw new System.ApplicationException(" Not implemented yet");
        }
}