<commit_before>$(document).ready(function() {

    var countdownInterval = null;
    var hoursInterval     = null;
    var minutesInterval   = null;
    var secondsInterval   = null;
    var currentButton     = 'daysCounter';
    var currentHeaderOpt  = 1;

    //set up the difference between retirement and today in multiple formats
    function daysBetween( date1, date2 ) {
        console.log(date1, date2);
        //Get 1 day in milliseconds
        var one_day    = 1000*60*60*24;
        var one_hour   = 1000*60*60;
        var one_minute = 1000*60;
        var one_second = 1000;

        // Convert both dates to milliseconds
        var date1_ms = date1.getTime();
        var date2_ms = date2.getTime();

        // Calculate the difference in milliseconds
        var difference_ms = date2_ms - date1_ms;

        var daysLeft    = Math.abs(Math.ceil(difference_ms/one_day));
        var hoursLeft   = Math.abs(Math.ceil( (difference_ms % one_day)/one_hour ));
        var minutesLeft = Math.abs(Math.ceil( ((difference_ms % one_day) % one_hour)/one_minute ) );
        var secondsLeft = Math.abs(Math.ceil( (((difference_ms % one_day) % one_hour) % one_minute )/one_second));

        //if less than 10 then have it appear as 2 digit
        function doubleDigitize(digit) {
            if (digit < 10) {
                digit = '0' + digit;
            }
            return digit;
        }

        daysLeft    = doubleDigitize(daysLeft);
        hoursLeft   = doubleDigitize(hoursLeft);
        minutesLeft = doubleDigitize(minutesLeft);
        secondsLeft = doubleDigitize(secondsLeft);

        var timeLeftArray = [daysLeft, hoursLeft, minutesLeft, secondsLeft];

        return timeLeftArray;
    }

    //get the current time
    function getTime (timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring) {
        //Set the two dates
        var retireDate           = new Date('June 3, 2016 8:30:00 pm (EST)');
        var today                = new Date();
        var timeZoneOffset       = (today.getTimezoneOffset()/60) - 4;
        today.setHours(today.getHours() + timeZoneOffset);
        var timeLeftArray        = daysBetween(retireDate, today);
        hoursUntilRetiring       = (+timeLeftArray[0] * 24) + (+timeLeftArray[1]);
        minutesUntilRetiring     = (hoursUntilRetiring * 60) + (+timeLeftArray[2]);
        secondsUntilRetiring     = (minutesUntilRetiring * 60) + (+timeLeftArray[3]);
        var timeLordArray        = [timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring];
        return timeLordArray;
    }

    //change the countdown options
    function changeCountdown(clickOption) {
        var timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring;

        var timeLordArray = getTime(timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring);

        timeLeftArray        = timeLordArray[0];
        hoursUntilRetiring   = timeLordArray[1];
        minutesUntilRetiring = timeLordArray[2];
        secondsUntilRetiring = timeLordArray[3];

        switch (+clickOption) {
            case 1:
                $('body').find('#total-time-left').html(
                    '

' +
                    timeLeftArray[0] + '

Days

' +
                    '

' +
                    timeLeftArray[1] + '

Hours

' +
                    '

' +
                    timeLeftArray[2] + '

Minutes

' +
                    '

' +
                    timeLeftArray[3] + '

Seconds

');
                break;
            case 2:
                $('.clock-boxes').find('.clock-dials').text(hoursUntilRetiring);
                break;
            case 3:
                $('body').find('#total-time-left').html(
                    '

' +
                    minutesUntilRetiring + '

Total Minutes

');
                break;
            case 4:
                $('body').find('#total-time-left').html(
                    '

' +
                    secondsUntilRetiring + '

Total Seconds

');
                break;
            default:
                break;
        }
    }

    //fade things in and out
    function fadeInAndOut (whichEl, elToAdd) {
        $('body').find(whichEl).fadeOut( "500", function() {
            $('body').find(whichEl).html(elToAdd);
            $('body').find(whichEl).fadeIn('500', function() {});
        });
    }

    $('#cd-menu').on('click', '.cd-buttons', function(){
        var elId = $(this).find('p').attr('id') || '';

        var imageHeight = $('#lenny-image').height();
        $('#lenny-image').css('height', imageHeight);

        if (currentButton !== elId) {
            currentButton = elId;
            var imageEl = '#lenny-image';
            var timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring;

            var timeLordArray = getTime(timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring);

            timeLeftArray        = timeLordArray[0];
            hoursUntilRetiring   = timeLordArray[1];
            minutesUntilRetiring = timeLordArray[2];
            secondsUntilRetiring = timeLordArray[3];

            clearInterval(countdownInterval);
            clearInterval(hoursInterval);
            clearInterval(minutesInterval);
            clearInterval(secondsInterval);

            switch (elId) {
                case 'daysCounter':

                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            timeLeftArray[0] + '

Days

' +
                                            '

' +
                                            timeLeftArray[1] + '

Hours

' +
                                            '

' +
                                            timeLeftArray[2] + '

Minutes

' +
                                            '

' +
                                            timeLeftArray[3] + '

Seconds

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    countdownInterval = setInterval(function() {changeCountdown(1)}, 1000);

                    break;
                case 'hoursCounter':
                    var htmlImageString = '';
                    var htmlClockString = '

'+hoursUntilRetiring+'

Total Hours

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    hoursInterval = setInterval(function() {changeCountdown(2)}, 1000);

                    break;
                case 'minutesCounter':
                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            minutesUntilRetiring + '

Total Minutes

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    minutesInterval = setInterval(function() {changeCountdown(3)}, 1000);

                    break;
                case 'secondsCounter':
                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            secondsUntilRetiring + '

Total Seconds

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    secondsInterval = setInterval(function() {changeCountdown(4)}, 1000);

                    break;
                default:
                    console.log('nay');
            }
        }

        setTimeout(function(){$('#lenny-image').css('height', 'auto')}, 700);

    });

    //set up a random bg color using base 16 math
    function randomColor () {
        return '#'+Math.floor(Math.random()*16777215).toString(16);
    }

    //can change header, bg and days font
    function changeColor() {
        var backgroundColor   = randomColor();
        //var headerFontColor = randomColor();
        //var daysFont        = randomColor();
        $('body').css('background-color', backgroundColor);
        $('#page-overlay').css('background-color', backgroundColor);
    }

    //set interval to change background color
    setInterval(changeColor, 4000);

    //easter egg: on click of header we get different headers and images
    $('body').on('click', '#retirement-header', function(event) {

        event.preventDefault();
        currentButton = '';

        var imageHeight = $('#lenny-image').height();
        $('#lenny-image').css('height', imageHeight);
        var imageEl = '#lenny-image';
        +currentHeaderOpt === 5 ? currentHeaderOpt = 0 : '';
        var headerOptions =[
                            "Countdown to Lenny's Retirement 2016!",
                            "Lenny Arrives in Portland With Tools",
                            "Countdown to SF Summer with Sandy",
                            "Sit Back, Have a Drink, and Relax",
                            "New Profession: Full Time Mechanic"
                            ];

        switch (currentHeaderOpt) {
            case 0:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 1:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 2:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 3:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 4:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
        }

        $(this).text(headerOptions[currentHeaderOpt]);

        setTimeout(function(){$('#lenny-image').css('height', 'auto')}, 700);
        currentHeaderOpt++;
    });

    //view site, password is correct
    function viewSitePasswordCorrect() {
        //set up clock
        changeCountdown(1);
        //set clock interval to start
        countdownInterval = setInterval(function() {changeCountdown(1)}, 1000);
        //add first image
        $('body').find('#lenny-image').html('');
    }

    //if return key is used pass value to passwordInput function
    $('#page-overlay').on('keyup', '#shall-not-pass', function(e) {
        if(event.keyCode == 13) {
            var passwordInput = $('#shall-not-pass').val();
            checkPassword(passwordInput);
        }
    });

    //set up a frontend password to deter some users
    $('#page-overlay').on('click', '#bridge-troll', function(e) {
        e.preventDefault();
        var passwordInput = $('#shall-not-pass').val();
        checkPassword(passwordInput);
    });

    //test Password
    function checkPassword (passwordInput) {
        if (passwordInput === 'lennyretires'){
            viewSitePasswordCorrect();
            $('#page-overlay').hide();
        } else {
            alert('Wrong Password. Please Try Again');
        }
    }

});<commit_msg>remove console logs and blips when photos change<commit_after>$(document).ready(function() {

    var countdownInterval = null;
    var hoursInterval     = null;
    var minutesInterval   = null;
    var secondsInterval   = null;
    var currentButton     = 'daysCounter';
    var currentHeaderOpt  = 1;

    //set up the difference between retirement and today in multiple formats
    function daysBetween( date1, date2 ) {
        //Get 1 day in milliseconds
        var one_day    = 1000*60*60*24;
        var one_hour   = 1000*60*60;
        var one_minute = 1000*60;
        var one_second = 1000;

        // Convert both dates to milliseconds
        var date1_ms = date1.getTime();
        var date2_ms = date2.getTime();

        // Calculate the difference in milliseconds
        var difference_ms = date2_ms - date1_ms;

        var daysLeft    = Math.abs(Math.ceil(difference_ms/one_day));
        var hoursLeft   = Math.abs(Math.ceil( (difference_ms % one_day)/one_hour ));
        var minutesLeft = Math.abs(Math.ceil( ((difference_ms % one_day) % one_hour)/one_minute ) );
        var secondsLeft = Math.abs(Math.ceil( (((difference_ms % one_day) % one_hour) % one_minute )/one_second));

        //if less than 10 then have it appear as 2 digit
        function doubleDigitize(digit) {
            if (digit < 10) {
                digit = '0' + digit;
            }
            return digit;
        }

        daysLeft    = doubleDigitize(daysLeft);
        hoursLeft   = doubleDigitize(hoursLeft);
        minutesLeft = doubleDigitize(minutesLeft);
        secondsLeft = doubleDigitize(secondsLeft);

        var timeLeftArray = [daysLeft, hoursLeft, minutesLeft, secondsLeft];

        return timeLeftArray;
    }

    //get the current time
    function getTime (timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring) {
        //Set the two dates
        var retireDate           = new Date('June 3, 2016 8:30:00 pm (EST)');
        var today                = new Date();
        var timeZoneOffset       = (today.getTimezoneOffset()/60) - 4;
        today.setHours(today.getHours() + timeZoneOffset);
        var timeLeftArray        = daysBetween(retireDate, today);
        hoursUntilRetiring       = (+timeLeftArray[0] * 24) + (+timeLeftArray[1]);
        minutesUntilRetiring     = (hoursUntilRetiring * 60) + (+timeLeftArray[2]);
        secondsUntilRetiring     = (minutesUntilRetiring * 60) + (+timeLeftArray[3]);
        var timeLordArray        = [timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring];
        return timeLordArray;
    }

    //change the countdown options
    function changeCountdown(clickOption) {
        var timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring;

        var timeLordArray = getTime(timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring);

        timeLeftArray        = timeLordArray[0];
        hoursUntilRetiring   = timeLordArray[1];
        minutesUntilRetiring = timeLordArray[2];
        secondsUntilRetiring = timeLordArray[3];

        switch (+clickOption) {
            case 1:
                $('body').find('#total-time-left').html(
                    '

' +
                    timeLeftArray[0] + '

Days

' +
                    '

' +
                    timeLeftArray[1] + '

Hours

' +
                    '

' +
                    timeLeftArray[2] + '

Minutes

' +
                    '

' +
                    timeLeftArray[3] + '

Seconds

');
                break;
            case 2:
                $('.clock-boxes').find('.clock-dials').text(hoursUntilRetiring);
                break;
            case 3:
                $('body').find('#total-time-left').html(
                    '

' +
                    minutesUntilRetiring + '

Total Minutes

');
                break;
            case 4:
                $('body').find('#total-time-left').html(
                    '

' +
                    secondsUntilRetiring + '

Total Seconds

');
                break;
            default:
                break;
        }
    }

    //fade things in and out
    function fadeInAndOut (whichEl, elToAdd) {
        $('body').find(whichEl).fadeOut( "500", function() {
            $('body').find(whichEl).html(elToAdd);
            $('body').find(whichEl).fadeIn('500', function() {});
        });
    }

    $('#cd-menu').on('click', '.cd-buttons', function(){
        var elId = $(this).find('p').attr('id') || '';

        var imageHeight = $('#lenny-image').height();
        $('#lenny-image').css('height', imageHeight);

        if (currentButton !== elId) {
            currentButton = elId;
            var imageEl = '#lenny-image';
            var timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring;

            var timeLordArray = getTime(timeLeftArray, hoursUntilRetiring, minutesUntilRetiring, secondsUntilRetiring);

            timeLeftArray        = timeLordArray[0];
            hoursUntilRetiring   = timeLordArray[1];
            minutesUntilRetiring = timeLordArray[2];
            secondsUntilRetiring = timeLordArray[3];

            clearInterval(countdownInterval);
            clearInterval(hoursInterval);
            clearInterval(minutesInterval);
            clearInterval(secondsInterval);

            switch (elId) {
                case 'daysCounter':

                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            timeLeftArray[0] + '

Days

' +
                                            '

' +
                                            timeLeftArray[1] + '

Hours

' +
                                            '

' +
                                            timeLeftArray[2] + '

Minutes

' +
                                            '

' +
                                            timeLeftArray[3] + '

Seconds

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    countdownInterval = setInterval(function() {changeCountdown(1)}, 1000);

                    break;
                case 'hoursCounter':
                    var htmlImageString = '';
                    var htmlClockString = '

'+hoursUntilRetiring+'

Total Hours

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    hoursInterval = setInterval(function() {changeCountdown(2)}, 1000);

                    break;
                case 'minutesCounter':
                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            minutesUntilRetiring + '

Total Minutes

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    minutesInterval = setInterval(function() {changeCountdown(3)}, 1000);

                    break;
                case 'secondsCounter':
                    var htmlImageString = '';
                    var htmlClockString =   '

' +
                                            secondsUntilRetiring + '

Total Seconds

';
                    var timeLeftEl = '#total-time-left';

                    fadeInAndOut(imageEl, htmlImageString);
                    fadeInAndOut(timeLeftEl, htmlClockString);

                    secondsInterval = setInterval(function() {changeCountdown(4)}, 1000);

                    break;
                default:
                    console.log('nay');
            }
        }

        setTimeout(function(){$('#lenny-image').css('height', 'auto')}, 700);

    });

    //set up a random bg color using base 16 math
    function randomColor () {
        return '#'+Math.floor(Math.random()*16777215).toString(16);
    }

    //can change header, bg and days font
    function changeColor() {
        var backgroundColor   = randomColor();
        $('body').css('background-color', backgroundColor);
        $('#page-overlay').css('background-color', backgroundColor);
    }

    //set interval to change background color
    setInterval(changeColor, 4000);

    //easter egg: on click of header we get different headers and images
    $('body').on('click', '#retirement-header', function(event) {

        event.preventDefault();
        currentButton = '';

        var imageHeight = $('#lenny-image').height();
        $('#lenny-image').css('height', imageHeight);
        var imageEl = '#lenny-image';
        +currentHeaderOpt === 5 ? currentHeaderOpt = 0 : '';
        var headerOptions =[
                            "Countdown to Lenny's Retirement 2016!",
                            "Lenny Arrives in Portland With Tools",
                            "Countdown to SF Summer with Sandy",
                            "Sit Back, Have a Drink, and Relax",
                            "New Profession: Full Time Mechanic"
                            ];

        switch (currentHeaderOpt) {
            case 0:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 1:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 2:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 3:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
            case 4:
                var htmlImageString = '';
                fadeInAndOut(imageEl, htmlImageString);
                break;
        }

        $(this).text(headerOptions[currentHeaderOpt]);

        setTimeout(function(){$('#lenny-image').css('height', 'auto')}, 2000);
        currentHeaderOpt++;
    });

    //view site, password is correct
    function viewSitePasswordCorrect() {
        //set up clock
        changeCountdown(1);
        //set clock interval to start
        countdownInterval = setInterval(function() {changeCountdown(1)}, 1000);
        //add first image
        $('body').find('#lenny-image').html('');
    }

    //if return key is used pass value to passwordInput function
    $('#page-overlay').on('keyup', '#shall-not-pass', function(e) {
        if(event.keyCode == 13) {
            var passwordInput = $('#shall-not-pass').val();
            checkPassword(passwordInput);
        }
    });

    //set up a frontend password to deter some users
    $('#page-overlay').on('click', '#bridge-troll', function(e) {
        e.preventDefault();
        var passwordInput = $('#shall-not-pass').val();
        checkPassword(passwordInput);
    });

    //test Password
    function checkPassword (passwordInput) {
        if (passwordInput === 'lennyretires'){
            viewSitePasswordCorrect();
            $('#page-overlay').hide();
        } else {
            alert('Wrong Password. Please Try Again');
        }
    }

});<|endoftext|>


<commit_before>let libs = require('./libs');

let templates = {
  axis: require('../templates/axis.json'),
  bar: require('../templates/bar.json'),
  box: require('../templates/box.json'),
  bullet: require('../templates/bullet.json'),
  gantt: require('../templates/gantt.json'),
  histogram: require('../templates/histogram.json'),
  scatter: require('../templates/scatter.json'),
  vega: require('../templates/vega.json'),
  xy: require('../templates/xy.json'),
  xymatrix: require('../templates/xymatrix.json')
};

let d3 = libs.d3;
let vg = libs.vg;

let getNestedRec = function (spec, parts) {
  if (spec === undefined || parts.length === 0) {
    return spec;
  }
  return getNestedRec(spec[parts[0]], parts.slice(1));
};

let getNested = function (spec, name) {
  return getNestedRec(spec, name.split('.'));
};

let setNestedRec = function (spec, parts, value) {
  if (parts.length === 1) {
    spec[parts[0]] = value;
    return;
  }
  if (spec[parts[0]] === undefined) {
    spec[parts[0]] = {};
  }
  setNestedRec(spec[parts[0]], parts.slice(1), value);
};

let setNested = function (spec, name, value) {
  setNestedRec(spec, name.split('.'), value);
};

let templateFunctions = {
  defaults: function (args, options, scope) {
    for (let index = 0; index < args[0].length; index += 1) {
      let value = getNested(scope, args[0][index][0]);
      if (value === undefined) {
        value = getNested(options, args[0][index][0]);
      }
      if (value === undefined) {
        value = transform(args[0][index][1], options, scope);
        setNested(scope, args[0][index][0], value);
      }
    }
    return transform(args[1], options, scope);
  },

  let: function (args, options, scope) {
    for (let index = 0; index < args[0].length; index += 1) {
      let value = transform(args[0][index][1], options, scope);
      setNested(scope, args[0][index][0], value);
    }
    return transform(args[1], options, scope);
  },

  get: function (args, options, scope) {
    let value = getNested(scope, args[0]);
    if (value === undefined) {
      value = getNested(options, args[0]);
    }
    if (value === undefined) {
      value = transform(args[1], options, scope);
    }
    if (value === undefined) {
      value = null;
    }
    return value;
  },

  map: function (args, options, scope) {
    let transformed = [];
    let elements = transform(args[0], options, scope);

    for (let elementIndex = 0; elementIndex < elements.length; elementIndex += 1) {
      scope[args[1]] = elements[elementIndex];
      for (let itemIndex = 2; itemIndex < args.length; itemIndex += 1) {
        let element = transform(args[itemIndex], options, scope);
        if (element !== null) {
          transformed.push(element);
        }
      }
    }
    return transformed;
  },

  if: function (args, options, scope) {
    let condition = transform(args[0], options, scope);
    if (condition) {
      return transform(args[1], options, scope);
    }
    return transform(args[2], options, scope);
  },

  eq: function (args, options, scope) {
    let a = transform(args[0], options, scope);
    let b = transform(args[1], options, scope);
    return (a === b);
  },

  and: function (args, options, scope) {
    let arr = transform(args, options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (!arr[i]) {
        return false;
      }
    }
    return true;
  },

  or: function (args, options, scope) {
    let arr = transform(args, options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i]) {
        return true;
      }
    }
    return false;
  },

  join: function (args, options, scope) {
    let result = '';
    let sep = transform(args[0], options, scope);
    let arr = transform(args[1], options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (i > 0) {
        result += sep;
      }
      result += arr[i];
    }
    return result;
  },

  merge: function (args, options, scope) {
    let merged = transform(args[0], options, scope);
    for (let i = 1; i < args.length; i += 1) {
      merged = merge(merged, transform(args[i], options, scope));
    }
    return merged;
  },

  apply: function (args, options, scope) {
    let templateName = transform(args[0], options, scope);
    let templateOptions = transform(args[1], options, scope);
    return transform(templates[templateName], templateOptions);
  },

  colorScale: function (args, options, scope) {
    let params = transform(args[0], options, scope);
    let name = params.name || 'color';
    if (!Array.isArray(params.values) ||
      params.values.length < 1 ||
      params.values[0][params.field] === undefined ||
      typeof params.values[0][params.field] === 'string') {
      return {
        name: name,
        type: 'ordinal',
        domain: {data: params.data, field: name},
        range: 'category10'
      };
    }
    return {
      name: name,
      type: 'linear',
      zero: false,
      domain: {data: params.data, field: name},
      range: ['#dfd', 'green']
    };
  },

  isStringField: function (args, options, scope) {
    let values = transform(args[0], options, scope);
    let field = transform(args[1], options, scope);

    if (!Array.isArray(values) ||
      values.length < 1 ||
      values[0][field] === undefined ||
      typeof values[0][field] === 'string') {
      return true;
    }
    return false;
  },

  orient: function (args, options, scope) {
    let dir = transform(args[0], options, scope);
    let obj = transform(args[1], options, scope);
    let transformed = {};
    let mapping = {
      x: 'y',
      x2: 'y2',
      xc: 'yc',
      y: 'x',
      y2: 'x2',
      yc: 'xc',
      width: 'height',
      height: 'width'
    };
    if (dir === 'horizontal') {
      return obj;
    }
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (mapping[key]) {
          transformed[mapping[key]] = obj[key];
        } else {
          transformed[key] = obj[key];
        }
      }
    }
    return transformed;
  }
};

let transform = function (spec, options, scope) {
  options = options || {};
  scope = scope || {};

  if (Array.isArray(spec)) {
    if (spec.length > 0 && (typeof spec[0] === 'string') && spec[0].slice(0, 1) === '@') {
      return templateFunctions[spec[0].slice(1)](spec.slice(1), options, scope);
    }
    let transformed = [];
    for (let index = 0; index < spec.length; index += 1) {
      transformed.push(transform(spec[index], options, scope));
    }
    return transformed;
  }
  if (spec === null) {
    return spec;
  }
  if (typeof spec === 'object') {
    let transformed = {};
    for (let key in spec) {
      if (spec.hasOwnProperty(key)) {
        transformed[key] = transform(spec[key], options, scope);
      }
    }
    return transformed;
  }
  return spec;
};

let isObjectLiteral = function (object) {
  return object && object.constructor && object.constructor.name === 'Object';
};

let isArrayLiteral = function (object) {
  return object && object.constructor && object.constructor.name === 'Array';
};

let extend = function (defaults, options) {
  if (options === undefined) {
    return defaults;
  }
  if (isObjectLiteral(defaults)) {
    let extended = {};
    for (let prop in defaults) {
      if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = extend(defaults[prop], options[prop]);
      }
    }
    for (let prop in options) {
      if (!Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = options[prop];
      }
    }
    return extended;
  }
  if (isArrayLiteral(defaults)) {
    let extended = [];
    for (let index = 0; index < defaults.length; index += 1) {
      extended.push(extend(defaults[index], options[index]));
    }
    if (isArrayLiteral(options)) {
      for (let index = defaults.length; index < options.length; index += 1) {
        extended.push(options[index]);
      }
    }
    return extended;
  }
  return options;
};

let merge = function (defaults, options) {
  if (options === undefined || options === null) {
    return defaults;
  }
  if (defaults === undefined || defaults === null) {
    return options;
  }
  if (isObjectLiteral(defaults)) {
    let extended = {};
    for (let prop in defaults) {
      if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = merge(defaults[prop], options[prop]);
      }
    }
    for (let prop in options) {
      if (!Object.prototype.hasOwnProperty.call(extended, prop)) {
        extended[prop] = options[prop];
      }
    }
    return extended;
  }
  if (isArrayLiteral(defaults)) {
    let extended = [];
    for (let index = 0; index < defaults.length; index += 1) {
      extended.push(defaults[index]);
    }
    if (isArrayLiteral(options)) {
      for (let index = 0; index < options.length; index += 1) {
        extended.push(options[index]);
      }
    }
    return extended;
  }
  return defaults;
};

