Sample Angular Website

Leave a comment Standard

So I’ve seen a lot of people using AngularJS but I see very few examples of a website made using it. That’s why I decided to post an example website to give you an idea of what a full website looks like using AngularJS. It has samples of some of the things you’ll commonly find in a website made entirely with Angular:

  •  Navigation & Routing
  • Providers & Directives
  • Controllers & Config Blocks
  • Data Calculations
  • Filtering

Sorry if you’re looking for Angular 2.0, this was made with Angular 1.5.8. View, fork and/or edit the files on Plunker!

Node JS Tutorial: How To Create A Simple Server

Leave a comment Standard

This will allow you to quickly setup a working node server in just a few easy steps.

1. Install Node.js

For Windows/Linux
Go to http://nodejs.org and download the
latest version of node for the operating system you want to install it on.

Open node and test if it’s working by typing 2+2 and hitting enter.

For Mac OS X
Visit Homebrew and then open your
command line and run (If you’re prompted to install command line tools go ahead and do that). :

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"

When that’s done run you can make sure your install was successful by running:

brew doctor

Then it’s a good idea run this to make sure you have the most up to date copy:

brew update

Then install node by running:

brew install node

Test your install by opening a command line and typing this to see the node version:

node -v

2. Install NPM

This package will help you install lots of node related libraries. You can find out more
about it by visiting https://npmjs.org.
Open a command line and type:

npn install express body-parser

If you get an error on Windows that says something along the lines of

Error: ENOENT, stat...

This means the NPM directory is missing from your filesystem. Navigate to where NPM should be as displayed by the error message and create an empty folder called npm.

3. Create These Simple Server Files

First let’s make our index.html. This should go in the directory you want to serve this index file from. So on a server it would be something along the lines of htdocs/public_html/directory/ or var/www/html and on your local computer it should be whatever directory you did your npm install.

Create the index.html file:

<html ng-app="app">
  <head>
    <title>My First Node Server File</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
    <link rel="stylesheet" href="css/stylesheet.css">
  </head>
  <body ng-controller="appCtrl">
    <div class="page-header">
      <h1>
        <i class="glyphicon glyphicon-certificate"></i>
        Congratulations!
      </h1>
    </div>
    <section>You have successfully created your first HTML5 node server.</section>
  </body>
  <footer>
    <a href="http://design1online.com" target="_blank">Tutorials by Design1Online.com, LLC</a>
  </footer>
</html>

Now let’s create the server.js file:

'use strict';

// Importing express and body parser libraries
var express = require('express');
var bodyParser = require('body-parser');

//this is a built in node library that handles the file system
var fs = require('fs');


/**
* Server configs
*/

/**
* The port to run your node server on
* 
* If you're running this on a web server this should be 80
* If you're running this locally try 8080 or 9080
*/
var BASE_PORT = 8080;

/** 
* The root directory of your files
*
* By default it uses the current folder this file is in
*/
var ROOT_DIR = __dirname + '/';
ROOT_DIR = fs.realpathSync(ROOT_DIR);
if (!fs.existsSync(ROOT_DIR)) {
	console.log('Error: cannot find working directory: ' + ROOT_DIR);
	exit();
}

/**
* Create an instance of express
*/
var app = express();

/**
 * Adds a simple logging, "mounted" on the root path.
 * Using Express middleware
 **/
app.use(function(req, res, next) {
	console.log('%s %s', req.method, req.url);
	next();
});

/**
 * Allows us to parse http body parameters as json
 **/
app.use(bodyParser.json());

app.use(express.static(ROOT_DIR));

app.listen(BASE_PORT, function() {
	console.log('Node server started @ http://localhost:' + BASE_PORT);
	console.log('Serving static files from ' + ROOT_DIR);
	console.log('Press Ctrl + c for server termination');
});

4. Start the Server

Go to the directory you installed npm in and that your index.html and server.js file reside. This is where you want to start the node server. In the console type:

node server.js

Now open your browser. If you installed node on a server then navigate to your index page on your website. You should see your new node js index file. If you’re running the node server on your local machine then type in http://localhost:BASE_PORT and replace BASE_PORT with the port number you configured in the server.js file. You’ll see your index file in your browser.

Congrats! You’ve successfully create your first node server.

PHP Tutorial: Dynamically Cache and Combine All CSS Files

Comments 10 Standard

Does your website use a lot of CSS files? If so did you know you can increase your website’s speed by caching and combining all of your CSS files into a single file?

Why Is It Useful?

Every time your browser loads a page on your website it has to make a request for all of the resources included or displayed on your page. Resources consist of things like image files, JS files, XML files and CSS files. If you find that you have more than one CSS file that you need to include on your website the requests required to load each of those files can sometimes take longer than a single request to load a single larger file. If you combine and cache your CSS files into a single file you can improve your website’s response time.

What’s a Cache?

A cache is a snapshot of a file at a moment in time. Typically you want to cache files that are static, meaning they don’t change often. If your file changes are fairly frequent then you end up generating a cache file too frequently for it to be of any use. That’s why this is a great technique to use with CSS files since they aren’t static but they don’t change that often either.

Setup

  1. Create two files, one called cache.css and another called cache.php.
  2. Place both of them in the same folder directory that you keep your style sheets in. We’ll use the CSS file to create a snapshot of all of our CSS files in our style sheet directory and we’ll use the PHP file to check generate and return the contents of our cache file.
  3. Change the permissions on the cache.php file to 0755. This will allow your PHP file to modify your cache.css file.
  4. Update the website page headers so instead of loading each of your individual .css files you’re now only loading your cache.php file

Before

<html>
     <head>
		<link href="stylesheets/filename1.css" rel="stylesheet" type="text/css" />
		<link href="stylesheets/filename2.css" rel="stylesheet" type="text/css" />
		<link href="stylesheets/filename3.css" rel="stylesheet" type="text/css" />
    </head>
    <body>
          This is what the header would look like before updating to the single file. Notice how you're making reference links to multiple .css files. Each of those requires your browser to make a request in order to load the three separate files.
    </body>
</html>

After

<html>
     <head>
		<link href="stylesheets/cache.php" rel="stylesheet" type="text/css" />
    </head>
    <body>
          This is what the header looks like. It now references our cache.php file which will give it the cached version of our CSS files.
    </body>
</html>

The Code

Inside of your cache.php file put the following code:

<?php 
/**
* File: cache.php
* Author: design1online.com, LLC
* Purpose: updates and loads the current css cache file
**/
$path = "path_to_your_public_directory/";
$dir = "name_of_your_css_folder_directory/";
$cachefilename = "cache.css";
$files_to_cache = array(
 	"filename1.css",	//add all of your css file names
 	"filename2.css", 	//that are inside your_css_folder_directory
 	"filename2.css"		//that you want to cache
);

//check for file changes
if ($handle = opendir($path . $dir)) {
 	while (false !== ($entry = readdir($handle))) 
        {
 		//if any of the $files_to_cache have changed recently we need to update the cache file
                //to do this we compare the last modified times on the files to see if one of our
                //$files_to_cache was updated more recently than our cache file
 		if (is_file($entry) && is_readable($entry) && substr($entry, -3, 3) == "css" &&
 		date(date(filemtime($entry)) > filemtime($path . $dir . $cachefilename)))
                {
                        //we've found a $file_to_cache that was updated more recently than the cache file
                        //so open the cache file and prepare to overwrite the contents with the changes
			$cachefile = fopen($path . $dir . $cachefilename, "w");

			//write all of the $files_to_cache to the cache file
			foreach ($files_to_cache as $filename)
			{
				$copyfile = fopen($path . $dir . $filename, "r");
				fwrite($cachefile, fread($copyfile, filesize($filename)));
				fclose($copyfile);		
			}

                        //close the connection to the cache file - this also updates the last modified time
                        //on the cache file so that it won't try to re-generate the cache file again until 
                        //a $files_to_cache has been changed again
			fclose($cachefile);

                        //since we found one file that was changed and we've updated the cache file 
                        //we no longer need to look for other files that may have potentially been updated, so 
                        //this will tell the loop to stop running
			break;
		}
        }
}

