Hi, I'm Miguel Mota.
A software developer and open source contributor. Learn more »

StackOverflow

Generate Self-signed SSL Certificate

・3 min read
Using HTTPS for your web application is a no-brainer, but sometimes it is not intuitively clear on how to get started on using SSL for your website. I’m going to be going over step-by-step on generating a self-signed certficate and testing it out on a Node.js web server. Generating Private Key First let’s generate a private key. The private key is used to decrypt the data encrypted by the public key. Only your server should have access to the private key. The generated RSA key is 1024-bit triple DES encrypted. It will ask you for a passphrase so make sure you remember it. Read more...

K-Means Clustering in JavaScript

・9 min read
Clustering is grouping of data or dividing a large data set into smaller data sets of some similarity. A well known clustering algorithm in unsupervised machine learning is K-Means clustering. The K-Means algorithm takes in n observations (data points), and groups them into k clusters, where each observation belongs to a cluster based on the nearest mean (cluster centroid). The distance between a data point and cluster centroid is calculated using the Euclidean distance. Read more...

Naive Bayes Classifier in JavaScript

・8 min read
The Naive Bayes classifier is a pretty popular text classification algorithm because of it’s simplicity. You’ll often see this classifier used for spam detection, authorship attribution, gender authentication, determing whether a review is positive or negative, and even sentiment analysis. The Naive Bayes classifier takes in a corpus (body of text) known as a document, which then a stemmer runs through the document and returns a “bag or words” so to speak. Stemming is the process of reducing an inflected word to it’s word stem (root). For example, the stem of the words “dreaming”, “dreamer”, and “dreamed”, is just “dream”. Read more...

Pixelate images with Canvas

・2 min read
There may be cases in which you want to pixelate an image, such as creating 8-bit style pixel art themed games or you simply want to give a hint of what an image is about without exposing too much. Turns out that it’s not complicated at all to do pixelation with canvas. View demo » The main methods needed from the canvas context are imageSmoothingEnabled for rendering crisp pixels and drawImage for drawing those pixels on to the canvas context. Read more...

Bitwise operators in JavaScript

・8 min read
Bitwise operators act on the level of individual bits which allows for fast comparisons and calculations. I’ll be going over a couple of ways to use bitwise opeartors in JavaScript since it’s not entirely clear at first. Some of the examples shown are from various sources which I’ve accumlated over time in which I’m going to elaborate on them. Bitwise AND Return a one if the two bits are both one. Read more...

ES6 Examples

・9 min read
If you’ve been up-to-date with what’s going on in the JavaScript world then you know that ES6 is currently the new hotness in town. I’m going to be showing examples of some of the nicest features in ES6, which include: Modules Classes Arrow Functions Destructuring Generators Promises Proxies Defaults Maps Weak Maps Sets Symbols Shorthand Objects Spread Operator Rest operator Constants Block Scoping Template Strings Modules Export example (math.js): let notExported = 'abc'; export function square(x) { return x * x; } export const MY_CONSTANT = 123; Import example (demo.js): Read more...

Deployment with Git

・2 min read
A Git hook allows you to execute custom scripts when an action occurs, such as when a commit or push is performed. Before I discovered git hooks, my deployment process consisted of pushing changes to my remote repository, SSH’ing into the server, navigating to the site directory, pulling the changes, and restarting the webserver. It wasn’t efficient at all and a waste of time doing that several times a day. I’ll explain how to set up a simple git hook making the deployment process a bit more effortless, but first I want to give credit to this how-to article which got me started. Read more...

Intro to Redis

・7 min read
Redis is an in-memory, key-value store that is fast. Really fast. Redis can hold hundreds of millions of keys in memory and handle tens of thousands of requests per second without breaking a sweat. It’s useful for caching data, maintaining sessions, keeping counters, queues, publish/subscribe real time notifications, and so on. There are many use cases for Redis due to it’s simple dictionary model that maps keys to values, but what one should be aware of is that it’s focus is not long-term data persistance. The whole Redis database is loaded into memory so there is a chance of data loss due to the fact that Redis first stores new entries in memory and then writes it to disk in the background after a certain period of time or amount of new keys have been accumulated. For example, if there were to be a power failure you could potentially lose a minute or two worth of data, which can or may not be fatal depending on your application. Of course, you can configure the threshold to something more comfortable which I will go over later. Read more...

Getting Started with Backbone.js