let chart = function (type, initialOptions, done) {
  let that = {};

  that.options = {};
  that.template = templates[type];

  that.update = function (newOptions) {
    that.options = extend(that.options, newOptions);

    // Transform pass 1 to get the padding
    let spec = transform(that.template, that.options);

    // Use padding and element size to set size, unless
    // size explicitly specified or element size is zero.
    let el = d3.select(that.options.el)[0][0];
    let sizeOptions = {};

    let style = window.getComputedStyle(el, null);
    let elWidth = window.parseInt(style.getPropertyValue('width'));
    let elHeight = window.parseInt(style.getPropertyValue('height'));

    if (elWidth !== 0 && elHeight !== 0) {
      if (that.options.width === undefined) {
        sizeOptions.width = elWidth;
        if (spec.padding) {
          sizeOptions.width -= spec.padding.left + spec.padding.right;
        }
      }
      if (that.options.height === undefined) {
        sizeOptions.height = elHeight;
        if (spec.padding) {
          sizeOptions.height -= spec.padding.top + spec.padding.bottom;
        }
      }
    }
    let curOptions = extend(that.options, sizeOptions);

    // Options that go directly to Vega runtime
    let vegaOptions = {
      el: curOptions.el,
      renderer: curOptions.renderer
    };

    // Transform pass 2 to get the final visualization
    that.spec = transform(that.template, curOptions);

    console.log(that.spec);

    vg.parse.spec(that.spec, function (chartObj) {
      let chart = chartObj(vegaOptions);
      let printSignal = (name, val) => console.log(name + ': ' + val);
      for (let i = 0; i < that.spec.signals.length; i += 1) {
        chart.onSignal(that.spec.signals[i].name, printSignal);
      }
      chart.update();
      if (done) {
        done(chart);
      }
    });
  };

  that.update(initialOptions);

  return that;
};

