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`?

Poloniex Exchange Hijacking Scheme Causes Investor Losses of $250 Million and Counting

This morning at around 8:30am PST, a group of nearly 30 scammers, carried out a hijacking scam on the cryptocurrency exchange Poloniex. The orchestrated scam has collectively robbed Poloniex investors of $250 Million… and increasing with each minute.

The heist began yesterday morning when investors noticed the interest rate for lending your BitCoin to other investors was much higher than usual. Typically you can earn around 0.003% for loaning your money to facilitate margin buying and selling. The default length of the loan is 2 days but most loans are paid back within a few hours. Drawn in by the unprecedented interest rates, Poloniex investors loaned out a upwards of $14 million. Most thought they would collect a little interest for an hour or two and then have the loan back in the account to continue trading.

Unknowingly, they had just funded the group of theives to sinister plot. The following morning as Poloniex users began checked their lending accounts, they were surprised to notice not a single loan had been paid back. Yes, it’s considered a gamble to loan money for potentially 2 days, as the crypto prices can fluctuate considerably in that time. Strangely though, as investors looked over the various coin prices, the market seemed to have flat-lined. There was very little upward or downward movement. At closer examination it became clear what was going on.

The group had set a substantial position just above and just below the current selling price. Some coins the position was above 75 bitcoin (BTC), roughly $1,000,000 converted to USD. Without enough buyers to buy all 75 BTC the price of the coin can’t increase. You could also try and sell your position, but the low end was locked in with another huge position. The positions were so close together that you would lose money on the trading fees if you bought and sold at all. As unknowing investors bounced back and forth between the high and low they were just digging themselves in deeper. As people tried to buy out the top money would just come from the bottom. The positions were set at just the right positions to gain the culprit a 1% return for each buy and sell.

As this continued for nearly an hour some investors had the idea they would just sell everything off and cash out. If only they didn’t have a significant amount of their money locked up in a loan. This frenzy caused the price of Bitcoin to start declining, which meant the value of the money locked up in the loan was also declining. In addition, the scheme included short selling of Bitcoin, where they gained money through by speculating on the decline of Bitcoin’s price.

In just under two hours the scam had already moved over $100,000,000 into the digital wallets of these coluding low lifes.

Poloniex has no customer support number or even a listed mailing address on their website. I reached out to them through their customer support contact form, but they have not responded with any comment on the event.

Currently, there is a sign-up form for anyone who sustained losses from this policy loophole and would like to join a class action lawsuit, forcing Poloniex to release the accounts and names of those involved to the authorities.

The point of digitial currency was to eliminate scams, theft, and allow for a broad consensus on all transactions. How and if this financial crime is resolved will set a tone for the trustworthyness and future of digital currency as a whole. If digital currency markets are as corrupt as insiders on Wall Street, then really what’s the point?

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"
});

Cryptocurrency Trading Patterns

POSTED : January 11, 2018

I created some cryptocurrency price graph overlays to analyze potential market patterns

DISCLAIMER!!! THIS IS NOT FINANCIAL ADVICE. DO NOT USE THIS AS A GUIDE FOR CRYPTO TRADING AS YOU WILL MOST LIKELY LOSE MONEY.

TIME DATA IS FOR PST, GRAPHS ARE FROM POLONIEX EXCHANGE

BITCOIN’S PRICE PLUMMETS EVERY JANUARY AROUND THE 16TH. HERE IS AN OVERLAY OF THE PAST 3 YEARS.

MONTHY TRADING PATTERN
MID-MONTH IS THE BEST TIME TO BUY

POSSIBLE CAUSE: PEOPLE WHO ARE PAID BI-MONTHLY RUN OUT OF FUNDS BY MID MONTH. SO, THEY SELL OFF SOME CRYPTOS,  THEN REBUY AFTER THEIR MID-MONTH PAYCHECK.

THE BUSIEST TRADING DAYS EACH WEEK ARE;
FRIDAY, MONDAY, WEDNESDAY, THURSDAY

NOT THE BEST TIMES FOR DAY-TRADING AS PRICES FLUCTUATE RAPIDLY AND IT’S HARDER TO PREDICT WHERE THE VALUE IS HEADED.

TYPICAL DAILY PRICE PATTERN

AS ONE MAJOR COUNTRY GOES TO BED THE PRICE FALLS, AS ANOTHER COUNTRY WAKES UP THE PRICE INCREASES
KOREA, USA, AND UK ARE THE LARGEST INVESTORS IN CRYPTOS

ETHEREUM DAILY PATTERN
MOST MAJOR COINS HAVE THIS EXACT PATTERN.
(THIS IS AN OVERLAY OF 4 RANDOMLY SELECTED DAYS FROM THE PAST 6 MONTHS)

IT APPEARS THAT MANY MAJOR CRYPTOCURRENCY PRICE PATTERNS MIRROR EACH OTHER.
IF YOU NOTICE ONE COIN DROPPING THE OTHERS ARE CLOSE BEHIND.

 

DO YOU JUMP ON A SPIKING COIN?

I ANALYZED SEVERAL PATTERNS THAT OCCUR WHEN ONE CRYPTO BEGINS TO SPIKE IN VALUE.

1. IT INEVITABLY PULLS PEOPLE IN. THIS CAUSES A SELL-OFF OF OTHER COINS.

2. WHEN OTHER COINS STOP DECLINING, IT IS A GOOD SIGN THAT THE SURGING COIN IS GOING TO STOP CLIMBING AS THE ADDED INFLUX OF PURCHASING HAS SLOWED. (BELOW, RIPPLE SPIKES AND SUDDENLY ETH, XLM, AND LTC. DECLINE SHARPLY. RIPPLE DROPS RIGHT WHEN XLM STARTS CLIMBING AGAIN.)

COINS THAT INCREASE IN VALUE WHILE BITCOIN’S PRICE DECLINES HAVE STEADIER GAINS OVER TIME.

BELOW, WHEN BITCOIN DROPS, PEOPLE FLOOD THEIR INVESTMENTS INTO OTHER COINS TO OFFSET THE LOSS.

NOTICE, ETHERIUM DID NOT BUBBLE LIKE RIPPLE AND STELLAR. EVEN WHEN BITCOIN FLUCTUATED OVER THE NEXT FEW WEEKS ETH MAINTAINED A STEADY LINE.

THE RIPPLE AND STELLAR BUBBLE CAUSED BOTH TO DIP LOWER THAN THEIR ORIGINAL VALUE. PATTERNS SHOW PEOPLE GET IN A SELL-OFF FRENZY AFTER A BUBBLE, CAUSING THE PRICE TO DIP BELOW THE “PRE-BUBBLE” PRICE.

(I ALWAYS DO RE-BUY POSITIONS SLIGHTLY BELOW THE “PRE-BUBBLE” PRICE)

5-YEAR CRYPTOCURRENCY MARKET CAP OVERLAY

Please note, this is the market cap for the entire cryptocurrency exchange market (not just Bitcoin).

bitcoin 4 year market pattern

SIGNS A CRYPTOCURRENCY PRICE MAY DECLINE.

1. IT IS APPROACHING MID-MONTH.
2.THE VALUE INCREASED EXPONENTIALLY AS BITCOIN’S DECLINED.
3. ANOTHER TOP COIN PRICE BEGINS TO SPIKE.
4.  OTHER TOP COINS ARE BEGINNING TO DROP.

5. PRICES DECLINE WHEN…
KOREA GOES TO BED.

I HAVE ABOUT A DOZEN OTHER OVERLAY ANALYSIS THAT I WILL POST LATER.

 -SETH HARDEN

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.

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; }
}

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

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.