・17 min read
In this tutorial I will go over Backbone.js main components: Models, Collections, Views, and Routes. We will not be building an application but instead we will be going over a number of simple examples of each Backbone compoment, that hopefully after we are done you will have a firm understanding of Backbone.js and be able to put it all together. Models Models are a key component of Backbone applications. With model objects you can easily keep track of your data and update as needed. A strength of Backbone models is that you can synchronize your model data to the server which we will go over later. Read more...

Memoization – Caching function results in JavaScript

・2 min read
Memoization (based on the word memorable) is technique that caches the result of a function in order to avoid recalculation the next time the same function is called. Initially when the function is executed, the result gets added to an object holding the calculated results. When the function is called again, it checks the results object to see if already contains the result and if it does then return it. If it’s not cached, then calculate and store it. The code below is a modified version of the memoization example that I came across as I was reading Secrets of the JavaScript Ninja by John Resig. I also added bit of code to store the result in local storage so that we keep a copy of the results even after the page is refreshed. Read more...

Set up SSH keys

・1 min read
Having to type in a password in order to SSH into your server every single time is tedious and not the way to go. I will show you how to set up SSH keys so that you can elimate an extra step from your workflow. Generating keys On your local maching, generate a new SSH key with the command: # Generate new key. ssh-keygen -t rsa When asked for the file to save the key in, enter: Read more...

Node.js and Nginx on Ubuntu

・5 min read
In this tutorial I will show how to install and configure Node.js and Nginx on you Ubuntu server. Installing Dependencies The only dependency we really need is the build-essential package in order to be able to compile the Node.js source code. # Make sure to download the latest repos. sudo apt-get update # Required to run `make` command. sudo apt-get install build-essential # If you need to use https. sudo apt-get install libssl-dev # My favorite text editor. sudo apt-get install vim # Git to manage your repos. sudo apt-get install git Installing Node.js Head over to the Node.js Downloads page and copy the link to the source code tarball (node-<version>.tar.gz). Read more...

Raspberry Pi camera board video streaming

・4 min read
Raspberry Pi camera board So you got your Raspberry Pi and decided to get a Camera Board to do something awesome with it. Why not turn it a simple video streamer? That’s what I thought too. I wanted to set up a simple security camera for my home so that I can see spy on whoever is lurking around from wherever I am through a web browser. Turns out it wasn’t hard at all to set up. This blog post helped me get started. I’m going to walk you through all the steps I took. Read more...

Screenshots with getUserMedia API

・4 min read
With the getUserMedia API, it is now possible to access the user’s webcam and microphone using just JavaScript. What this means is that we can finally get rid of those nasty Flash plugins and use this native approace instead. At the writing of this post, only Firefox 17+ and Chrome 21+ have support for getUserMedia. Give credit where credit is due. The code is heavily inspired by HTML5 Rocks’ article Capturing Audio & Video in HTML5. Read more...

Basic HTML5 Audio Manipulation

・2 min read
Using JavaScript, we can create an audio object and manipulate it very easily. Below is some code (gist) to help you get started. You can play, stop, pause, and loop the audio. <!-- Audio Control Buttons --> <button id="play-button">Play</button> <button id="stop-button">Stop</button> <button id="pause-button">Pause</button> <button id="loop-button">Loop</button> // Basic HTML5 audio manipulation (function () { 'use strict'; // Set namespace. var NS = {}; // Control buttons. NS.playButton = document.getElementById('play-button'); NS.stopButton = document.getElementById('stop-button'); NS.pauseButton = document.getElementById('pause-button'); NS.loopButton = document.getElementById('loop-button'); // State variables. NS.looping = false; NS.paused = false; // Check for audio support. if ('Audio' in window) { // Create new audio object. NS.audio = new Audio(); // Check for ogg support. if (!!(NS.audio.canPlayType && NS.audio.canPlayType('audio/ogg; codecs="vorbis"').replace(/no/, ''))) { NS.audio.src = 'media/rimshot.ogg'; // Check for mp3 support. } else if (!!(NS.audio.canPlayType && NS.audio.canPlayType('audio/mpeg;').replace(/no/, ''))) { NS.audio.src = 'media/rimshot.mp3'; // Check for mp4 support. } else if (!!(NS.audio.canPlayType && NS.audio.canPlayType('audio/mp4; codecs="mp4a.40.2"').replace(/no/, ''))) { NS.audio.src = 'media/rimshot.m4a'; // Set default source to mp3. } else { NS.audio.src = 'media/rimshot.mp3'; } // Reset audio to beginning. NS.resetAudio = function () { NS.audio.pause(); NS.audio.currentTime = 0; }; // Play button click listener. NS.playButton.onclick = function (e) { e.preventDefault(); // Reset audio and play. NS.resetAudio(); NS.audio.play(); }; // Stop button click listener. NS.stopButton.onclick = function (e) { e.preventDefault(); // Reset audio. NS.resetAudio(); }; // Pause button click listener. NS.pauseButton.onclick = function (e) { e.preventDefault(); // Toggle off paused state and play audio. if (NS.paused) { NS.audio.play(); NS.paused = false; this.innerText = 'Pause'; // Toggle on paused state and pause audio. } else { NS.audio.pause(); NS.paused = true; this.innerText = 'Resume'; } }; // Loop button click listener. NS.loopButton.onclick = function (e) { e.preventDefault(); // Toggle off looping stated and reset audio. if (NS.looping) { NS.resetAudio(); NS.looping = false; this.innerText = 'Loop'; // Toggle on looping state and play audio. } else { NS.resetAudio(); NS.audio.play(); NS.looping = true; this.innerText = 'Stop Looping'; } }; // Audio ended event listener. NS.audio.addEventListener('ended', function() { // Reset after audio has ended. NS.resetAudio(); NS.pauseButton.innerText = 'Pause'; // If looping, replay audio after it has ended. if (NS.looping) { this.play(); } }, false); // No audio support. } else { alert('Your browser does not support the audio element.'); } })(); Check out the simple demo. Read more...

