UnderscoreJS Compose

After watching a video about UnderscoreJS
I saw the use of the compose function, I have never noticed this when skimming through the underscore docs. The compose function:
> Returns the composition of a list of functions, where each function consumes the return value of the function that follows. In math terms, composing the functions f(), g(), and h() produces f(g(h())).

So to add some context to this; the compose function will take in multiple functions as its params and execute each of these passing the result in to the next function. One thing to note is that the functions are run in reverse order to which they were passed in. Why does this matter? Well if you have used underscore at any length you will have most likely used the chain function to try and clean up the use of multiple underscore functions:

_.chain(people)
	.sortBy(function(person) { return person.age; })
	.map(function(person) { return person.name + " is " + person.age})
	.first()
	.value();
//"mark is 14"

This code is taking an array of people and sorting them by age then returning a string for the person and getting the first string in the array. This works and is “functional” however this could be cleaner. This is where the compose function comes in we can use compose to link the functions together and not only provide cleaner code but also make the code reusable by default.

var people = [{name: "john", age: 21}, {name: "mark", age: 14}, {name: "harry", age: 40}, {name: "Mary", age: 70}];
var mapNameAndAge = function(people) {
    return _.map(people, function(person) {
        return person.name + " is " + person.age;
    });
}
var sortByAge = function(people) {
    return _.sortBy(people, 'age');
}

var comp = _.compose(_.first, mapNameAndAge, sortByAge);
comp(people);
//"mark is 14"

So you can see there is some set up as you need to define the functions before you call compose however the final composed function is much cleaner and clearer to understand. This is also reuseable by defualt. This does not stop at underscore this can be used in other places such as API calls and data calls e.g:

var updateUser = _.compose(save, update, find);
updateUser({id: 1, location: london});
 

BelTech 2015 The internet of Things

The main theme of the discussion was that IoT (Internet of Things) was everywhere. Michael Crossey (Intel) discussed the changes in IoT and how it is related to the dropping cost of tech. This is related to Moore’s lawThe observation made in 1965 by Gordon Moore, co-founder of Intel, that the number of transistors per square inch on integrated circuits had doubled every year since the integrated circuit was invented. Moore predicted that this trend would continue for the foreseeable future.

Progrssion of IoT

Moore’s law can create great value and improve IoT, Intel are using this to build a reference model for vendors to create and expand IoT and help grow their products. John Shaw from Kingspan talk primarily on his own experiences with IoT with his business which provides smart solar solutions. Their solar PV adoption is powered by Intel Quark, Kingspan sees the IoT as a way of connecting not only devices but people, animals and objects in a smart way. John was very quick to brag about the advancements of Kingspan and how their head office is a carbon negative office. IoT helped to achieve this goal by using smart systems that talk to each other and allow the office to work efficiently.

Working with Large Systems

Joe Hughes of Glen Dimplex also focused on how his company was making advancements in the home and commercial cooling/heating by using IoT devices. Using smart heaters customers could control the heating in an energy efficient way. A system built with cloud controlled heating and having direct links to customers systems allows Glen Dimplex to provide an advanced service. Joe also talked about how this could in fact help the national grid. Joe explained that being able to monitor customers on site devices they can monitor energy usages and patterns, which can allow the national grid control the spinning up and down of resources. A question was put to the panel on the security implications of these systems. A product that talks to 1000’s of customer devices and also can talk to the national grid could have the potential to bring down one of the largest connected systems in the country. This is a valid point but as with any product the security must be a high priority.

IoT in Health

Gareth Tolerton of Total Mobile talked about the impact IoT has on health care and how capturing data on patients can help to provide a better health care system. Working with tech like smart locks can provide safe and much needed services to patients that receive at home care. Allowing the programmatic access to care workers. This system addresses issues with people who feel isolated and vulnerable as care workers can be allowed access without having to obtain keys for a patient’s home, if a care worker no longer treats or is linked to a patient then the access can be revoked. Other IoT systems can help to provide personally tailored health care for patients, but as mentioned by Gareth work is still needed to provide trust in the data collected and sufficiently protect the data.

Take Away

One of my main concerns with the growing IoT market space is the maturity of the network and infrastructure currently in place. I recently watched a promotional video for a smart bike pedal that connected via a sim card to the internet and provided the rider with data. I struggle to see the feasibility of devices like this and other IoT devices. I’m currently with a major mobile provider and I struggle to get a full connection when in the centre of Belfast. Bandwidth, connection speeds and coverage are still big issues faced by many people. If we flood the networks with devices fighting for connection we could cripple the already struggling infrastructure.

 

