Error on “npm install gulp –save-dev”

Using a PC at work so unable to reap the benefits that I get from CodeKit 2 on my mac at home, I’ve mean meaning to get Grunt or Gulp into my workflow.

Always one to jump on a bandwagon, I decided to choose Gulp over Grunt as the newer task runner seems to be gaining traction over the warthog. A sucker for a logo, I also prefer the Gulp logo.

Starting a new project this afternoon, I decided to spend the final hours of the working week getting set up and accustomed to Gulp.

Our dev server at the office is running Ubuntu 11.10 so it was a bit of a struggle updating dependencies to actually get node.js installed. A bit of brainstorming with Sam (read: Sam, the unix genius, took the reins did it for me) and node was installed.

Following the setup instructions I hit a hurdle when trying to install Gulp to my project folder. With the command:

npm install gulp --save-dev

I was getting a lengthy error:

npm WARN package.json htdocs@0.0.0 No repository field.
npm WARN package.json gulp-uglify@1.0.1 No README data
npm WARN package.json gulp@3.8.8 No README data
npm ERR! Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR!     at Error (native)
npm ERR!  { [Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json']
npm ERR!   stack: 'Error: EACCES, chown \'/path/to/dir/htdocs/node_modules/gulp/package.json\'\n    at Error (native)',
npm ERR!   errno: -13,
npm ERR!   code: 'EACCES',
npm ERR!   path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_finish_call: 'chown',
npm ERR!   fstream_type: 'File',
npm ERR!   fstream_path: '/path/to/dir/htdocs/node_modules/gulp/package.json',
npm ERR!   fstream_class: 'FileWriter',
npm ERR!   fstream_stack:
npm ERR!    [ '/usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19',
npm ERR!      '/usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7',
npm ERR!      'Object.oncomplete (evalmachine.:93:15)' ] }
npm ERR!
npm ERR! Please try running this command again as root/Administrator.

npm ERR! System Linux 3.0.0-12-generic-pae
npm ERR! command "node" "/usr/local/bin/npm" "install" "gulp" "--save-dev"
npm ERR! cwd /path/to/dir/htdocs
npm ERR! node -v v0.13.0-pre
npm ERR! npm -v 1.4.26
npm ERR! path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_path /path/to/dir/htdocs/node_modules/gulp/package.json
npm ERR! fstream_type File
npm ERR! fstream_class FileWriter
npm ERR! fstream_finish_call chown
npm ERR! code EACCES
npm ERR! errno -13
npm ERR! stack Error: EACCES, chown '/path/to/dir/htdocs/node_modules/gulp/package.json'
npm ERR! stack     at Error (native)
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/fstream/lib/writer.js:308:19
npm ERR! fstream_stack /usr/local/lib/node_modules/npm/node_modules/graceful-fs/polyfills.js:143:7
npm ERR! fstream_stack Object.oncomplete (evalmachine.:93:15)
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /path/to/dir/htdocs/npm-debug.log
npm ERR! not ok code 0

After A LOT of trouble shooting, we discovered the issue was caused by npm being unable to change of the owner of package.json because the drive the site resided on (a mounted NAS) was in NTFS format. Rather than pull my hair out and try and find a work around, I moved the site to the main drive and everything was gravy.

CodeKit 2 replacing hostname instances with preview URL

After settings up a new project for a quick static build using CodeKit 2, I noticed some strange (and buggy) behaviour an interesting feature.

It appears that when previewing a project through CodeKit 2′s preview, it replaces all instances of the hostname specified in the project’s “External Server Address” with the preview URL.

In my case, I’d set up my host in MAMP Pro as “GWAC”, pointing to this in CodeKit 2′s
“External Server Address”

mampScreen Shot 2014-09-09 at 8.49pm

 

Wherever the string “GWAC” appears in my files, it is replaced with CodeKit’s preview URL. ie:

Screen Shot 2014-09-09 at 8.53pm

becomes:

Screen Shot 2014-09-09 at 8.54pm

 Update

This is expected behaviour. Makes sense:

 

PHP Recursive Function to Build a Site Tree / Site Map

A problem faced fairly regularly is the need to generate a site tree either for a menu or a site map.

Assuming your page structure in your database is along the lines of:

intPageId strPageName intParentId
1 Top Level Page X 0
2 Top Level Page Y 0
3 Child Page X 1
4 Grandchild Page X 3
5 Grandchild Page Y 3

Giving you a visual structure of:

Site tree structure

I’m a developer, not a designer. Don’t judge me

You can achieve this fairly simply in with the following PHP recursive function to get your page structure into an array. Note, I have used the Laravel query builder in this example as the project I wrote this for was a Laravel project, but this can be swapped out with a query builder from whatever framework you are using or with PHP’s PDO (or any of the lesser PHP APIs for working with databases).

function generateSiteTree($startAt)
{
	if ($children = \DB::table('cms_pages')->where('intParentId', '=', $startAt)->get())
	{
		$thisLevel = array();
		foreach ($children as $child) 
		{
			$thisLevel[$child->intPageId] = $child;
			$thisLevel[$child->intPageId]->children = generateSiteTree($child->intPageId);
		}
		return $thisLevel;
	}
 
}
 
$tree = generateSectionSiteTree(0);
 
 
print_r($tree);

That’s it.

Bonus recursive function

The project I wrote this function for required me to be able to reel off the site tree only for the top level parent of the current page, regardless of however deep you currently are.

This is easily achieved with this function:

function recurseToFindSectionParent($pageId)
{
	$current = \DB::table('cms_pages')->where('intPageId', '=', $pageId)->first();
 
	if ($current->intParentId == 0) //we've reached the top of the chain
	{
		return $current->intPageId;
	}
	else //keep going
	{
		return recurseToFindSectionParent($current->intParentId);
	}
}
$topParentID = recurseToFindSectionParent($currentPageId);

You can now feed the ID of the top level parent into the generateSiteTree function:

$tree = generateSiteTree($topParentID);

Upload Progress Bar with jQuery

Another quick post detailing a method for creating an upload progress bar with jQuery for file uploads. More for self reference than anything.

This example is using XHR.upload.onprogress to return a loaded (bytes uploaded) and total (total bytes of the file) value so an upload progress can be computed. We are using the jQuery form plugin for uploading files. We take the “loaded” and “total” values to display and update a progress indicator (status bar and the displayed percentage). Once the AJAX upload has completed, we reset and hide the progress indicator.

Boom.

$(this).ajaxSubmit({
    target: '#output',
	xhr: function()
	{
		myXhr = $.ajaxSettings.xhr();
        if (myXhr.upload)
        {
            $('#progressBar').show();
            myXhr.upload.addEventListener('progress', function(ev){
            	if (ev.lengthComputable) {
	                var percentComplete = Math.round((ev.loaded / ev.total) * 100);
			$('#percentage').text(percentComplete + '%');
			$('#status').css('width', percentComplete+'%');
	        }
            }, false);
            myXhr.upload.addEventListener('load', function(ev){
            	$('#progressBar').hide();
            	$('#percentage').text('0%');
		$('#status').css('width', '0%');
            }, false);
        }
        return myXhr;
	},
	dataType: 'json',
        success:  afterSuccess
});

HTML for the progress indicator:

<div id="progressBar">
	<div id="status"></div>
	<div id="percentage">0%</div>
</div>

CSS for the progress indicator:

#progressBar{
	width: 350px;
	text-align: center;
	height: 16px;
	position: fixed;
	left: 50%;
	margin-left: -175px;
	z-index: 9;
	border:1px solid #9d9d9d;
	border-radius: 5px;
	overflow: hidden;
	top: 45px;
	display: none;
}
#progressBar #status{
	width: 0%;
	background:#00bd67;
	height: 16px;
	transition:1s linear width; /*this gives a smooth effect as the progress increases*/
}
#progressBar #percentage{
	position: absolute;
	text-align: left;
	z-index: 11;
	top: 0;
	left:0;
	font-size: 12px;
	color: #ffffff;
	width: 350px;
	padding-left: 5px;
	line-height: 15px;
}
Upload progress bar with jQuery