Slide Out Navigation using CSS3 Translate

・5 min read
There are many ways to create a navigation menu for a mobile site, but the kind that seems to be most popular at the time is a slide out menu, such as the one you see on the Facebook app. The advantages of using this type of menu is that it is easily accessible and there is a lot of room for list items since the user can scroll within the menu. Read more...

Call and Apply Methods in JavaScript

・3 min read
The call and apply methods in JavaScript might look complicated at first glance, but they are actually easy to wrap your head around. Suppose we have an object called square with a few properties: var square = { color: "red", getColor: function () { return "I am the color " + this.color + "!"; }, getArea: function (width, height) { return "My area is " + (width * height) + " feet!"; } }; It has a color property, and two method properties; getColor and getArea. Read more...

Sass Triangles

・1 min read
Creating CSS triangles shouldn’t be hard. Here’s a handy little mixin for creating triangles in Sass (gist): @mixin triangle($size:24px, $color:#000, $direction:up, $trim:false, $transparent:false) { content: ""; display: inline-block; width: 0; height: 0; border: solid $size; @if $direction == up { border-color: transparent transparent $color transparent; @if $transparent { border-color: $color $color transparent $color; } @if $trim { border-top-width: 0; } } @if $direction == right { border-color: transparent transparent transparent $color; @if $transparent { border-color: $color $color $color transparent ; } @if $trim { border-right-width: 0; } } @if $direction == down { border-color: $color transparent transparent transparent; @if $transparent { border-color: transparent $color $color $color; } @if $trim { border-bottom-width: 0; } } @if $direction == left { border-color: transparent $color transparent transparent; @if $transparent { border-color: $color transparent $color $color; } @if $trim { border-left-width: 0; } } }

Understanding Prototype in JavaScript

・4 min read
A prototype is an object from where other objects inherit properties from. All objects in JavaScript are descended from Object, a global object. Why this matters I’ll explain later, but for now let’s jump in to some code. Constructor and Methods Let’s define a functional object constructor called Quadrilateral and have width and height as parameters. // Define our constructor var Quadrilateral = function(width, height) { this.width = width; this.height = height; return this; } Traditionally if we wanted to have a method we would define it something like this: Read more...

Responsive Video

・1 min read
Dealing with responsive video can be quite troublesome. Here is a simple script you might find useful: (function() { // Responsive Video function responsiveVideo(selector) { // Get videos var videos = document.querySelectorAll(selector); // Loop through videos for (var i = 0; i < videos.length; i++) { var video = videos[i]; // Get aspect ratio var videoRatio = (video.height / video.width) * 100; // Stretch video video.style.position = "absolute"; video.style.top = 0; video.style.left = 0; video.setAttribute("width","100%"); video.setAttribute("height","100%"); // Add a wrapper to contain video var wrapper = document.createElement("div"); wrapper.className = "video-wrap"; wrapper.style.width = "100%"; wrapper.style.position = "relative"; wrapper.style.paddingTop = videoRatio + "%"; // Add it to the DOM var parentNode = video.parentNode; parentNode.insertBefore(wrapper, video); wrapper.appendChild(video); } } // Initialize. Make sure it's after DOMContentLoaded. responsiveVideo(".video"); })(); This will work with HTML5 video, and embeded video such as YouTube or Vimeo. Read more...