AngularJS – Communicate between controllers, services and directives


This solution uses JQuery.
I already include JQuery in the page so why not use it. If you need a non-JQuery solution here are a few links:

StackOverflow suggestions
Video tutorial
Native AngularJS broadcast
 

angular.module('fillta.service.Events', ['ngResource'])
    .factory('Events', function () {
        var el = document.createElement('div')
        var EventsListener = {
            on:function (event, callback, unsubscribeOnResponse) {
                $(el).on(event, function () {
                    if (unsubscribeOnResponse) {
                        $(el).off(event, el, callback)
                    }
                    callback.apply(this, arguments) //invoke client callback
                })
            },
            emit:function (event) {
                $(el).trigger(event, arguments)
            }
        }
        return EventsListener;
    })

This is a very quick and dirty entry. Essentially JQuery already has an amazing, cross-browser event system implemented. Its included in the page to make use of a few plugins, it seemed like a better idea to just use it over the other work arounds. And it seems (apparently, not tested myself) the native AngularJS way can be inefficient.

Stick that block of code in your services file. whenever you need to use it in another server or controller just add “Events” as a dependency then you can use, Events.emit(‘event’,arg1,arg2) and in your other controllers subscribe using Events.on(‘event’,function(arg1,arg2){},false) – The third argument is optional, if true then a function is unsubscribed when the event is emitted for the first time, otherwise it stays subscribed and listen for events.

That’s it. I have about 30 unpublished posts I need to finish off – Hopefully get the time soon but look forward to some tutorials and info on my experiences working with a range of technologies the last 7+ months (NodeJS,Socket.IO,Cassandra,AngularJS,requireJS,Netty,Higgs and loads more). Hope it is useful.

Learning Scala : My first attempt at a command line progress bar


While on my path to learning Scala, or rather improving my very lacking Scala knowledge I’ve written a progress bar for the command line…
I’m pretty sure it is far more verbose than it needs to be, but until I know how to code less and do more, this is it:
Read more of this post

Cassandra Hector Wrapper – Hector Simplified


This a simple wrapper I wrote for Hector.
—————————————–
Available at : https://github.com/zcourts/cassandra-hector-wrapper

It doesn’t support all the features of Hector…that’s sort of the point but not. The main point was to get something quick and simple.
I did this on the train over 3/4 mornings while heading to work. I wanted it to not have anything too complex or low level.
In effect I hope that even a new Cassandra user could just download a copy and start using it without the need to
fully understand all of Cassandra’s concepts. 
I’ll review it and make some needed changes however it does currently work fine. I noticed after pushing to github that
I’m not check if Hector returns null, which generally means whatever was requested couldn’t be found or an error occured
or something or the other.

Usage is similar to Hector’s see https://github.com/rantav/hector if you want to use Hector directly.
See the file https://github.com/zcourts/cassandra-hector-wrapper/blob/master/src/main/java/com/scriptandscroll/adt/UsageExamples.java
for a decent set of usage examples.

You start by creating a Keyspace object.

Keyspace ks=new Keyspace("clusterName", "keyspaceName", "localhost:9160") ;