BelTech 2015

I had the pleasure of attending this years BelTech conference hosted in the amazingly designed Titanic building. The conferences was based on a few topics including smart cities, startups and practitioners. I focused on the smart cities and practitioners.

Opening Keynote

The opening keynote was presented by Kate Atkinson the co founder of Datasnap.io a company focused on the development of products that provide data and insight into customer engament. Using proximity tracking technology DataSnap tracks the movement of patrons at venues and provides data to the customer. Kate talked about the challenges of working with customers and trying to improve the data they require. One of the big requests from customers was to have live maps of the location to watch live data of patrons and how the move around a venue. This can be hard to provide when no real detailed floor maps are available. The solution for this was to map the proximity sensors to rooms or areas. Instead of tracking the location of a patron track their movement between sensors. The result gives data on how many patrons move from A to B then to C and how many move from A to C without stopping at B. This allows the customer to workout why patrons are skipping B and find ways to change this.

Smart Cities

The smart cities session was run with a number of mayors from across the UK, US and europe. The discussion started off talking about the state of smart cities currently, the different cities that were brought into question were; Skien (Norway), Lowell (Massachusetts), South Dublin (Ireland) and Donegal (Ireland). The main theme from each mayor was the focus on bringing companies together to provide a better smart city. However this does come with some challenges, the mayor of Donegal talked about issues with the structure of the local government and how parts had been broken up and segregated from other resources such as online payment and the management of customer interactions. This does however provide a gap that can be filled with smart technologies. The mayor of South Dublin made points about how people expect more from the city with the higher taxes being introduced, this is to help provide more services such as free wifi. Whereas the mayor of Lowell focused on how the city was already smart and push more resources into the existing schemes and even starting more projects. These schemes are the usual that people think of when you hear smart city, funding startups and university based incubator programs. A change from the free wifi, online services and tech startups the mayor of Skien focused on how the growth of the smart city can actually benefit the citizens health and lifestyle. One issue facing all cities is the increased life expectancy which in turn puts more pressure on the heath care system. Skien is focused on building smart homes and integrating smart systems into people’s lives to help protect and improve their way of life.

My take away from the talk, smart cities are becoming a big part of the political thought process and are not a thing of the future, some locations are better suited than others. This can be driven on the geographical location such as remote area’s (always hard to provide high speed broadband etc). Some other reasons could be linked to the technical competence of the local government as some of the mayors were not the most conversed in modern tech and this was clear at point of the talk.

You can read more on the talks below:

The Internet of Things

 

Backbone Forms

I was thinking out loud today about Backbone views and how to manage user inputted data. When I has searched for
how to manage forms and handle user data the few examples I saw all used jQuery to pull the values out of the DOM. Which
we all know can cause issues with performance and adds a level of complexity when it comes to maintaining the code, as
the form grows the code used to pull the values out of the text boxes etc will grow.

I was thinking about this for a while until I came up with a pattern that would allow the code to update the model linked
to the view and handle new inputs added to the html without any code changes need in the view or the model. The pattern
(if you could call it that) uses data attributes
on the html to decide if the model needs updating and does this in a dynamic way.

<input type="text" class="listen-to" data-model="input1"/>

The input is decorated with a data-model attribute which will map to an attribute on the model, it also has a “listen-to”
class which will be picked up by the views events.

events: {
            "change .listen-to": "updateModel"
        }

The event will trigger once input has lost focus, this then calls the update model function. The event will fire when any
of the inputs have changed e.g allowing for as many inputs as needed. The event will be passed into the function and this
will be used to find out which attribute of the model to update and what value to update with.

updateModel: function(evt){
            this.model.set(evt.currentTarget.attributes["data-model"].value,
            evt.currentTarget.value);
            //optional: update another view with the latest value in the model
            this.outputView = new OutputView({
                model: this.model,
                el: $("#output_container")
            });

        }

As you can see in the example (hacked together) the evt will hold target that triggered the event. The data-model attribute
is used to get the model attribute to update and the value is taken from the currentTarget. For demo purposes another
is update to show that the changes are made to the model in real time. This could be extended so that a submit button will
call a function that only needs to get the model and do what ever it wants with the values as the model attributes have been
updated as the user has been filling them in.

This takes away the need to use jQuery for getting the values from the inputs and allows more inputs to be added to the
template which out any view code changes.

You can see the full demo here.

 

Chrome Dev Tools – IDE Replacement

I recently talked at locally JavaScript meetup I talked about the top 5 features of the Chrome developer tools. I have given a simular talk at my old company which talked through the dev tools and how they can be used to improve the development process.

After the first talk it started to dawn on me that with some of the features in the tool kit you could get to the point of replacing the development IDE. The development cycle can be a comfortable or painful process for a developer, I have worked on some projects where the time between making a code change and seeing the results could take up to 5 minutes.

So how do we streamline this process, enter Chrome developer tools. The most powerful feature in the sources pannel.

Chrome Source Panel

As the complexity of JavaScript applications increase, developers need powerful debugging tools to help quickly discover the cause of an issue and fix it efficiently. The Chrome DevTools include a number of useful tools to help make debugging JavaScript less painful.

The sources panel provides all the needed tools for developing;
– breakpoints
– call stack
– watches
– console execution
– live editing of code

This is all great but we are still only in the dev tools, we still need a IDE or text editor to create the code then open it in chrome. What if we could edit the code and not have return the to IDE to make the changes again.

Well we can, dev tools allows you to map files to a local workspace. This makes a link between the files in the browser to the files on you local machine. See this in action below:

Adding a workspace

Now that the workspace is linked you can make changes in the browser and have these saved to the local file, this now breaks the link between the IDE and the browser. You have created a instant feadback loop.

This shows the power of the Chrome developer tools, this is only the start. As time progresses the dev tools will grow it’s feature set providing more options for developers. If you have any cool tips or tricks for the dev tools please leave a comment.

 

JetBrains Intellij Workshop

Today I attended a workshop from the team at Jetbrains, the workshop gave a detailed look into the Intellij IDE. The workshop was presented by Hadi Hariri, with his anti mouse philosophy in mind we dug into the ways to using Intellij to work efficiently. I will outline some of the take away points that I felt that most developers would not know and must learn if you plan to use or already use Intellij to develop.

##Navigation

“use the keyboard” the mantra that Hadi repeated and which made me feel bad for all the times I’v used the mouse.

Presentation assistant was shown at the point as Hadi would be using the keyboard to do everything we would need to see what key combinations were being executed. Presentation assistant flashes up on screen what keys are used to carry out an action and the action name. This will now be turned on anytime that I do live coding demos and you should do the same. This feature should also be turned on while you are pair programming for the times when you are bashing away on the keyboard and the other developer is lost to the world trying to work out what the you are doing.

So now on to the meat of the workshop the hip cool key combinations that will make you look L33T in front of all you programming friends.

###Navigation:
cmd + o get to class
cmd + 1 open the project structure
– In the project structure you can also:
– start typing and this will search for the file
– set auto scroll so that files opened via search are scrolled to on the project view
shift (double press) search everywhere this will search not only classes but files, build tasks, features anything you can really think about.
In this feature you can also toggle IDE features
Run build configurations
cmd + 7 file structure of the project
cmd + n create new file
– in the new file selection you can also start typing to search/refine the selection
cmd + e show recent file
– this comes into play especially if you disable tabled editing, Hadi was an advocate of the one tab rule in which you only have one file open at as time and using the file navigation built into Intellij you can go back and forth. Tab settings can be changed from the general settings menu and any limit can be set on the number of open tabs.
shift + cmd + e show recently edited files
cmd + y show a popup window of the code definition
cmd + b go to the code definition

###Windows
shift + cmd F12 hide all windows except the file you are editing

###Text
alt + up select line (context aware) e.g. select var, then function the class etc
shit cmd enter statement complete can be used to complete if statements

###Refactoring Code
import preferences allows you to import a namespace or each individual class, you can also add tolerances to if more that say 3 classes are used from a package then you can import the package.
cmd + t surround code, allowing you to surround a statement easily

These are just some of the tips and tricks that I had picked up from the workshop, the help documentation built into Intellij and the web site is a great resource for looking for shortcuts and different approaches for completing a task. A big thanks to the team at Dev Bash for setting up the workshop, check them out for more talks and workshops like this.

If you have learnt any tips or tricks for using this very powerful IDE please leave a comment.