Upload progress bar with jQuery

Note: When developing this, I had an issue with the progress being reported waaaaay too fast. On file uploads of ~70Mb the progress would shoot to 100% in a couple of seconds and the upload would churn away in the background until it was complete. I made a post on Stack Overflow and someone suggested that it could be due to antivirus on my machine. I tried on a machine without AV and sure enough it worked great. I’ve tried turning off AV on my work dev machine and it behaved as expected (I’m unsure if it’s anything to do with the brand of anti virus but I have avast on my work machine).

IE8 prompting to download jQuery JSON response

I had a few JSON calls which IE8 was prompting me to download/save the response rather than simply hand it to jQuery to do it’s thing.

The returned JSON had the “correct” header and no other browsers were experiencing any issue:

header('Content-type: application/json');

To get around the IE8 issue, I had to change the header of the returned JSON to return text/plain:

header('Content-type: text/plain');

and ensure that my JSON calls had the dataType “json” specified. Without this explicitly specified, the browser was unable to parse the returned JSON.

$.ajax({
	type: "POST",
	dataType: "json",
	url: URL,
	data:data,
	success: function(data){
		alert(data.status)
	}
});

Boom!

As an extra note, I was also using dropzone.js for drag and drop file uploads. Dropzone.js doesn’t allow you to force the datatype of the response so I had to convert the response to JSON before doing anything with it with:

JSON.parse(responseText);

(Note, JSON.parse is only supported in modern browsers, this was not an issue though for me though as only modern browsers were able to use the dropzone functionality anyway and I had a fallback in place for older browsers)

PHP sessions not setting in Internet Explorer (IE)

I just made a pretty interesting discovery in that PHP sessions do not set in IE when there is one or more underscores (_) in the URL.

IE was the last browser I checked an almost completed project in, having developed in Chrome and Firefox. My heart sank when I found I was unable to log in. I hadn’t experienced this issue on any other browser and didn’t have a clue where to even start.

I was able to log in on the staging environment (where I show progress to the client) but not on my local dev so it had to be an environment issue. The only difference between the environments was the URL. I had a play around and found that removing the underscores from my local dev environment URL fixed this issue and I was able to log in. Boom.

jQuery $ is undefined in IE iFrame

I have a very jQuery heavy app which I am including in an iFrame on a site I am working on. Developing in Firefox and Chrome, it was only at the last minute when I came to test the site in Internet Explorer. Much to my dismay I was getting “$ is undefined”. There were no issues when running the site directly in IE (not through the iFrame).

I tried numerous fixes recommended by Stack Overflow including delaying the loading of the iFrame until the main content had loaded, but in the end, it was simply fixed by hosting jQuery from my own server rather than pulling it in from the CDN.

Cookie Clicker AutoHotKey script

I’ve been stupidly addicted to Cookie Clicker for the last few days. There are a few of us in the office with sore fingers from our in house competition to see who can get the highest rate clicks per second (CPS). At the time of writing, I’m firing at 1,853,140,156.5 CPS.

To gain a leg up on the competition (albeit an unethical one), I went after an AutoHotKey script to take care of some extra clicking for me while I’m out of the office. To save me learning AHK and writing my own, I came across this post: http://www.autohotkey.com/board/topic/97540-cookie-clicker-game/

Here’s the Cookie Clicker AutoHotKey:

$~m::
if (IsCookieActive()) {
	Loop, 9
	If stop = 1
		Break
	Else
	{
		WinGetActiveStats WindowName, WindowW, WindowH, WindowX, WindowY
		if ErrorLevel
			sleep 0
		else
			click 267, 460
	}
}
return

Shift::
If stop = 1
	stop = 0
Else
	stop = 1
return


IsCookieActive() {
	WinGetActiveTitle, title
	titleContains := "cookies"
	; MsgBox %title%
	IfInString, title, %titleContains%
	{
		return true
	} 
	else 
	{
		return false
	}
}

To Use: Change the loop value (currently set to 9) to the number of cookie clicks you wish to execute. Run the AHK script. Start it by pressing ‘m’ and stop it by double pressing ‘shift’.

jQuery Coverflow inspired Slider plugin

A fun project I’m working on required the use of a jQuery Coverflow type content slider. I searched high and low for a plugin to do the job but nothing quite fit the bill so I set out to write my own. I already had a jQuery content slider plugin that I wrote about a year ago which I decided to use as my starting point.

This coverflow plugin is inspired by Apple’s popular coverflow seen the iPhone, iPad, OSX – just about all their devices. When a “cover” is selected, either by clicking on it or by being navigated to with the arrows, it is centered and brought into focus.

jQuery Coverflow slider

DEMO HERE | GRAB THE PLUGIN ON GIT HUB

The plugin, while far from a one size fits all implementation, suits my requirements perfectly and should be a good starting point to anyone wanting similar functionality.

Installation

Installation of the jQuery plugin is relatively simple…

1. Include the CSS in the head of your document:

<head>
....
<link rel="stylesheet" type="text/css" href="jquery.coverflow.slider.css" />
</head>

2. Specify the cover images in an unordered list (ul) wrapped in a div:

<div id="contentSlider">
	<ul>
		<li><img src="cover1.jpg"></li>
		<li><img src="cover2.jpg"></li>
		<li><img src="cover3.jpg"></li>
		<li><img src="cover4.jpg"></li>
		<li><img src="cover5.jpg"></li>
		<li><img src="cover6.jpg"></li>
		<li><img src="cover7.jpg"></li>
		<li><img src="cover8.jpg"></li>
	</ul>
</div>

3. Include jQuery and jquery.coverflow.slider.js before the closing body tag of your document.

....
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery.coverflow.slider.js"></script>
</body>

4. Initialise the plugin below the inclusion of the coverflow js file

$('#contentSlider').coverFlow()

5 (optional). Options:

$('#contentSlider').coverFlow({
	'initialFocus' : 0, //the index of the slide you want to be focused on load
	'speed' : 200, // the speed of the animation
	'addClasses' : "", //classes to add to the slider
	afterChange: function(index){
		console.log('Slide in focus: ' + index);
	} //executes after the slide has changed
});

Feel Free to ask any questions below. I’ll try and help where I can.

Pure CSS3 Tooltips

pure-css3-tooltipVery simple pure CSS3 Tooltips using :hover for the tip itself, the CSS3 ‘transition’ property for a nice effect when the tooltip comes in, rgba for the background property for slight transparency on the tooltip and the :after pseudo class for a small arrow to complete the effect.

SEE THE DEMO HERE

The HTML is very simple. Just put your tooltip trigger text/image/other content within a standard <a> tag (with the toolTip class so we know to target it) and put the tooltip text in a nested <span>:

<a href="#null" class="toolTip">(?)
<span>There are many variations of passages of Lorem Ipsum available, 
but the majority have suffered alteration in some form, by injected 
humour, or randomised words which don't look even slightly 
believable.</span>
</a>

You must relatively position the <a> so the toolTip knows where to base itself as it will be absolutely positioned:

.toolTip{
	position: relative;
        text-decoration:none;
}

You will want the toolTip to be hidden initially, so when you declare it’s appearance in the CSS, you must also hide it. You also set up the transition here to allow the animation to occur when it opens. When I put this together, safari still required the -webkit prefix for transition. Chrome and Firefox were fine, however for peace of mind, I put in all the prefixes. At sometime in the near future these will not be needed:

.toolTip span{
	/*hiding it by moving it behind the main content*/
	z-index: -5;
 
	/*Set the start opacity to 0 so we can fade it in nicely using transitions*/
	opacity: 0;
 
	background: rgba(0, 0, 0, 0.8);
	border-bottom: 30px none transparent;
	border-radius: 5px 5px 5px 5px;
	bottom: 25px;
	color: #FFFFFF;
	font-size: 12px;
	padding: 10px;
	position: absolute;
	left: -10px;
	text-align: justify;
	width: 300px;
	transition: all 0.3s ease-out 0s;
        -webkit-transition: all 0.3s ease-out 0s;
	-moz-transition: all 0.3s ease-out 0s;
	-ms-transition: all 0.3s ease-out 0s;
	-o-transition: all 0.3s ease-out 0s;
}

When the <a> is hovered, we need to show the toolTip, we also change the position and the opacity from those declared above so we get a nice animation when it appears:

.toolTip:hover span{
	bottom: 30px;
	box-shadow: 1px 1px 1px rgba(0, 0, 0, 0.5);
	display: block;
	opacity: 1;
	left: -5px;
	z-index: 9;
}

And finally, to complete the effect, use the :after pseudo class to apply a small arrow:

.toolTip span:after {
	border-color: rgba(0, 0, 0, 0.8) transparent;
	border-style: solid;
	border-width: 15px 15px 0 0;
	bottom: -15px;
	content: "";
	display: block;
	position: absolute;
	left: 20px;
	width: 0;
}

And you have pure CSS3 tooltips. Any questions or comments? I’d love to hear them!