module.exports = {
  transform: transform,
  chart: chart,
  templates: templates
};
<commit_msg>Removing debug statements<commit_after>let libs = require('./libs');

let templates = {
  axis: require('../templates/axis.json'),
  bar: require('../templates/bar.json'),
  box: require('../templates/box.json'),
  bullet: require('../templates/bullet.json'),
  gantt: require('../templates/gantt.json'),
  histogram: require('../templates/histogram.json'),
  scatter: require('../templates/scatter.json'),
  vega: require('../templates/vega.json'),
  xy: require('../templates/xy.json'),
  xymatrix: require('../templates/xymatrix.json')
};

let d3 = libs.d3;
let vg = libs.vg;

let getNestedRec = function (spec, parts) {
  if (spec === undefined || parts.length === 0) {
    return spec;
  }
  return getNestedRec(spec[parts[0]], parts.slice(1));
};

let getNested = function (spec, name) {
  return getNestedRec(spec, name.split('.'));
};

let setNestedRec = function (spec, parts, value) {
  if (parts.length === 1) {
    spec[parts[0]] = value;
    return;
  }
  if (spec[parts[0]] === undefined) {
    spec[parts[0]] = {};
  }
  setNestedRec(spec[parts[0]], parts.slice(1), value);
};

let setNested = function (spec, name, value) {
  setNestedRec(spec, name.split('.'), value);
};

let templateFunctions = {
  defaults: function (args, options, scope) {
    for (let index = 0; index < args[0].length; index += 1) {
      let value = getNested(scope, args[0][index][0]);
      if (value === undefined) {
        value = getNested(options, args[0][index][0]);
      }
      if (value === undefined) {
        value = transform(args[0][index][1], options, scope);
        setNested(scope, args[0][index][0], value);
      }
    }
    return transform(args[1], options, scope);
  },

  let: function (args, options, scope) {
    for (let index = 0; index < args[0].length; index += 1) {
      let value = transform(args[0][index][1], options, scope);
      setNested(scope, args[0][index][0], value);
    }
    return transform(args[1], options, scope);
  },

  get: function (args, options, scope) {
    let value = getNested(scope, args[0]);
    if (value === undefined) {
      value = getNested(options, args[0]);
    }
    if (value === undefined) {
      value = transform(args[1], options, scope);
    }
    if (value === undefined) {
      value = null;
    }
    return value;
  },

  map: function (args, options, scope) {
    let transformed = [];
    let elements = transform(args[0], options, scope);

    for (let elementIndex = 0; elementIndex < elements.length; elementIndex += 1) {
      scope[args[1]] = elements[elementIndex];
      for (let itemIndex = 2; itemIndex < args.length; itemIndex += 1) {
        let element = transform(args[itemIndex], options, scope);
        if (element !== null) {
          transformed.push(element);
        }
      }
    }
    return transformed;
  },

  if: function (args, options, scope) {
    let condition = transform(args[0], options, scope);
    if (condition) {
      return transform(args[1], options, scope);
    }
    return transform(args[2], options, scope);
  },

  eq: function (args, options, scope) {
    let a = transform(args[0], options, scope);
    let b = transform(args[1], options, scope);
    return (a === b);
  },

  and: function (args, options, scope) {
    let arr = transform(args, options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (!arr[i]) {
        return false;
      }
    }
    return true;
  },

  or: function (args, options, scope) {
    let arr = transform(args, options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i]) {
        return true;
      }
    }
    return false;
  },

  join: function (args, options, scope) {
    let result = '';
    let sep = transform(args[0], options, scope);
    let arr = transform(args[1], options, scope);
    for (let i = 0; i < arr.length; i += 1) {
      if (i > 0) {
        result += sep;
      }
      result += arr[i];
    }
    return result;
  },

  merge: function (args, options, scope) {
    let merged = transform(args[0], options, scope);
    for (let i = 1; i < args.length; i += 1) {
      merged = merge(merged, transform(args[i], options, scope));
    }
    return merged;
  },

  apply: function (args, options, scope) {
    let templateName = transform(args[0], options, scope);
    let templateOptions = transform(args[1], options, scope);
    return transform(templates[templateName], templateOptions);
  },

  colorScale: function (args, options, scope) {
    let params = transform(args[0], options, scope);
    let name = params.name || 'color';
    if (!Array.isArray(params.values) ||
      params.values.length < 1 ||
      params.values[0][params.field] === undefined ||
      typeof params.values[0][params.field] === 'string') {
      return {
        name: name,
        type: 'ordinal',
        domain: {data: params.data, field: name},
        range: 'category10'
      };
    }
    return {
      name: name,
      type: 'linear',
      zero: false,
      domain: {data: params.data, field: name},
      range: ['#dfd', 'green']
    };
  },

  isStringField: function (args, options, scope) {
    let values = transform(args[0], options, scope);
    let field = transform(args[1], options, scope);

    if (!Array.isArray(values) ||
      values.length < 1 ||
      values[0][field] === undefined ||
      typeof values[0][field] === 'string') {
      return true;
    }
    return false;
  },

  orient: function (args, options, scope) {
    let dir = transform(args[0], options, scope);
    let obj = transform(args[1], options, scope);
    let transformed = {};
    let mapping = {
      x: 'y',
      x2: 'y2',
      xc: 'yc',
      y: 'x',
      y2: 'x2',
      yc: 'xc',
      width: 'height',
      height: 'width'
    };
    if (dir === 'horizontal') {
      return obj;
    }
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        if (mapping[key]) {
          transformed[mapping[key]] = obj[key];
        } else {
          transformed[key] = obj[key];
        }
      }
    }
    return transformed;
  }
};

let transform = function (spec, options, scope) {
  options = options || {};
  scope = scope || {};

  if (Array.isArray(spec)) {
    if (spec.length > 0 && (typeof spec[0] === 'string') && spec[0].slice(0, 1) === '@') {
      return templateFunctions[spec[0].slice(1)](spec.slice(1), options, scope);
    }
    let transformed = [];
    for (let index = 0; index < spec.length; index += 1) {
      transformed.push(transform(spec[index], options, scope));
    }
    return transformed;
  }
  if (spec === null) {
    return spec;
  }
  if (typeof spec === 'object') {
    let transformed = {};
    for (let key in spec) {
      if (spec.hasOwnProperty(key)) {
        transformed[key] = transform(spec[key], options, scope);
      }
    }
    return transformed;
  }
  return spec;
};

let isObjectLiteral = function (object) {
  return object && object.constructor && object.constructor.name === 'Object';
};

let isArrayLiteral = function (object) {
  return object && object.constructor && object.constructor.name === 'Array';
};

let extend = function (defaults, options) {
  if (options === undefined) {
    return defaults;
  }
  if (isObjectLiteral(defaults)) {
    let extended = {};
    for (let prop in defaults) {
      if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = extend(defaults[prop], options[prop]);
      }
    }
    for (let prop in options) {
      if (!Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = options[prop];
      }
    }
    return extended;
  }
  if (isArrayLiteral(defaults)) {
    let extended = [];
    for (let index = 0; index < defaults.length; index += 1) {
      extended.push(extend(defaults[index], options[index]));
    }
    if (isArrayLiteral(options)) {
      for (let index = defaults.length; index < options.length; index += 1) {
        extended.push(options[index]);
      }
    }
    return extended;
  }
  return options;
};

let merge = function (defaults, options) {
  if (options === undefined || options === null) {
    return defaults;
  }
  if (defaults === undefined || defaults === null) {
    return options;
  }
  if (isObjectLiteral(defaults)) {
    let extended = {};
    for (let prop in defaults) {
      if (Object.prototype.hasOwnProperty.call(defaults, prop)) {
        extended[prop] = merge(defaults[prop], options[prop]);
      }
    }
    for (let prop in options) {
      if (!Object.prototype.hasOwnProperty.call(extended, prop)) {
        extended[prop] = options[prop];
      }
    }
    return extended;
  }
  if (isArrayLiteral(defaults)) {
    let extended = [];
    for (let index = 0; index < defaults.length; index += 1) {
      extended.push(defaults[index]);
    }
    if (isArrayLiteral(options)) {
      for (let index = 0; index < options.length; index += 1) {
        extended.push(options[index]);
      }
    }
    return extended;
  }
  return defaults;
};

let chart = function (type, initialOptions, done) {
  let that = {};

  that.options = {};
  that.template = templates[type];

  that.update = function (newOptions) {
    that.options = extend(that.options, newOptions);

    // Transform pass 1 to get the padding
    let spec = transform(that.template, that.options);

    // Use padding and element size to set size, unless
    // size explicitly specified or element size is zero.
    let el = d3.select(that.options.el)[0][0];
    let sizeOptions = {};

    let style = window.getComputedStyle(el, null);
    let elWidth = window.parseInt(style.getPropertyValue('width'));
    let elHeight = window.parseInt(style.getPropertyValue('height'));

    if (elWidth !== 0 && elHeight !== 0) {
      if (that.options.width === undefined) {
        sizeOptions.width = elWidth;
        if (spec.padding) {
          sizeOptions.width -= spec.padding.left + spec.padding.right;
        }
      }
      if (that.options.height === undefined) {
        sizeOptions.height = elHeight;
        if (spec.padding) {
          sizeOptions.height -= spec.padding.top + spec.padding.bottom;
        }
      }
    }
    let curOptions = extend(that.options, sizeOptions);

    // Options that go directly to Vega runtime
    let vegaOptions = {
      el: curOptions.el,
      renderer: curOptions.renderer
    };

    // Transform pass 2 to get the final visualization
    that.spec = transform(that.template, curOptions);

    vg.parse.spec(that.spec, function (chartObj) {
      let chart = chartObj(vegaOptions);
      chart.update();
      if (done) {
        done(chart);
      }
    });
  };

  that.update(initialOptions);

  return that;
};

module.exports = {
  transform: transform,
  chart: chart,
  templates: templates
};
<|endoftext|>


<commit_before>/**
 * @name ChannelListController
 * @desc Controller for the channel-list view
 */

(function() {
    'use strict';

    angular.module('cometApp')
           .controller('ChannelListController', ChannelListController);

        ChannelListController.$inject = ['$rootScope',
                                         '$state',
                                         'filterFilter',
                                         'userService',
                                         'dialogService',
                                         'channels'];

        function ChannelListController ($rootScope,
                                        $state,
                                        filterFilter,
                                        userService,
                                        dialogService,
                                        channels) {

          var vmc = this;
          vmc.channels = null;
          vmc.isEmpty = true;
          vmc.gotoCreateChannel = gotoCreateChannel;

          activate();

          /**
           * @name activate
           * @desc controller activation logic
           */
          function activate () {
              vmc.channels = channels;
              vmc.isEmpty = (vmc.channels.length === 0);
          }

          /**
           * @name gotoCreateChannel
           * @desc validates the user account and redirects to the
           *       create channel page
           */
          function gotoCreateChannel(){
            userService.getCurrentUser().then(function (user) {
              if (user && user.confirmed) {
                $state.go('dashboard.project.channel-create');
              }
              else {
                dialogService.showModalAlert('Crear Canal', 'Debes confirmar tu cuenta para poder crear un proyecto');
              }
            });
          }
        }
})();
<commit_msg>Explorar proyecto - Dejo solo los caneles publicos y abiertos en el listado<commit_after>/**
 * @name ChannelListController
 * @desc Controller for the channel-list view
 */

(function() {
    'use strict';

    angular.module('cometApp')
           .controller('ChannelListController', ChannelListController);

        ChannelListController.$inject = ['$rootScope',
                                         '$state',
                                         'lodash',
                                         'filterFilter',
                                         'userService',
                                         'dialogService',
                                         'channels'];

        function ChannelListController ($rootScope,
                                        $state,
                                        lodash,
                                        filterFilter,
                                        userService,
                                        dialogService,
                                        channels) {

          var vmc = this;
          vmc.channels = null;
          vmc.isEmpty = true;
          vmc.gotoCreateChannel = gotoCreateChannel;

          activate();

          /**
           * @name activate
           * @desc controller activation logic
           */
          function activate () {

              vmc.channels = channels;

              // only public and opened channels
              lodash.remove(vmc.channels, function (c) {
                // remove the closed projects
                if (c.state !== 'O' || c.type === 'P') {
                  return true;
                }
                return false;
              });

              vmc.isEmpty = (vmc.channels.length === 0);
          }

          /**
           * @name gotoCreateChannel
           * @desc validates the user account and redirects to the
           *       create channel page
           */
          function gotoCreateChannel(){
            userService.getCurrentUser().then(function (user) {
              if (user && user.confirmed) {
                $state.go('dashboard.project.channel-create');
              }
              else {
                dialogService.showModalAlert('Crear Canal', 'Debes confirmar tu cuenta para poder crear un proyecto');
              }
            });
          }
        }
})();
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
 chalk = require('chalk'),
 assert = require('yeoman-generator').assert,
 helpers = require('yeoman-generator').test,
 os = require('os'),
 _ = require('lodash-node'),
 caseNum = 1,
 generatorPath = '../generators/app',
 outputDir = './temp-test',
 contextsDir = 'contexts',
 componentName = 'my-test-component',
 prompts0ContextsMultipleViewports = require(path.resolve('test/mockData', 'prompts0ContextsMultipleViewports.json')),
 prompts1ContextMultipleViewports = require(path.resolve('test/mockData', 'prompts1ContextMultipleViewports.json')),
 prompts2ContextsMultipleViewports = require(path.resolve('test/mockData', 'prompts2ContextsMultipleViewports.json')),
 prompts0Contexts1Viewport = require(path.resolve('test/mockData', 'prompts0Contexts1Viewport.json')),
 prompts1Context1Viewport = require(path.resolve('test/mockData', 'prompts1Context1Viewport.json')),
 prompts2Contexts1Viewport = require(path.resolve('test/mockData', 'prompts2Contexts1Viewport.json'));

var filesDefaults = [
   componentName + '/' + 'media/',
   componentName + '/' + 'index.html',
   componentName + '/' + 'index.js',
   componentName + '/' + 'print.css'
 ];

var files0ContextsMultipleViewports = [
  componentName + '/' + '0-600.css',
  componentName + '/' + '600-1024.css',
  componentName + '/' + '1024+.css'
];

// Default prompt options
var files1ContextMultipleViewports = [
  componentName + '/' + contextsDir + '/' + 'mysite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'mysite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'mysite/1024+.css'
];

var files2ContextsMultipleViewports = [
  componentName + '/' + contextsDir + '/' + 'mysite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'mysite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'mysite/1024+.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/1024+.css'
];

var files0Contexts1Viewport = [
  componentName + '/' + 'all.css'
];

var files1Context1Viewport = [
  componentName + '/' + contextsDir + '/' + 'mysite/all.css'
];

var files2Contexts1Viewport = [
  componentName + '/' + contextsDir + '/' + 'mysite/all.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/all.css'
];

function printPromptDetails (props) {
  var msg = '';

  for (var key in props) {
    msg += '\n' + _.startCase(key) + ':\t' + props[key];
  }

  console.log(
    chalk.yellow(
    '\n---- DETAILS ----',
    msg, '\n'
  ));
};

// 0 Contexts, Multiple Viewports
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts0ContextsMultipleViewports)
      .on('end', done);
  });

  it('create files - (0 Contexts, Multiple Viewports)', function () {
    assert.file(filesDefaults);
    assert.file(files0ContextsMultipleViewports);
  });

  after(function() {
    printPromptDetails(prompts0ContextsMultipleViewports);
    console.log(files0ContextsMultipleViewports);
  });
});

// 1 Context, Multiple Viewports - default
describe('component:app - case ' + caseNum++, function () {
  console.log('\nTesting ' + chalk.yellow(componentName) + ' component...');

  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts1ContextMultipleViewports)
      .on('end', done);
  });

  it('create files - (1 Context, Multiple Viewports - default)', function () {
    assert.file(filesDefaults);

    assert.file(files1ContextMultipleViewports);
  });

  after(function () {
    printPromptDetails(prompts1ContextMultipleViewports);
    console.log(files1ContextMultipleViewports);
  });
});

// 2 Contexts, Multiple Viewports
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts2ContextsMultipleViewports)
      .on('end', done);
  });

  it('create files - (2 Contexts, Multiple Viewports)', function () {
    assert.file(filesDefaults);
    assert.file(files2ContextsMultipleViewports);
  });

  after(function () {
    printPromptDetails(prompts2ContextsMultipleViewports);
    console.log(files2ContextsMultipleViewports);
  });
});

// 0 Contexts, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts0Contexts1Viewport)
      .on('end', done);
  });

  it('create files - (0 Contexts, 1 Viewport)', function () {
    assert.file(filesDefaults);
    assert.file(files0Contexts1Viewport);
  });

  after(function(){
    printPromptDetails(prompts0Contexts1Viewport);
    console.log(files0Contexts1Viewport);
  });
});

// 1 Context, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts1Context1Viewport)
      .on('end', done);
  });

  it('create files - (1 Context, 1 Viewport)', function () {
    assert.file(filesDefaults);
    assert.file(files1Context1Viewport);
  });

  after(function() {
    printPromptDetails(prompts1Context1Viewport);
    console.log(files1Context1Viewport);
  });
});

// 2 Contexts, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts2Contexts1Viewport)
      .on('end', done);
  });

  it('create files - (2 Contexts, 1 Viewport)', function () {
    // TODO: Fix failure
    assert.file(filesDefaults);
    // assert.file(files2Contexts1Viewport);
  });

  after(function() {
    printPromptDetails(prompts2Contexts1Viewport);
    console.log(files2Contexts1Viewport);
  });
});
<commit_msg>Test: Fixed 2Contexts1Viewport case failure<commit_after>'use strict';

var path = require('path'),
 chalk = require('chalk'),
 assert = require('yeoman-generator').assert,
 helpers = require('yeoman-generator').test,
 os = require('os'),
 _ = require('lodash-node'),
 caseNum = 1,
 generatorPath = '../generators/app',
 outputDir = './temp-test',
 contextsDir = 'contexts',
 componentName = 'my-test-component',
 prompts0ContextsMultipleViewports = require(path.resolve('test/mockData', 'prompts0ContextsMultipleViewports.json')),
 prompts1ContextMultipleViewports = require(path.resolve('test/mockData', 'prompts1ContextMultipleViewports.json')),
 prompts2ContextsMultipleViewports = require(path.resolve('test/mockData', 'prompts2ContextsMultipleViewports.json')),
 prompts0Contexts1Viewport = require(path.resolve('test/mockData', 'prompts0Contexts1Viewport.json')),
 prompts1Context1Viewport = require(path.resolve('test/mockData', 'prompts1Context1Viewport.json')),
 prompts2Contexts1Viewport = require(path.resolve('test/mockData', 'prompts2Contexts1Viewport.json'));

var filesDefaults = [
   componentName + '/' + 'media/',
   componentName + '/' + 'index.html',
   componentName + '/' + 'index.js',
   componentName + '/' + 'print.css'
 ];

var files0ContextsMultipleViewports = [
  componentName + '/' + '0-600.css',
  componentName + '/' + '600-1024.css',
  componentName + '/' + '1024+.css'
];

// Default prompt options
var files1ContextMultipleViewports = [
  componentName + '/' + contextsDir + '/' + 'mysite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'mysite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'mysite/1024+.css'
];

var files2ContextsMultipleViewports = [
  componentName + '/' + contextsDir + '/' + 'mysite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'mysite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'mysite/1024+.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/0-600.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/600-1024.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/1024+.css'
];

var files0Contexts1Viewport = [
  componentName + '/' + 'all.css'
];

var files1Context1Viewport = [
  componentName + '/' + contextsDir + '/' + 'mysite/all.css'
];

var files2Contexts1Viewport = [
  componentName + '/' + contextsDir + '/' + 'mysite/all.css',
  componentName + '/' + contextsDir + '/' + 'myothersite/all.css'
];

function printPromptDetails (props) {
  var msg = '';

  for (var key in props) {
    msg += '\n' + _.startCase(key) + ':\t' + props[key];
  }

  console.log(
    chalk.yellow(
    '\n---- DETAILS ----',
    msg, '\n'
  ));
};

// 0 Contexts, Multiple Viewports
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts0ContextsMultipleViewports)
      .on('end', done);
  });

  it('create files - (0 Contexts, Multiple Viewports)', function () {
    assert.file(filesDefaults);
    assert.file(files0ContextsMultipleViewports);
  });

  after(function() {
    printPromptDetails(prompts0ContextsMultipleViewports);
    console.log(files0ContextsMultipleViewports);
  });
});

// 1 Context, Multiple Viewports - default
describe('component:app - case ' + caseNum++, function () {
  console.log('\nTesting ' + chalk.yellow(componentName) + ' component...');

  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts1ContextMultipleViewports)
      .on('end', done);
  });

  it('create files - (1 Context, Multiple Viewports - default)', function () {
    assert.file(filesDefaults);

    assert.file(files1ContextMultipleViewports);
  });

  after(function () {
    printPromptDetails(prompts1ContextMultipleViewports);
    console.log(files1ContextMultipleViewports);
  });
});

// 2 Contexts, Multiple Viewports
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts2ContextsMultipleViewports)
      .on('end', done);
  });

  it('create files - (2 Contexts, Multiple Viewports)', function () {
    assert.file(filesDefaults);
    assert.file(files2ContextsMultipleViewports);
  });

  after(function () {
    printPromptDetails(prompts2ContextsMultipleViewports);
    console.log(files2ContextsMultipleViewports);
  });
});

// 0 Contexts, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts0Contexts1Viewport)
      .on('end', done);
  });

  it('create files - (0 Contexts, 1 Viewport)', function () {
    assert.file(filesDefaults);
    assert.file(files0Contexts1Viewport);
  });

  after(function(){
    printPromptDetails(prompts0Contexts1Viewport);
    console.log(files0Contexts1Viewport);
  });
});

// 1 Context, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts1Context1Viewport)
      .on('end', done);
  });

  it('create files - (1 Context, 1 Viewport)', function () {
    assert.file(filesDefaults);
    assert.file(files1Context1Viewport);
  });

  after(function() {
    printPromptDetails(prompts1Context1Viewport);
    console.log(files1Context1Viewport);
  });
});

// 2 Contexts, 1 Viewport
describe('component:app - case ' + caseNum++, function () {
  before(function (done) {
    helpers.run(path.join(__dirname, generatorPath))
      .inDir(path.join(os.tmpdir(), outputDir))
      .withArguments([componentName])              // Mock the arguments
      .withPrompt(prompts2Contexts1Viewport)
      .on('end', done);
  });

  it('create files - (2 Contexts, 1 Viewport)', function () {
    assert.file(filesDefaults);
    assert.file(files2Contexts1Viewport);
  });

  after(function() {
    printPromptDetails(prompts2Contexts1Viewport);
    console.log(files2Contexts1Viewport);
  });
});
<|endoftext|>


<commit_before>require(['wire'], function(wire) {

	wire({
		plugins: [
//					{ module: 'wire/debug' },
			{ module: pluginName }
		],
		node1: { $ref: 'dom.all!#node1' },
		divs: { $ref: 'dom.all!.test' },
		div: { $ref: 'dom.all!.test', i: 0 },
		atNode: { $ref: 'dom.all!div', i: 0 },
		deep: { $ref: 'dom.all!p', at: { $ref: 'atNode' }, i: 0 },
		deep2: { $ref: 'dom.all!p', at: 'atNode', i: 0 },
		domFirst: { $ref: 'dom.first!.test' },
		domFirstAt: { $ref: 'dom.first!p', at: { $ref: 'atNode' } },
		byIdResolver: { $ref:'dom!' },
		firstResolver: { $ref:'dom.first!' },
		allResolver: { $ref:'dom.all!' },

		// test element factory and facets
		get1: {
			element: { $ref: 'dom!get1' },
			properties: {
				'class': 'foo',
				target: 'top',
				href: '#'
			},
			insert: {
				at: { $ref: 'dom!get1-inserts-here' }
			},
			ready: {
				focus: [],
				appendChild: { $ref: 'dom!get1-appends-this' }
			}
		},

		// test clone factory and facets
		clone1: {
			clone: { $ref: 'dom!clone1' },
			properties: {
				'class': 'foo',
				target: 'top',
				href: '#',
				id: 'anotherId'
			},
			insert: {
				at: { $ref: 'dom!clone1-inserts-here' }
			},
			ready: {
				appendChild: { $ref: 'dom!clone1-appends-this' }
			}
		}
	}).then(
		function(context) {
			doh.register(pluginName, [
				function domAllReturnsAtLeastOne(doh) {
					// dom.all/query always returns an array, so test
					// against the first
					doh.assertEqual(1, context.node1.length);
					doh.assertEqual('node1', context.node1[0].id);
				},
				function domAllLength(doh) {
					doh.assertEqual(3, context.divs.length);
				},
				function domAllIndexZeroReturnsFirst(doh) {
					// Using the plugin's i option to extract a single
					// node
					doh.assertEqual('test one', context.div.className);
				},
				function domAllAtWithRef(doh) {
					// Checking "at" option (root/context).
					doh.assertEqual('node1', context.deep && context.deep.id);
				},
				function domAllAtWithString(doh) {
					// Checking "at" option without $ref
					doh.assertEqual('node1', context.deep2 && context.deep2.id);
				},
				function domFirst(doh) {
					// basic dom.first!
					doh.assertEqual('test one', context.domFirst.className);
				},
				function byIdResolver(doh) {
					// should return a byId resolver
					var node = context.byIdResolver('node1');
					doh.assertEqual(node, context.node1[0]);
				},
				function firstResolver(doh) {
					// should return a byId resolver
					var node = context.firstResolver('.test');
					doh.assertEqual(node, context.domFirst);
				},
				function allResolver(doh) {
					// should return a byId resolver
					var node = context.allResolver('div')[0];
					doh.assertEqual(node, context.atNode);
				},
				function domFirstNoMatch(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.first!.this-will-fail' }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllOutOfBoundsHigh(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: 10 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllOutOfBoundsLow(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: -1 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllWithNonNumericIndex(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: 'foo' }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domFirstWithIndex(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.first!.test', i: 0 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function pluginAt(doh) {
					// ensure the at option works at the plugin level
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName, at: 'dom.first!#at-tests .root' },
						node: { $ref: 'dom.first!.at-test' }
					}).then(
						function(context) {
							dohd.callback(context.node.className === 'at-test ok');
						},
						dohd.errback
					);

					return dohd;
				},
				function optionAtOverridespluginAt(doh) {
					// ensure the at option is overridable
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName, at: 'dom.first!#at-tests .root' },
						nodes: { $ref: 'dom.all!.test', at: 'dom.first!body' }
					}).then(
						function(context) {
							dohd.callback(context.nodes.length === 3);
						},
						function(e) {
							dohd.errback(e);
						}
					);

					return dohd;
				},
				function testAddRemoveClass(doh) {
					var dohd = new doh.Deferred();

					wire({
						plugins: [
//                            { module: 'wire/debug' },
							{ module: pluginName, classes: { init: 'init', ready: 'ready' } }
						],
						node: { $ref: 'dom!node1' }
					}).then(
						function(context) {
							var html;
							html = document.getElementsByTagName('html')[0];
							dohd.callback(html.className === 'ready' && ('node1' === context.node.id));
						},
						function(e) {
							dohd.errback(e);
						}
					);

					return dohd;
				},
				function unresolveableSelectorIsUnresolvable(doh) {
					var dohd = new doh.Deferred();

					wire({
						plugins: [
//                            { module: 'wire/debug' },
							{ module: pluginName }
						],
						node: { $ref: 'dom!node3' }
					}).then(
						function(context) {
							dohd.errback('node3 should not have been resolvable');
						},
						function(e) {
							dohd.callback(true);
						}
					);

					return dohd;
				},

				// element factory tests

				function elementGetsAnElement(doh) {
					doh.assertEqual(context.get1, document.getElementById('get1'));
				},
				function elementAllowsProperties(doh) {
					doh.assertEqual(context.get1.className, 'foo');
					doh.assertEqual(context.get1.target, 'top');
				},
				function elementAllowsInsert(doh) {
					doh.assertEqual(context.get1.parentNode, document.getElementById('get1-inserts-here'));
				},
				function elementAllowsInvoke(doh) {
					doh.assertEqual(context.get1.firstChild, document.getElementById('get1-appends-this'));
					doh.assertEqual(context.get1, document.activeElement);
				},

				// clone tests

				function cloneElementLeavesElementInDom(doh) {
					doh.assertNotEqual(context.clone1, document.getElementById('clone1'));
				},
				function cloneElementIsAnElement(doh) {
					doh.assertEqual(context.clone1.nodeType, 1);
				},
				function cloneElementAllowsProperties(doh) {
					doh.assertEqual(context.clone1.className, 'foo');
					doh.assertEqual(context.clone1.target, 'top');
				},
				function cloneElementAllowsInsert(doh) {
					doh.assertEqual(context.clone1.parentNode, document.getElementById('clone1-inserts-here'));
				},
				function cloneElementAllowsInvoke(doh) {
					doh.assertEqual(context.clone1.firstChild, document.getElementById('clone1-appends-this'));
				}
			]);

			doh.run();
		},
		function(err) {
			console.log(err);
			console.log(err.stack);
		}
	);
});
<commit_msg>Add unit test for missing plugin when using insert facet<commit_after>require(['wire'], function(wire) {

	wire({
		plugins: [
//					{ module: 'wire/debug' },
			{ module: pluginName }
		],
		node1: { $ref: 'dom.all!#node1' },
		divs: { $ref: 'dom.all!.test' },
		div: { $ref: 'dom.all!.test', i: 0 },
		atNode: { $ref: 'dom.all!div', i: 0 },
		deep: { $ref: 'dom.all!p', at: { $ref: 'atNode' }, i: 0 },
		deep2: { $ref: 'dom.all!p', at: 'atNode', i: 0 },
		domFirst: { $ref: 'dom.first!.test' },
		domFirstAt: { $ref: 'dom.first!p', at: { $ref: 'atNode' } },
		byIdResolver: { $ref:'dom!' },
		firstResolver: { $ref:'dom.first!' },
		allResolver: { $ref:'dom.all!' },

		// test element factory and facets
		get1: {
			element: { $ref: 'dom!get1' },
			properties: {
				'class': 'foo',
				target: 'top',
				href: '#'
			},
			insert: {
				at: { $ref: 'dom!get1-inserts-here' }
			},
			ready: {
				focus: [],
				appendChild: { $ref: 'dom!get1-appends-this' }
			}
		},

		// test clone factory and facets
		clone1: {
			clone: { $ref: 'dom!clone1' },
			properties: {
				'class': 'foo',
				target: 'top',
				href: '#',
				id: 'anotherId'
			},
			insert: {
				at: { $ref: 'dom!clone1-inserts-here' }
			},
			ready: {
				appendChild: { $ref: 'dom!clone1-appends-this' }
			}
		}
	}).then(
		function(context) {
			doh.register(pluginName, [
				function domAllReturnsAtLeastOne(doh) {
					// dom.all/query always returns an array, so test
					// against the first
					doh.assertEqual(1, context.node1.length);
					doh.assertEqual('node1', context.node1[0].id);
				},
				function domAllLength(doh) {
					doh.assertEqual(3, context.divs.length);
				},
				function domAllIndexZeroReturnsFirst(doh) {
					// Using the plugin's i option to extract a single
					// node
					doh.assertEqual('test one', context.div.className);
				},
				function domAllAtWithRef(doh) {
					// Checking "at" option (root/context).
					doh.assertEqual('node1', context.deep && context.deep.id);
				},
				function domAllAtWithString(doh) {
					// Checking "at" option without $ref
					doh.assertEqual('node1', context.deep2 && context.deep2.id);
				},
				function domFirst(doh) {
					// basic dom.first!
					doh.assertEqual('test one', context.domFirst.className);
				},
				function byIdResolver(doh) {
					// should return a byId resolver
					var node = context.byIdResolver('node1');
					doh.assertEqual(node, context.node1[0]);
				},
				function firstResolver(doh) {
					// should return a byId resolver
					var node = context.firstResolver('.test');
					doh.assertEqual(node, context.domFirst);
				},
				function allResolver(doh) {
					// should return a byId resolver
					var node = context.allResolver('div')[0];
					doh.assertEqual(node, context.atNode);
				},
				function domFirstNoMatch(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.first!.this-will-fail' }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllOutOfBoundsHigh(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: 10 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllOutOfBoundsLow(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: -1 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domAllWithNonNumericIndex(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.all!.test', i: 'foo' }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function domFirstWithIndex(doh) {
					// should fail wiring when query fails
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName },
						node: { $ref: 'dom.first!.test', i: 0 }
					}).then(
						function(e) {
							dohd.errback(e);
						},
						function() {
							dohd.callback(true);
						}
					);

					return dohd;
				},
				function pluginAt(doh) {
					// ensure the at option works at the plugin level
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName, at: 'dom.first!#at-tests .root' },
						node: { $ref: 'dom.first!.at-test' }
					}).then(
						function(context) {
							dohd.callback(context.node.className === 'at-test ok');
						},
						dohd.errback
					);

					return dohd;
				},
				function optionAtOverridespluginAt(doh) {
					// ensure the at option is overridable
					var dohd = new doh.Deferred();

					wire({
						dom: { module: pluginName, at: 'dom.first!#at-tests .root' },
						nodes: { $ref: 'dom.all!.test', at: 'dom.first!body' }
					}).then(
						function(context) {
							dohd.callback(context.nodes.length === 3);
						},
						function(e) {
							dohd.errback(e);
						}
					);

					return dohd;
				},
				function testAddRemoveClass(doh) {
					var dohd = new doh.Deferred();

					wire({
						plugins: [
//                            { module: 'wire/debug' },
							{ module: pluginName, classes: { init: 'init', ready: 'ready' } }
						],
						node: { $ref: 'dom!node1' }
					}).then(
						function(context) {
							var html;
							html = document.getElementsByTagName('html')[0];
							dohd.callback(html.className === 'ready' && ('node1' === context.node.id));
						},
						function(e) {
							dohd.errback(e);
						}
					);

					return dohd;
				},
				function unresolveableSelectorIsUnresolvable(doh) {
					var dohd = new doh.Deferred();

					wire({
						plugins: [
//                            { module: 'wire/debug' },
							{ module: pluginName }
						],
						node: { $ref: 'dom!node3' }
					}).then(
						function(context) {
							dohd.errback('node3 should not have been resolvable');
						},
						function(e) {
							dohd.callback(true);
						}
					);

					return dohd;
				},

				function insertShouldFailLoudlyIfPluginNotPresent(doh) {
					var dohd = new doh.Deferred();

					wire({
						node: {
							// Intentionally missing plugin
							literal: {}, // doesn't matter,
							insert: { last: { $ref: 'dom.first!body' } }
						}
					}).then(
						function() {
							dohd.errback('insert should have caused wiring failure')
						},
						function() {
							dohd.callback(true);
						}
					);
				},

				// element factory tests

				function elementGetsAnElement(doh) {
					doh.assertEqual(context.get1, document.getElementById('get1'));
				},
				function elementAllowsProperties(doh) {
					doh.assertEqual(context.get1.className, 'foo');
					doh.assertEqual(context.get1.target, 'top');
				},
				function elementAllowsInsert(doh) {
					doh.assertEqual(context.get1.parentNode, document.getElementById('get1-inserts-here'));
				},
				function elementAllowsInvoke(doh) {
					doh.assertEqual(context.get1.firstChild, document.getElementById('get1-appends-this'));
					doh.assertEqual(context.get1, document.activeElement);
				},

				// clone tests

				function cloneElementLeavesElementInDom(doh) {
					doh.assertNotEqual(context.clone1, document.getElementById('clone1'));
				},
				function cloneElementIsAnElement(doh) {
					doh.assertEqual(context.clone1.nodeType, 1);
				},
				function cloneElementAllowsProperties(doh) {
					doh.assertEqual(context.clone1.className, 'foo');
					doh.assertEqual(context.clone1.target, 'top');
				},
				function cloneElementAllowsInsert(doh) {
					doh.assertEqual(context.clone1.parentNode, document.getElementById('clone1-inserts-here'));
				},
				function cloneElementAllowsInvoke(doh) {
					doh.assertEqual(context.clone1.firstChild, document.getElementById('clone1-appends-this'));
				}
			]);

			doh.run();
		},
		function(err) {
			console.log(err);
			console.log(err.stack);
		}
	);
});
<|endoftext|>


<commit_before>var Ezlog = require('ezlog'),
		log = new Ezlog({pref:{t:'[TaskList]',c:'green'}});

var TaskList = function TaskList (o){
  o = o || {};

  //log('TaskList initialized');

  return this;
};

/**
 * @method start         Check if requirements are met
 * @req    url {string}  Url to grab source code from
 */
TaskList.prototype.start = function (){
	//log("startin' task");

	this.d.hello = 'world';

	return this.f_next();
};

/**
 * @method getSource          Gets a website source code
 * @data   d.source {string}  Website it's source code
 */
TaskList.prototype.getSource = function (){
	//log("gettin' source");

	var self = this;

	if(Math.random() > 0.3)
		return self.f_retryAll('Debugger retry', new Error('Node err here'));

	return self.f_next();
};

/**
 * @method writeSource        Writes a source code on HD
 * @req    d.source {string}  Website it's source page
 */
TaskList.prototype.writeSource = function (){
	//log("writin' souce");

	var self = this;

	return self.f_next();
};

/**
 * @method notify  Log what happened in the previous methods
 */
TaskList.prototype.notify = function (){
	//log('HELLO notify');

	var self = this;

	return self.f_next();
};

TaskList.prototype.onRetryAll = function (){

};

TaskList.prototype.onNext = function (nextData){
	//log('!onNext!' + JSON.stringify(nextData));
};

TaskList.prototype.onFinish = function (){
	log('!onFinish!');
};

TaskList.prototype.onAbort = function (){
	//log('!onAbort!');
};

// Adding data to Class prototype object, will be same in every instance.
// No need to add in our shared data object namespace, which could be reset.
// Also using the prototype object, we only assign it once.
TaskList.prototype.writeDir = './sourceCodes';

module.exports = TaskList;<commit_msg>Better prototype object creation/inheritance in TaskList.js<commit_after>var Ezlog = require('ezlog'),
		log = new Ezlog({pref:{t:'[TaskList]',c:'green'}});

function TaskList (o){
  o = o || {};

  //log('TaskList initialized');

  return this;
};

var proto = Object.create(null);

/**
 * @method start         Check if requirements are met
 * @req    url {string}  Url to grab source code from
 */
proto.start = function (){
	//log("startin' task");

	this.d.hello = 'world';

	return this.f_next();
};

/**
 * @method getSource          Gets a website source code
 * @data   d.source {string}  Website it's source code
 */
proto.getSource = function (){
	//log("gettin' source");

	var self = this;

	if(Math.random() > 0.3)
		return self.f_retryAll('Debugger retry', new Error('Node err here'));

	return self.f_next();
};

/**
 * @method writeSource        Writes a source code on HD
 * @req    d.source {string}  Website it's source page
 */
proto.writeSource = function (){
	//log("writin' souce");

	var self = this;

	return self.f_next();
};

/**
 * @method notify  Log what happened in the previous methods
 */
proto.notify = function (){
	//log('HELLO notify');

	var self = this;

	return self.f_next();
};

proto.onRetryAll = function (){

};

proto.onNext = function (nextData){
	//log('!onNext!' + JSON.stringify(nextData));
};

proto.onFinish = function (){
	log('!onFinish!');
};

proto.onAbort = function (){
	//log('!onAbort!');
};

// Adding data to Class prototype object, will be same in every instance.
// No need to add in our shared data object namespace, which could be reset.
// Also using the prototype object, we only assign it once.
proto.writeDir = './sourceCodes';

TaskList.prototype = Object.create(proto);

module.exports = TaskList;<|endoftext|>