//output the contents of the cache file
//the header content type will make sure the
//browser interprets the file contents as text/css
header("Content-type: text/css");

//clear the buffers to prevent overflows
ob_clean();
flush();

//open and return the contents of the cachefile
//you'll notice your cache file contains all of your
//$files_to_cache merged into one
readfile($path . $dir . $cachefilename);

Last But Not Least

Update the $path, $dir and $cachefile name as needed at the top of your new cache.php file. This will tell the file where to find your css stylesheets and which ones you want to cache. Since this script looks at the last modified dates on our $files_to_cache we need to make sure and update one of the files in our $files_to_cache list in order for it to generate our initial cache.css file. To do this I would recommend making a change to one of your $files_to_cache or using touch to update the last modified time stamp on one of your $files_to_cache. Once you’ve done that you can view any page you updated to use cache.php as it’s stylesheet (see setup step 4) in any web browser to view the results of your efforts.

PHP Tutorial: Mixing HEX Colors within a Range

Leave a comment Standard

This seems to be coming up more often with the client games I’ve been working on. Now everyone wants  dynamic images and colors. This function will produce a random hexcode color within the range of the two hexcode colors given. It’s inclusive so you can also get the original colors returned.

<?php
/**
* Purpose: produce a color within a range of two hexcode colors
* Precondition: two hexcode colors, min/max range values optional
* Postcondition: one random color within the range returned
**/
function mixRange($color1, $color2, $MIN = 1, $MAX = 10)
{
    $range = rand($MIN, $MAX);
 
    $r = hexdec(substr($color1,0,2));
    $g = hexdec(substr($color1,2,2));
    $b = hexdec(substr($color1,4,2));
     
    $gr = (hexdec(substr($color2,0,2))-$r)/$MAX; //Graduation Size Red
    $gg = (hexdec(substr($color2,2,2))-$g)/$MAX;
    $gb = (hexdec(substr($color2,4,2))-$b)/$MAX;
     
    return str_pad(dechex($r+($gr*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($g+($gg*$range)),2,'0',STR_PAD_LEFT) .
        str_pad(dechex($b+($gb*$range)),2,'0',STR_PAD_LEFT);
}
?>

jQuery Tutorial: Scroll UI dialog boxes with the page as it scrolls

Comments 14 Standard

Do you have a jQuery UI modal dialog box that you want to scroll down as the page scrolls? I tried searching for someone who’d figured out a way to do it but I couldn’t find anything so I did the grunt work myself and thought I’d share it with you. This will scroll the dialog and the modal overlay so they stay correctly positioned on the page even if the user moves the browser window scroll bar with their mouse pointer or a mouse scroll wheel.

Scroll UI Dialog With the Page

$(document).ready(function() {
    $(document).scroll(function(e){

        if ($(".ui-widget-overlay")) //the dialog has popped up in modal view
        {
            //fix the overlay so it scrolls down with the page
            $(".ui-widget-overlay").css({
                position: 'fixed',
                top: '0'
            });

            //get the current popup position of the dialog box
            pos = $(".ui-dialog").position();

            //adjust the dialog box so that it scrolls as you scroll the page
            $(".ui-dialog").css({
                position: 'fixed',
                top: pos.y
            });
        }
    });
});

Demo and Code

Want to see how it works? Try the working JSFiddle demo and see for yourself.

PHP Function: Posted Time Ago – Facebook Style

Leave a comment Standard

So I won’t claim credit to this but I was browsing DevNetwork and I found a function that is both useful, succinct and awesome all rolled up into one. Using a php lookup table you can calculate the time since something was posted in PHP ie “so and so posted x time ago” facebook style.

function time_passed($timestamp)
{
     $diff = time() - (int)$timestamp;

     if ($diff == 0) 
          return 'just now';

     $intervals = array
     (
         1                   => array('year',    31556926),
         $diff < 31556926    => array('month',   2628000),
         $diff < 2629744     => array('week',    604800),
         $diff < 604800      => array('day',     86400),
         $diff < 86400       => array('hour',    3600),
         $diff < 3600        => array('minute',  60),
         $diff < 60          => array('second',  1)
     );

      $value = floor($diff/$intervals[1][1]);
      return $value.' '.$intervals[1][0].($value > 1 ? 's' : '').' ago';
}

Javascript: Charts, Graphs and Data Visualization for the Web

Comments 2 Standard

I was searching for some graphing, charting and data visualization libraries and I thought it might be helpful to share my finds and my favorite. Enjoy!

  • High Charts – Best looking, easiest to use and by far has the most features. The downside… it’s also the most expensive. A developer license will run you around $400 and an unlimited developer license is $3,600. They also have a stock ticker version. Nice stuff and my first choice if you can afford it.
  • jqPlot – is the best freeware, open source library out there in my opinion. It allows you to customize the colors and axis labels and has support for bar, scatter, bubble, pie and area graphs. It’s not as easy to use but it will get the job done if need be.
  • JSCharts -a JavaScript based chart generator that requires little or no coding. Just include our scripts, prepare your chart data in XML, JSON or JavaScript Array and your chart is ready. Free version watermarked. Paid versions range from $79 – $169 commercial license and $39 – $89 non-profit license.
  • dygraphs – an open source JavaScript library that produces produces interactive, zoomable charts of time series. It is designed to display dense data sets and enable users to explore and interpret them.
  • InfoVis – provides tools for creating Interactive Data Visualizations for the Web. Freeware.
  • g.raphael – Raphaël is a small JavaScript library that should simplify your work with vector graphics on the web and G.Raphaël is specifically for charts. If you want to create your own specific chart or image crop and rotate widget, for example, you can achieve it simply and easily with this library. Very simplified js commands to create graphs and charts. Freeware.
  • sigma – Web network visualization. Freeware. Lightweight JavaScript library to draw graphs, using the HTML canvas element. It has been especially designed to display interactively static graphs exported from a graph visualization software and display dynamically graphs that are generated on the fly.
  • JSXGraph – JSXGraph is a cross-browser library for interactive geometry, function plotting, charting, and data visualization in a web browser. It is implemented completely in JavaScript, does not rely on any other library, and uses SVG, VML, or canvas. JSXGraph is easy to embed and is less than 100 KByte if embedded in a web page. Freeware.
  • Bluff – Bluff is a JavaScript port of the Gruff graphing library for Ruby. It is designed to support all the features of Gruff with minimal dependencies; the only third-party scripts you need to run it are a copy. Freeware.
  • Visualization Free – an easy-to-use, no software download Web-based charting and visualization application. Not for commercial use.
  • Timeline – Interactive widget for visualizing temporal data. Freeware.
  • PlotKit – a Chart and Graph Plotting Library for Javascript. It has support for HTML Canvas and also SVG via Adobe SVG Viewer and native browser support. PlotKit is a complete rewrite of CanvasGraph. It is better structured and supported. Freeware, requires MochiKit 13 or higher.
  • Flot – JavaScript plotting library for jQuery, with a focus on simple usage, attractive looks and interactive features. Freeware.
  • Sparklines – generates small inline charts directly in the browser using data supplied either inline in the HTML, or via javascript.
  • MilkChart – This library will generate a graph similar to Microsoft Excel. Freeware.
  • Canvas 3D Graph – this is the only 3D graphing software I could find. Freeware.
  • TufteGraph – make graphs using jQuery. Configuration is by dynamic functions, allowing for a really compact API (very few options). Non-core layout is done via CSS rather than code. Freeware.
  • MooChart – is a mooTools plugin to draw bubble graphs on the canvas.
  • Protovis – Protovis composes custom views of data with bars and dots. Protovis defines marks through dynamic properties that encode data, allowing inheritance, scales and layouts to simplify construction. Freeware.
  • Rickshaw – an open source javascript toolkit for creating interactive time series graphs
  • Google Charts – not exactly perfect but sometimes the KIS (keep it simple) rule works best.
  • Protochart – open source library using Prototype and Canvas to create good looking charts. This library is highly motivated by Flot, Flotr and PlotKit libraries.