//then a column or super column family object
ColumnFamily cf= new ColumnFamily(ks,"columnFamilyName);

//now the magic happens, you simple do cf.get[column|columns|row,rows]
Row row= cf.Row getRow("rowKey", "startColumn", "endColumn");

//you can now do
Column col = row.getColumn("columnName");
//then
String val= col.getValue();
//  OR .....
String val2=row.getColumnValue("columnName");
//OR
Iterator<Column> it=row.iterator();
while(it.hasNext()){
  Column c = it.next();
  //do whatever
}

Thats it!

Its important to note that I didn’t write this because the Hector client was lacking in anyway at all.
Quite the opposite in fact. The guys working on hector have done an awesome job and myself and I’m sure others
appreciate it. However when I was working on updating a project recently it was taking me far too much time to sift
through the hector docs and get familiar with all the changes etc. I started with a single file but that quickly got too nasty
and I just stopped, drew out some ideas and it turned out into all the classes currently in the project.

https://github.com/zcourts/cassandra-hector-wrapper/blob/master/src/main/java/com/scriptandscroll/adt/UsageExamples.java

package com.scriptandscroll.adt;

import java.util.ArrayList;
import java.util.List;

/**
 *Shows basic usage of the classes.
 * It firstly makes no provision to allow you to create keyspaces or column families, YET!
 * But once those are created from the CLI or some other way it provides a way to deal with
 * just about everything
 * @author Courtney Robinson <courtney@crlog.info>
 */
public class UsageExamples {

	public static void main(String[] args) {
		Keyspace ks = new Keyspace("clusterName", "keyspaceName", "localhost:9160");
		//Standard column family examples
		//create a column family object - THIS DOES NOT CREATE A COLUMN FAMILY IN CASSANDRA but assumes one with the given name already exists!
		ColumnFamily cf = new ColumnFamily(ks, "cfName");
		//now we can perform actions on this column family.
		//
		//first lets get a single column
		Column col = cf.getColumn("rowkey1", "columnName");
		//now we can use its value or name using
		col.getName();//returns a string
		//or
		col.getValue();//returns a string
		//
		//
		//we can get a set of columns from a row in three ways, by giving a startand end column name
		List<Column> cols = cf.getColumns("rowkey2", "startCol", "endCol");
		//by giving start and end col names and specifying a max amount of cols to get
		List<Column> cols2 = cf.getColumns("rowke2", "startCol", "endCol", false, 5);
		//or by giving an array of all columns to get
		//in this case it will only return the given columns
		List<Column> cols3 = cf.getColumns("rowkey2", new String[]{"col1", "col2", "col3", "col4"});
		//
		//We can also get rows within a CF
		//by setting start and end column names to an empty string and not setting a max value
		//we can get all the columns within the given row
		//the same options as getColumns apply, you specify columns by start and end key with an optional max amount or an array of columns
		Row row = cf.getRow("rowkey", "", "");
		//you can now do cool stuff with this row object like add and remove columns.
		//if you later pass this object to a column family it will apply those changes in Cassandra e.g.
		row.putColumn("newColName", "newColValue");
		//or
		row.putColumn(new Column("newerColName", "newerColValue"));
		//while we're at it we can remove columns from this row
		row.removeColumn(col);
		//or
		row.removeColumn("colName");
		//if we now write this row back to the column family all those changes are applied
		cf.putRow(row);//that's it! two new columns will be added, and two removed
		//we coould do
		//setting false stops it removing columns from cassandra that were removed from the object
		//columns that were added are still added obviously...
		cf.putRow(row, false);
		//we can also get multiple rows like this
		//setting start and end row keys and column names to empty gets everything
		//but we set the max rows to return as 20 and the max columns per row to 5
		//so up to 20 rows are returned which will contain up to 5 columns
		//there are multiple variations on these methods that allows various operations
		List<Row> rows = cf.getRows("", "", "", "", false, 20, 5);
		//Simple? Good! That is the aim!

		//Lukily Super column family operations work in a similar manner
		SuperColumnFamily scf = new SuperColumnFamily(ks, "superCFName");
		//now go through the same thing again...
		SuperColumn scol = scf.getSuperColumn("rowkey", "supercolName");
		//get sub columns of this super column
		List<Column> subCols = scol.getAllColumns();
		//or get multiple super columns
		List<SuperColumn> scol2 = scf.getSuperColumns("rowkey", new String[]{"superCol1", "superCol2", "superCol3"});

		//get a single sub column
		Column subCol = scf.getSubColumn("rowket", "superColname", "subcolname");
		List<Column> subCols2 = scf.getSubColumns("rowkey", "superCol", "startSubcol", "endSubCol");

		//we can get sub columns from multiple rows
		List<String> keys = new ArrayList<String>();
		keys.add("key1");
		keys.add("key2");
		keys.add("key3");
		keys.add("key4");
		keys.add("key5");
		//gets a list of rows with the sub columns requested
		List<Row> rowSubCols = scf.getSubColumnsFromMultipleRows(keys, "superColumn", "startSubCol", "endSubCol", false, 20);
		//get an entire super row
		SuperRow srow = scf.getSuperRow("rowkey", "startColumn", "endCol");
		SuperColumn sc = srow.getSuperColumn("superCol");//now do what we want
		List<SuperRow> lsuperRows = scf.getSuperRows(keys, "startCol", "endCol");
		//get up to 20 rows
		List<SuperRow> srows2 = scf.getSuperRows("startKey", "endKey", new String[]{}, 20);

		//we can also add and remove from a super row just as we did with a normal row
		ArrayList<Column> cols5 = new ArrayList();
		cols5.add(new Column("subname", "subval"));

		srow.putSuperColumn(new SuperColumn("colname", cols5));
		//and now
		scf.putSuperRow(srow);
		//all done...
		//still simple?
	}
}

On its own this would all mean nothing so again, a big thank you to the Hector guys.

If you can think of a better name then by all means, please say. Any comments, suggestions or general thoughts on it are most welcomed.

Dynamically require/include a Javascript file into a page and be notified when its loaded


This is a simple little JavaScript snippet I wrote the other day that basically includes an external javascript file in an HTML page head section.

Its pretty straight forward,

  • it first gets a reference to the head tag.
  • Creates a script element using document.createElement
  • Sets the source/url of the file
  • sets the type of the script element to the correct mime type of “text/javascript”
  • Then sets the onload property of the script element to a callback function you supply. In i.e. it will check the onreadystatechange and execute the callback function you provide.
  • And finally it appends the script element to the head of the page

		/**
		 *Load an externl JS file and append it to the head
		 */
		function require(file,callback){
			var head=document.getElementsByTagName("head")[0];
			var script=document.createElement('script');
			script.src=file;
			script.type='text/javascript';
			//real browsers
			script.onload=callback;
			//Internet explorer
			script.onreadystatechange = function() {
				if (_this.readyState == 'complete') {
					callback();
				}
			}
			head.appendChild(script);
		}

Probably a million and one ways to do this but it works decently in I.E 7+,Firefox,Chrome,Safari and Opera

Quick tips for squeezing performance out of Google’s Javascript charts with live (continuous) data/streams


I, until a few days ago always used JQuery for literally everything that needed Javascript. I’ve recently needed to use Google charts to show a live graphical representation of data. It needed to be a widget that didn’t rely on any framework so I had to brush up on my Javascript and forget all the easy stuff JQuery usually gives me! The chart would be updated EVERY SECOND, yeah pretty often! In every second there could be any amount of new points to be plotted. In addition, I’m only interested in points that have occurred within a fixed time period, the results of all this will be an “animated” graph that shifts left when data is updated. Read more of this post

Getting started with PHPUnit unit testing


The follow up to my previous post. The below is the php unit test class for the string class example I wrote.

Read more of this post

Creating a String class to represent and manipulate strings in PHP


In getting started with PHPUnit, I didn’t have any code I felt like writing unit tests for. Mainly because I wanted to start with something very simple. I started writing some code, one thing lead to another and I ended with a simple class to represent a string. It only has a few methods but it was more than enough to provide me with quite a few test cases. The unit test for the class in another post I’m going to do soon. (PHP Unit tests for string class is here)

Read more of this post

Installing Xampp and adding/updating PHPUnit and PHPDocumenter and configuring Netbeans 7 to use them on Windows


That title is quite a mouthful isn’t it? I usually do development on Ubuntu and only ever develop Windows specific programs on Windows using .NET but I’ve found the need to setup an environment to do some PHP/MySQL dev on windows (7). I’m running Windows 7 but the steps should work fine for XP and Vista too.

Read more of this post

Apache Cassandra + PHPcassa + Code Igniter = large scale PHP app in 5 minutes


I’m working on a new project, migrating an existing site using custom code with a very monolithic design on top of MySQL.

Design goals : Implement all the same functionality using a manageable framework with a small footprint on a distributed NoSQL database.
Small footprint? I’m thinking Code Igniter (CI)… Distributed NoSQL (my favorite part)? I’m thinking Apache Cassandra!!!
First problem…issue, whatever you want to call it. CI is built with SQL DB tied in fairly tightly. How do I separate the two without hacking the CI core and allow me to have the flexibility of upgrading CI in the future? And at the same time being able to integrate Cassandra tightly enough to not make it stand out like a penguin in Africa  sore thumb?

Enough with the questions, I’m very new to CI so this took me about an hour to make it happen. The idea is, CI provides a $this->db object when “database” is one of the auto loaded options. I want to still have this db instance available but providing  methods to access Cassandra. I also want this to be auto loaded and available in all controllers… So how? Read more of this post

C (#) sharp – Nullable type (null-coalescing/ double question mark) operator


I came across a very interesting operator today in C#.
At first I thought it was like a ternary operator but it turned out not to be. The operator “??”, yes two question marks.

It is known as the “nullable type”, “null-coalescing” or just the double question mark operator.

I’ve only come accross it in C# and according to the Microsoft, help page:
“The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.”

The remarks went on to say: Read more of this post

Follow

Get every new post delivered to your Inbox.

Join 346 other followers

%d bloggers like this: