<commit_before>import $ from '-jquery';

import {
  click,
  triggerEvent,
  keyEvent
} from 'ember-native-dom-helpers';

import {
  guardMultiple,
  buildSelector,
  findClosestValue
} from '../helpers';
import {
  fillElement
} from './helpers';
import {
  ELEMENT_NOT_FOUND,
  throwBetterError
} from '../better-errors';

const KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup'];

export default function ExecutionContext(pageObjectNode, testContext) {
  this.pageObjectNode = pageObjectNode;
  this.testContext = testContext;
}

ExecutionContext.prototype = {
  run(cb) {
    return cb(this);
  },

  runAsync() {
    throw new Error('not implemented');
  },

  click(selector, container) {
    const el = this.$(selector, container)[0];
    click(el);
  },

  fillIn(selector, container, options, content) {
    let el = this.$(selector, container)[0];

    fillElement(el, content, {
      selector,
      pageObjectNode: this.pageObjectNode,
      pageObjectKey: options.pageObjectKey
    });

    triggerEvent(el, 'input');
    triggerEvent(el, 'change');
  },

  $(selector, container) {
    if (container) {
      return $(selector, container);
    } else {
      // @todo: we should fixed usage of private `_element`
      // after https://github.com/emberjs/ember-test-helpers/issues/184 is resolved
      let testsContainer = this.testContext ?
        this.testContext._element :
        '#ember-testing';

      return $(selector, testsContainer);
    }
  },

  triggerEvent(selector, container, eventName, eventOptions) {
    const element = this.$(selector, container)[0];

    // `keyCode` is a deprecated property.
    // @see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    // Due to this deprecation `ember-native-dom-helpers` doesn't accept `keyCode` as a `KeyboardEvent` option.
    if (typeof eventOptions.key === 'undefined' && typeof eventOptions.keyCode !== 'undefined') {
      eventOptions.key = eventOptions.keyCode.toString();
      delete eventOptions.keyCode;
    }

    if (KEYBOARD_EVENT_TYPES.indexOf(eventName) > -1) {
      keyEvent(element, eventName, eventOptions.key, eventOptions);
    } else {
      triggerEvent(element, eventName, eventOptions);
    }
  },

  assertElementExists(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    let result = this.$(selector, container);

    if (result.length === 0) {
      throwBetterError(
        this.pageObjectNode,
        options.pageObjectKey,
        ELEMENT_NOT_FOUND,
        { selector }
      );
    }
  },

  find(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    selector = buildSelector(this.pageObjectNode, selector, options);

    let result = this.$(selector, container);

    guardMultiple(result, selector, options.multiple);

    return result;
  },

  findWithAssert(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    selector = buildSelector(this.pageObjectNode, selector, options);

    let result = this.$(selector, container);

    if (result.length === 0) {
      throwBetterError(
        this.pageObjectNode,
        options.pageObjectKey,
        ELEMENT_NOT_FOUND,
        { selector }
      );
    }

    guardMultiple(result, selector, options.multiple);

    return result;
  }
};

<commit_msg>Add support for multiple fillIn<commit_after>import $ from '-jquery';

import {
  click,
  triggerEvent,
  keyEvent
} from 'ember-native-dom-helpers';

import {
  guardMultiple,
  buildSelector,
  findClosestValue
} from '../helpers';
import {
  fillElement
} from './helpers';
import {
  ELEMENT_NOT_FOUND,
  throwBetterError
} from '../better-errors';

const KEYBOARD_EVENT_TYPES = ['keydown', 'keypress', 'keyup'];

export default function ExecutionContext(pageObjectNode, testContext) {
  this.pageObjectNode = pageObjectNode;
  this.testContext = testContext;
}

ExecutionContext.prototype = {
  run(cb) {
    return cb(this);
  },

  runAsync() {
    throw new Error('not implemented');
  },

  click(selector, container) {
    const el = this.$(selector, container)[0];
    click(el);
  },

  fillIn(selector, container, options, content) {
    let elements = this.$(selector, container).toArray();

    elements.forEach((el) => {
      fillElement(el, content, {
        selector,
        pageObjectNode: this.pageObjectNode,
        pageObjectKey: options.pageObjectKey
      });

      triggerEvent(el, 'input');
      triggerEvent(el, 'change');
    });
  },

  $(selector, container) {
    if (container) {
      return $(selector, container);
    } else {
      // @todo: we should fixed usage of private `_element`
      // after https://github.com/emberjs/ember-test-helpers/issues/184 is resolved
      let testsContainer = this.testContext ?
        this.testContext._element :
        '#ember-testing';

      return $(selector, testsContainer);
    }
  },

  triggerEvent(selector, container, eventName, eventOptions) {
    const element = this.$(selector, container)[0];

    // `keyCode` is a deprecated property.
    // @see: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode
    // Due to this deprecation `ember-native-dom-helpers` doesn't accept `keyCode` as a `KeyboardEvent` option.
    if (typeof eventOptions.key === 'undefined' && typeof eventOptions.keyCode !== 'undefined') {
      eventOptions.key = eventOptions.keyCode.toString();
      delete eventOptions.keyCode;
    }

    if (KEYBOARD_EVENT_TYPES.indexOf(eventName) > -1) {
      keyEvent(element, eventName, eventOptions.key, eventOptions);
    } else {
      triggerEvent(element, eventName, eventOptions);
    }
  },

  assertElementExists(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    let result = this.$(selector, container);

    if (result.length === 0) {
      throwBetterError(
        this.pageObjectNode,
        options.pageObjectKey,
        ELEMENT_NOT_FOUND,
        { selector }
      );
    }
  },

  find(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    selector = buildSelector(this.pageObjectNode, selector, options);

    let result = this.$(selector, container);

    guardMultiple(result, selector, options.multiple);

    return result;
  },

  findWithAssert(selector, options) {
    let container = options.testContainer || findClosestValue(this.pageObjectNode, 'testContainer');

    selector = buildSelector(this.pageObjectNode, selector, options);

    let result = this.$(selector, container);

    if (result.length === 0) {
      throwBetterError(
        this.pageObjectNode,
        options.pageObjectKey,
        ELEMENT_NOT_FOUND,
        { selector }
      );
    }

    guardMultiple(result, selector, options.multiple);

    return result;
  }
};

<|endoftext|>


<commit_before>function ColorMapService() {

    //blue to red gradient for environmental variables
    function tempColor(index, count, min, max ) {
        hue1 = 240 - (((index - min) / (max - min)) * 240);
        hue = (hue1 - 240);
        return 'hsl('+hue+',100%, 50%)';
    }

    //normal gradient
    function mapColor(index, count) {
        hue = 240 -  (index / count)*240;
        return 'hsl(' + hue + ',100%,50%)';
    }

    function mapColorMonochrome(min, max, value) {
        var lum = (value-min)/(max-min) * 95;
        return 'hsl(0, 65%,'+lum+'%)'; //RED hue - can be changed
    }

    this.generateColorMap = function(results) {
        var colors = {};
        for (var i = 0; i < results.societies.length; i++) {
            var society = results.societies[i];
                for (var j = 0; j < society.environmental_values.length; j++) {
                    variable = results.environmental_variables.filter(function(env_var) {
                        return env_var.id == society.environmental_values[j].variable;
                    });
                    if (variable.length > 0) {
                        var color = tempColor(society.environmental_values[0].value, results.environmental_variables[0].range, results.environmental_variables[0].min, results.environmental_variables[0].max);
                        colors[society.society.id] = color;
                    }
                }

            for (var j = 0; j < society.variable_coded_values.length; j++) {
                if (society.variable_coded_values[j].code_description && (society.variable_coded_values[j].code_description.description.indexOf("Missing data") != -1))
                    colors[society.society.id] = 'hsl(0, 0%, 100%)';
                else if (society.bf_cont_var) {
                    var color = mapColorMonochrome(results.code_ids[society.variable_coded_values[j].variable].min, results.code_ids[society.variable_coded_values[j].variable].max, society.variable_coded_values[j].coded_value);
                    colors[society.society.id] = color;
                } else {
                    var color = mapColor(society.variable_coded_values[j].coded_value, results.code_ids[society.variable_coded_values[j].variable].length);
                    colors[society.society.id] = color;
                }
            }

            if (society.language_family) {
                var color = mapColor(society.language_family, society.num_classifications);
                colors[society.society.id] = color;
            }
        }
        return colors;
    };
}
<commit_msg>Fixing gradients<commit_after>function ColorMapService() {

    //blue to red gradient for environmental variables
    function tempColor(index, min, max, id ) {
    if (id == 34 || id == 36) {
        hue = 30 + (((index - min) / (max - min)) * 88);
    } else if (id == 27){
        color = mapColorMonochrome(min, max, index, 252);
        return color;
    }
    else {
    hue = 240 - (((index - min) / (max - min))*240);
    }
        return 'hsl('+hue+',100%, 50%)';
    }

    //normal gradient
    function mapColor(index, count) {
        hue = 240 -  (index / count)*240;
        return 'hsl(' + hue + ',100%,50%)';
    }

    function mapColorMonochrome(min, max, value, color) {
        var lum = (((value-min)/(max-min))) * 95;
        lum = 100 - lum;
        return 'hsl('+color+', 65%,'+lum+'%)'; //RED hue - can be changed
    }

    this.generateColorMap = function(results) {
        var colors = {};
        for (var i = 0; i < results.societies.length; i++) {
            var society = results.societies[i];
                for (var j = 0; j < society.environmental_values.length; j++) {
                    variable = results.environmental_variables.filter(function(env_var) {
                        return env_var.id == society.environmental_values[j].variable;
                    });
                    if (variable.length > 0) {
                        var color = tempColor(society.environmental_values[0].value,  results.environmental_variables[0].min, results.environmental_variables[0].max, results.environmental_variables[0].id);
                        colors[society.society.id] = color;
                    }
                }

            for (var j = 0; j < society.variable_coded_values.length; j++) {
                if (society.variable_coded_values[j].code_description && (society.variable_coded_values[j].code_description.description.indexOf("Missing data") != -1))
                    colors[society.society.id] = 'hsl(0, 0%, 100%)';
                else if (society.bf_cont_var) {
                    var color = mapColorMonochrome(results.code_ids[society.variable_coded_values[j].variable].min, results.code_ids[society.variable_coded_values[j].variable].max, society.variable_coded_values[j].coded_value, 0);
                    colors[society.society.id] = color;
                } else {
                    var color = mapColor(society.variable_coded_values[j].coded_value, results.code_ids[society.variable_coded_values[j].variable].length);
                    colors[society.society.id] = color;
                }
            }

            if (society.language_family) {
                var color = mapColor(society.language_family, society.num_classifications);
                colors[society.society.id] = color;
            }
        }
        return colors;
    };
}
<|endoftext|>


<commit_before>jQuery('#addListeningText').focus();

jQuery("#addListeningSubmit").click(function() {
  jQuery.ajax({
    type:'POST',
    url:'/api/listening/add',
    data: {
      text:jQuery('#addListeningText').val(),
      date:jQuery('#addListeningDate').val(),
      format:jQuery('input[name="addListeningFormat"]:checked').val(),
      submitType:jQuery('input[name="submitType"]').val(),
    },
    success: function(data) {
      if (data == '') {
        jQuery('#addListeningText').val('');
        jQuery('input[name="addListeningFormat"]').prop('checked', false);
        jQuery('img.listeningFormat').removeClass('selected');
        recentlyListened();
        topAlbum();
        topArtist();
      }
      jQuery('#addListeningText').focus();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
  return false;
});

jQuery(function() {
  jQuery('#addListeningText').autocomplete({
    serviceUrl: '/autoComplete/addListening',
    minChars:3,
    maxHeight:312,
    onSelect: function(value, data) {
      jQuery('#addListeningText').value = data;
    },
    observableElement: { },
    images:true,
    list:true
  });
});

jQuery(".listeningFormat").click(function() {
  jQuery(".listeningFormat").removeClass('selected');
  jQuery(this).addClass('selected');
});
jQuery(".listeningFormat").keypress(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
   if (code == 13) {
      jQuery(".listeningFormat").removeClass('selected');
      jQuery(this).addClass('selected');

      jQuery('#' + jQuery(this).parent().attr("for")).prop('checked', true);
   }
});

jQuery("#addListeningShowmore").click(function() {
  jQuery(".listeningFormat").removeClass('hidden');
  jQuery(this).remove();
});

jQuery("#addListeningShowmore").keypress(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) {
    jQuery(".listeningFormat").removeClass('hidden');
    jQuery(this).remove();
  }
});

jQuery("#recentlyListened").hover(function () {
  var currentTime = new Date();
  if((currentTime.getTime() - jQuery("#recentlyUpdated").attr('value') > (60 * 2 * 1000))) {
    recentlyListened();
  }
});

function recentlyListened(isFirst) {
  if (isFirst != true) {
    jQuery('#recentlyListenedLoader2').show();
  }
  jQuery.ajax({
    type:'POST',
    url:'/api/listening/get',
    data: {
      limit:11,
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/chartTable',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#recentlyListenedLoader2').hide();
          jQuery('#recentlyListenedLoader').hide();
          jQuery('#recentlyListened').html(data);

          var currentTime = new Date();
          var hours = currentTime.getHours();
          var minutes = currentTime.getMinutes();
          if (minutes < 10) {
            minutes = "0" + minutes;
          }
          jQuery('#recentlyUpdated').html('updated '+ hours + ':' + minutes);
          jQuery('#recentlyUpdated').attr('value', currentTime.getTime());
        },
        complete: function() {
          setTimeout(recentlyListened, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recentlyListened(true);

function topAlbum() {
  jQuery.ajax({
    type:'POST',
    url:'/api/album/get',
    data: {
      limit:8,
      lower_limit:'<?=date("Y-m-d", ($interval == "overall") ? 0 : time() - ($interval * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumList/124',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#topAlbumLoader').hide();
          jQuery('#topAlbum').html(data);
        },
        complete: function() {
          setTimeout(topAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
topAlbum();

function topArtist() {
  jQuery.ajax({
    type:'POST',
    url:'/api/artist/get',
    data: {
      limit:10,
      lower_limit:'<?=date("Y-m-d", ($interval == "overall") ? 0 : time() - ($interval * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/artistBar',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#topArtistLoader').hide();
          jQuery('#topArtist').html(data);
        },
        complete: function() {
          setTimeout(topArtist, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
topArtist();

function recommentedTopAlbum() {
  jQuery.ajax({
    type:'POST',
    url: '/api/recommentedTopAlbum',
    data: {
      limit:10,
      lower_limit:'<?=date("Y-m-d", time() - (90 * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumTable',
        data: {
          json_data:data,
          limit:2,
          hide: {
            artist:true,
            count:true,
            rank:true,
            date:true,
            calendar:true
          }
        },
        success: function(data) {
          jQuery('#recommentedTopAlbumLoader').hide();
          jQuery('#recommentedTopAlbum').html(data);
        },
        complete: function() {
          setTimeout(recommentedTopAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recommentedTopAlbum();

function recommentedNewAlbum() {
  jQuery.ajax({
    type:'POST',
    url:'/api/recommentedNewAlbum',
    data: {
      limit:10,
      order_by:'album.year DESC, album.created DESC',
      lower_limit:'<?=date("Y-m-d", time() - (365 * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      console.log(data);
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumTable',
        data: {
          json_data:data,
          limit:2,
          hide: {
            artist:true,
            count:true,
            rank:true,
            date:true,
            calendar:true
          }
        },
        success: function(data) {
          jQuery('#recommentedNewAlbumLoader').hide();
          jQuery('#recommentedNewAlbum').html(data);
        },
        complete: function() {
          setTimeout(recommentedNewAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recommentedNewAlbum();<commit_msg>Added a JavaScript trim functionality for add listening parameter.<commit_after>jQuery('#addListeningText').focus();

jQuery("#addListeningSubmit").click(function() {
  jQuery.ajax({
    type:'POST',
    url:'/api/listening/add',
    data: {
      text:jQuery('#addListeningText').val(),
      date:jQuery('#addListeningDate').val(),
      format:jQuery('input[name="addListeningFormat"]:checked').val(),
      submitType:jQuery('input[name="submitType"]').val(),
    },
    success: function(data) {
      if (jQuery.trim(data) == '') {
        jQuery('#addListeningText').val('');
        jQuery('input[name="addListeningFormat"]').prop('checked', false);
        jQuery('img.listeningFormat').removeClass('selected');
        recentlyListened();
        topAlbum();
        topArtist();
      }
      jQuery('#addListeningText').focus();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
  return false;
});

jQuery(function() {
  jQuery('#addListeningText').autocomplete({
    serviceUrl: '/autoComplete/addListening',
    minChars:3,
    maxHeight:312,
    onSelect: function(value, data) {
      jQuery('#addListeningText').value = data;
    },
    observableElement: { },
    images:true,
    list:true
  });
});

jQuery(".listeningFormat").click(function() {
  jQuery(".listeningFormat").removeClass('selected');
  jQuery(this).addClass('selected');
});
jQuery(".listeningFormat").keypress(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
   if (code == 13) {
      jQuery(".listeningFormat").removeClass('selected');
      jQuery(this).addClass('selected');

      jQuery('#' + jQuery(this).parent().attr("for")).prop('checked', true);
   }
});

jQuery("#addListeningShowmore").click(function() {
  jQuery(".listeningFormat").removeClass('hidden');
  jQuery(this).remove();
});

jQuery("#addListeningShowmore").keypress(function(e) {
  var code = (e.keyCode ? e.keyCode : e.which);
  if (code == 13) {
    jQuery(".listeningFormat").removeClass('hidden');
    jQuery(this).remove();
  }
});

jQuery("#recentlyListened").hover(function () {
  var currentTime = new Date();
  if((currentTime.getTime() - jQuery("#recentlyUpdated").attr('value') > (60 * 2 * 1000))) {
    recentlyListened();
  }
});

function recentlyListened(isFirst) {
  if (isFirst != true) {
    jQuery('#recentlyListenedLoader2').show();
  }
  jQuery.ajax({
    type:'POST',
    url:'/api/listening/get',
    data: {
      limit:11,
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/chartTable',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#recentlyListenedLoader2').hide();
          jQuery('#recentlyListenedLoader').hide();
          jQuery('#recentlyListened').html(data);

          var currentTime = new Date();
          var hours = currentTime.getHours();
          var minutes = currentTime.getMinutes();
          if (minutes < 10) {
            minutes = "0" + minutes;
          }
          jQuery('#recentlyUpdated').html('updated '+ hours + ':' + minutes);
          jQuery('#recentlyUpdated').attr('value', currentTime.getTime());
        },
        complete: function() {
          setTimeout(recentlyListened, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recentlyListened(true);

function topAlbum() {
  jQuery.ajax({
    type:'POST',
    url:'/api/album/get',
    data: {
      limit:8,
      lower_limit:'<?=date("Y-m-d", ($interval == "overall") ? 0 : time() - ($interval * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumList/124',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#topAlbumLoader').hide();
          jQuery('#topAlbum').html(data);
        },
        complete: function() {
          setTimeout(topAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
topAlbum();

function topArtist() {
  jQuery.ajax({
    type:'POST',
    url:'/api/artist/get',
    data: {
      limit:10,
      lower_limit:'<?=date("Y-m-d", ($interval == "overall") ? 0 : time() - ($interval * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/artistBar',
        data: {
          json_data:data,
        },
        success: function(data) {
          jQuery('#topArtistLoader').hide();
          jQuery('#topArtist').html(data);
        },
        complete: function() {
          setTimeout(topArtist, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
topArtist();

function recommentedTopAlbum() {
  jQuery.ajax({
    type:'POST',
    url: '/api/recommentedTopAlbum',
    data: {
      limit:10,
      lower_limit:'<?=date("Y-m-d", time() - (90 * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumTable',
        data: {
          json_data:data,
          limit:2,
          hide: {
            artist:true,
            count:true,
            rank:true,
            date:true,
            calendar:true
          }
        },
        success: function(data) {
          jQuery('#recommentedTopAlbumLoader').hide();
          jQuery('#recommentedTopAlbum').html(data);
        },
        complete: function() {
          setTimeout(recommentedTopAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recommentedTopAlbum();

function recommentedNewAlbum() {
  jQuery.ajax({
    type:'POST',
    url:'/api/recommentedNewAlbum',
    data: {
      limit:10,
      order_by:'album.year DESC, album.created DESC',
      lower_limit:'<?=date("Y-m-d", time() - (365 * 24 * 60 * 60))?>',
      username:'<?php echo !empty($_GET['u']) ? $_GET['u'] : ''?>'
    },
    success: function(data) {
      jQuery.ajax({
        type:'POST',
        url:'/ajax/albumTable',
        data: {
          json_data:data,
          limit:2,
          hide: {
            artist:true,
            count:true,
            rank:true,
            date:true,
            calendar:true
          }
        },
        success: function(data) {
          jQuery('#recommentedNewAlbumLoader').hide();
          jQuery('#recommentedNewAlbum').html(data);
        },
        complete: function() {
          setTimeout(recommentedNewAlbum, 60 * 10 * 1000);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        }
      });
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
    }
  });
}
recommentedNewAlbum();<|endoftext|>


<commit_before>const git = require('simple-git');
const firebase = require('firebase')
const config = require('./config')

// const path = __dirname + '/iotos';
// git(path).then etc..

firebase.initializeApp(config);

var ref = firebase.database().ref().child("servers")

ref.child(config.device).on('value', deploy)

// ref.child(config.device).on('value', function (data) {
// 	//console.log(data.val())
// 	deploy();
// })

function deploy (data) {
  console.log('Starting Deploying aplication ...');
	git()
	.then(function() {
		console.log('Starting pull ... ');
	})
	.pull(function(err, update) {
		if(update && update.summary.changes) {
			console.log('processing and restarting app ...');
		}
	})
	.then(function() {
		console.log('pull done. :-)');
	});
}<commit_msg>update project<commit_after>const git = require('simple-git');
const firebase = require('firebase')
const config = require('./config')

// const path = __dirname + '/iotos';
// git(path).then etc..

firebase.initializeApp(config);

var ref = firebase.database().ref().child("servers")

ref.child(config.device).on('value', deploy)

// ref.child(config.device).on('value', function (data) {
// 	//console.log(data.val())
// 	deploy();
// })

function deploy (data) {
  console.log('Starting Deploying aplication ...');
  	require('child_process').exec(`docker build -t estebanrfp/iotos:latest https://github.com/estebanrfp/iotos.git`)
	require('child_process').exec(`docker run --privileged -e DEVICE='${DEVICE}' -e APIKEY='${APIKEY}' -e AUTHDOMAIN='${AUTHDOMAIN}' -e DATABASEURL='${DATABASEURL}' estebanrfp/iotos`);
	// git()
	// .then(function() {
	// 	console.log('Starting pull ... ');
	// })
	// .pull(function(err, update) {
	// 	if(update && update.summary.changes) {
	// 		console.log('processing and restarting app ...');
	// 	}
	// })
	// .then(function() {
	// 	console.log('pull done. :-)');
	// });
}<|endoftext|>


<commit_before>gEdges.initEditing = function () {
  gEdges.editedEdge = null;

  gBehaviors.addBehavior ("edges", "dblclick",
    function () {
      return true;
    }, gEdges.editEdge);

  d3.select (".edgeChars")
    .on ("keypress", function () {
      if (d3.event.keyCode == 13) {
        gModalMenu.submit ("edgeEntry");
      }
    });
};

gEdges.populateTMEdgeModal = function (edge) {
  d3.select (".tmEdgeEntry")
    .select (".modal-header")
    .text ("Edit Transition " + edge.source.name + " " + String.fromCharCode(0x2192) + " " + edge.target.name);
  gModalMenu.tmEdge.setTmEdgeStates (gEdges.editedEdge.transitions[0]);
};

gEdges.populateEdgeModal = function (edge) {
  var chars = edge.transitions[0].join ("");
  var epsilon = chars.length > 0 && chars[chars.length - 1] == gEpsilon;
  if (epsilon) {
    chars = chars.substring (0, chars.length - 1);
  }
  gModalMenu.setEdgeChars (chars);
  gModalMenu.setEpsilon (epsilon);
};

gEdges.editEdge = function (edge) {
  gEdges.editedEdge = edge;
  if (gGraph.mode == gGraph.TM) {
    gEdges.populateTMEdgeModal (edge);
    gModalMenu.open ("tmEdgeEntry");
  } else {
    gEdges.populateEdgeModal (edge);
    gModalMenu.open ("edgeEntry");
  }
  gModalMenu.open (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  d3.event.stopPropagation ();
};

gEdges.editCancelled = function () {
  if (gEdges.tmPruneEmpty (gEdges.editedEdge.transitions[0]).length == 0) {
    gEdges.removeEdge (gEdges.editedEdge.source, gEdges.editedEdge.target);
  }
  gEdges.editedEdge = null;
  gModalMenu.close (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  gGraph.draw ();
};

gEdges.deleteEditedEdge = function () {
  gEdges.removeEdge (gEdges.editedEdge.source, gEdges.editedEdge.target);
  gEdges.editedEdge = null;
  gModalMenu.close (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  gGraph.draw ();
};

gEdges.tmPruneEmpty = function (transitions) {
  if (gGraph.mode == gGraph.TM) {
    for (var i = 0; i < transitions.length; i++) {
      if (transitions[i].to == "" && transitions[i].from == "") {
        transitions.splice (i--, 1);
        continue;
      }
    }
  }
  return transitions;
};

gEdges.tmEditComplete = function () {
  var states = gEdges.tmPruneEmpty (gModalMenu.tmEdge.getTmEdgeStates ());
  for (var i = 0; i < states.length; i++) {
    if (states[i].to == "" || states[i].from == "") {
      gErrorMenu.displayModalError ("tmEdgeEntry", "Character and Write must be non-empty");
      return;
    }
    if (intersection (states[i].to, gGraph.charSet).length != 1 ||
        intersection (states[i].from, gGraph.charSet).length != 1) {
      gErrorMenu.displayModalError ("tmEdgeEntry", "Please only use characters in the character set");
      return;
    }
  }
  if (states.length == 0) {
    gErrorMenu.displayModalError ("tmEdgeEntry", "You must define at least one transition");
    return;
  }
  for (var i = 0; i < gEdges.edges.length; i++) {
    var edge = gEdges.edges[i];
    if (edge.source.id == gEdges.editedEdge.source.id && edge.target.id != gEdges.editedEdge.target.id) {
      for (var k = 0; k < states.length; k++) {
        for (var j = 0; j < edge.transitions[0].length; j++) {
          if (states[k].from == edge.transitions[0][j].from) {
            edge.transitions[0].splice (j--, 1);
          }
        }
      }
      if (edge.transitions[0].length == 0) {
        gEdges.removeEdge (edge.source, edge.target);
      }
    }
  }
  gEdges.editedEdge.transitions[0] = states;
  gEdges.editedEdge = null;
  gModalMenu.close ("tmEdgeEntry");
  gGraph.draw ();
  gGraph.draw (); //Fixes rendering issue
};

gEdges.editComplete = function () {
  var chars = removeDuplicates (gModalMenu.getEdgeCharacters ().replace (/[\s,]/g, ""));
  var legal = intersection (gGraph.charSet, chars);
  var oldChars = chars;
  chars = legal;
  gModalMenu.setEdgeChars (legal);
  chars += (gModalMenu.getEpsilon () ? gEpsilon : "");

  if (legal.length != oldChars.length) {
    if (chars.length == 0) {
      gErrorMenu.displayModalError ("edgeEntry", "Ignoring characters that aren't in the alphabet.");
    } else {
      gErrorMenu.displayError ("Ignoring characters that aren't in the alphabet.");
    }
  }
  if (chars.length == 0) {
    gErrorMenu.displayModalError ("edgeEntry", "Transitions must take at least one character");
    return;
  }

  var transitions = chars.split ("");
  transitions.sort ();
  for (var i = 0; i < transitions.length - 1; i++) {
    if (transitions[i] == transitions[i + 1]){
      transitions.splice (i--, 1);
    }
  }
  if (gGraph.mode == gGraph.DFA) {
    var removed = false;
    transitions.forEach (function (transition) {
      for (var i = 0; i < gEdges.edges.length; i++) {
        var edge = gEdges.edges[i];
        if (edge != gEdges.editedEdge && edge.source == gEdges.editedEdge.source) {
          var index = edge.transitions[0].indexOf (transition);
          if (index != -1) {
            edge.transitions[0].splice (index, 1);
            if (edge.transitions[0].length == 0) {
              gEdges.removeEdge (edge.source, edge.target);
              i--;
              removed = true;
            }
          }
        }
      }
    });
    if (removed) {
      gErrorMenu.displayError ("Removed duplicate transitions");
    }
  }

  gEdges.editedEdge.transitions[0] = transitions;
  gEdges.editedEdge = null;
  gModalMenu.close ("edgeEntry");
  gGraph.draw ();
};
<commit_msg>Prevent duplicate definitions on single edge, fixed #162<commit_after>gEdges.initEditing = function () {
  gEdges.editedEdge = null;

  gBehaviors.addBehavior ("edges", "dblclick",
    function () {
      return true;
    }, gEdges.editEdge);

  d3.select (".edgeChars")
    .on ("keypress", function () {
      if (d3.event.keyCode == 13) {
        gModalMenu.submit ("edgeEntry");
      }
    });
};

gEdges.populateTMEdgeModal = function (edge) {
  d3.select (".tmEdgeEntry")
    .select (".modal-header")
    .text ("Edit Transition " + edge.source.name + " " + String.fromCharCode(0x2192) + " " + edge.target.name);
  var states = JSON.parse (JSON.stringify (gEdges.editedEdge.transitions[0]));
  for (var i = 0; i < states.length; i++) {
    if (states[i].from == " ") {
      states[i].from = "";
    }
    if (states[i].to == " ") {
      states[i].to = "";
    }
  }
  gModalMenu.tmEdge.setTmEdgeStates (states);
};

gEdges.populateEdgeModal = function (edge) {
  var chars = edge.transitions[0].join ("");
  var epsilon = chars.length > 0 && chars[chars.length - 1] == gEpsilon;
  if (epsilon) {
    chars = chars.substring (0, chars.length - 1);
  }
  gModalMenu.setEdgeChars (chars);
  gModalMenu.setEpsilon (epsilon);
};

gEdges.editEdge = function (edge) {
  gEdges.editedEdge = edge;
  if (gGraph.mode == gGraph.TM) {
    gEdges.populateTMEdgeModal (edge);
    gModalMenu.open ("tmEdgeEntry");
  } else {
    gEdges.populateEdgeModal (edge);
    gModalMenu.open ("edgeEntry");
  }
  gModalMenu.open (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  d3.event.stopPropagation ();
};

gEdges.editCancelled = function () {
  if (gEdges.editedEdge.transitions[0].length == 0) {
    gEdges.removeEdge (gEdges.editedEdge.source, gEdges.editedEdge.target);
  }
  gEdges.editedEdge = null;
  gModalMenu.close (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  gGraph.draw ();
};

gEdges.deleteEditedEdge = function () {
  gEdges.removeEdge (gEdges.editedEdge.source, gEdges.editedEdge.target);
  gEdges.editedEdge = null;
  gModalMenu.close (gGraph.mode == gGraph.TM ? "tmEdgeEntry" : "edgeEntry");
  gGraph.draw ();
};

gEdges.tmEditComplete = function () {
  var states = gModalMenu.tmEdge.getTmEdgeStates ();
  var charsUsed = "";
  var emptyUsed = false;
  for (var i = 0; i < states.length; i++) {
    if (states[i].to == "") {
      states[i].to = " ";
    }
    if (states[i].from == "") {
      states[i].from = " ";
      if (emptyUsed) {
        gErrorMenu.displayModalError ("tmEdgeEntry", "Only one transition can be defined for blank");
        return;
      } else {
        emptyUsed = true;
      }
    } else if (charsUsed.indexOf (states[i].from) != -1) {
      gErrorMenu.displayModalError ("tmEdgeEntry", "Only one transition can be defined for character " + states[i].from);
      return;
    }
    charsUsed += states[i].from;
    if (intersection (states[i].to, gGraph.charSet).length != 1 ||
        intersection (states[i].from, gGraph.charSet).length != 1) {
      gErrorMenu.displayModalError ("tmEdgeEntry", "Please only use characters in the character set");
      return;
    }
  }
  if (states.length == 0) {
    gErrorMenu.displayModalError ("tmEdgeEntry", "You must define at least one transition");
    return;
  }
  for (var i = 0; i < gEdges.edges.length; i++) {
    var edge = gEdges.edges[i];
    if (edge.source.id == gEdges.editedEdge.source.id && edge.target.id != gEdges.editedEdge.target.id) {
      for (var k = 0; k < states.length; k++) {
        for (var j = 0; j < edge.transitions[0].length; j++) {
          if (states[k].from == edge.transitions[0][j].from) {
            edge.transitions[0].splice (j--, 1);
          }
        }
      }
      if (edge.transitions[0].length == 0) {
        gEdges.removeEdge (edge.source, edge.target);
      }
    }
  }
  gEdges.editedEdge.transitions[0] = states;
  gEdges.editedEdge = null;
  gModalMenu.close ("tmEdgeEntry");
  gGraph.draw ();
  gGraph.draw (); //Fixes rendering issue
};

gEdges.editComplete = function () {
  var chars = removeDuplicates (gModalMenu.getEdgeCharacters ().replace (/[\s,]/g, ""));
  var legal = intersection (gGraph.charSet, chars);
  var oldChars = chars;
  chars = legal;
  gModalMenu.setEdgeChars (legal);
  chars += (gModalMenu.getEpsilon () ? gEpsilon : "");

  if (legal.length != oldChars.length) {
    if (chars.length == 0) {
      gErrorMenu.displayModalError ("edgeEntry", "Ignoring characters that aren't in the alphabet.");
    } else {
      gErrorMenu.displayError ("Ignoring characters that aren't in the alphabet.");
    }
  }
  if (chars.length == 0) {
    gErrorMenu.displayModalError ("edgeEntry", "Transitions must take at least one character");
    return;
  }

  var transitions = chars.split ("");
  transitions.sort ();
  for (var i = 0; i < transitions.length - 1; i++) {
    if (transitions[i] == transitions[i + 1]){
      transitions.splice (i--, 1);
    }
  }
  if (gGraph.mode == gGraph.DFA) {
    var removed = false;
    transitions.forEach (function (transition) {
      for (var i = 0; i < gEdges.edges.length; i++) {
        var edge = gEdges.edges[i];
        if (edge != gEdges.editedEdge && edge.source == gEdges.editedEdge.source) {
          var index = edge.transitions[0].indexOf (transition);
          if (index != -1) {
            edge.transitions[0].splice (index, 1);
            if (edge.transitions[0].length == 0) {
              gEdges.removeEdge (edge.source, edge.target);
              i--;
              removed = true;
            }
          }
        }
      }
    });
    if (removed) {
      gErrorMenu.displayError ("Removed duplicate transitions");
    }
  }

  gEdges.editedEdge.transitions[0] = transitions;
  gEdges.editedEdge = null;
  gModalMenu.close ("edgeEntry");
  gGraph.draw ();
};
<|endoftext|>


<commit_before><commit_msg>updating dist<commit_after><|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var props = require('props');
var dive = require('dive');
var ejs = require('ejs');
var async = require('async');
var clone = require('clone');
var append = require('append');

// Main function
var bake = function(conf, hooks, cb) {

  // File counter
  var todo = 0;

  if (typeof conf != 'object')
    return cb(new Error('parameter conf must be a valid configuration object'));

  // Set values for `inputDir`, `outputDir` and `tplDir`
  var root = conf.root || process.cwd();
  var inputDir = conf.directories.input || 'pub';
  var outputDir = conf.directories.output || 'pub';
  var tplDir = conf.directories.templates || 'tpl';

  inputDir = path.resolve(root, inputDir);
  outputDir = path.resolve(root, outputDir);
  tplDir = path.resolve(root, tplDir);

  // Set values for `fileExt`
  var fileExt = conf.fileExtensions || { txt: 'html' };
  var fileExtPattern
      = new RegExp('\.(' + Object.keys(fileExt).join('|') + ')$', 'i');

  // Status log
  console.log('Beginning to bake ' + inputDir + '.');

  // Dive into the public directory
  dive(inputDir, function(err, master) {
    // Throw errors
    if (err)
      return cb(err);

    // Matching variable
    var match;

    // Match the master-file's name against enabled file extensions
    if (match = master.match(fileExtPattern)) {

      // Get the file extension of the master file
      var masterExt = match[1];

      // Increase file counter
      ++todo;

      // Read the master-file's contents
      fs.readFile(master, 'utf8', function(err, data) {
        // Throw errors
        if (err)
          return cb(err);

        // Get the properties
        // `prop` is the file specific property object
        var prop = props(data);

        // Amend `prop` by properties in `conf.properties` if defined
        if (conf.properties)
          prop = append(clone(conf.properties), prop);

        // Assert that `prop.template` is set
        if (typeof prop.template == 'undefined')
          prop.template = 'default.tpl';

        // `__propBefore` hook
        if (hooks.__propBefore)
          hooks.__propBefore(master, prop, propBeforeCB);
        else
          propBeforeCB(null, prop);

        function propBeforeCB(err, prop) {
          if (err)
            return cb(err);

          // tasks for async
          var tasks = {};

          // Various property hooks
          for (var key in prop) {(function (prop, key) {
            if (hooks[key])
              tasks[key] = function (callback) {
                return hooks[key](master, prop, callback);
              };
            else
              tasks[key] = function (callback) {
                return callback(null, prop[key]);
              };
          })(prop, key);}

          // run tasks in parallel
          async.parallel(tasks, function (err, prop) {
            if (err)
              return cb(err);

            // `__propAfter` hook
            if (hooks.__propAfter)
              hooks.__propAfter(master, prop, propAfterCB);
            else
              propAfterCB(null, prop);

            function propAfterCB(err, prop) {
              if (err)
                return cb(err);

              // Read the template file
              fs.readFile(path.resolve(tplDir, prop.template), 'utf8',
                  function(err, result) {
                // Throw errors
                if (err)
                  return cb(err);

                // (Pre-)Insert the content (so ejs-tags in
                // `prop.__content` are parsed, too.
                result = result.replace(/<%=\s+__content\s+%>/g,
                    prop.__content);

                // Result's filename
                var resName = master.replace(fileExtPattern,
                    '.' + fileExt[masterExt]);

                // New file's path
                if (typeof prop._id == 'undefined') {
                  prop._id = resName.replace(inputDir, '');
                  prop._id = prop._id.replace(/\/, '/');
                }

                // Remove first slash
                if (/^\//, prop._id)
                  prop._id = prop._id.substring(1);

                // Add output dir
                resName = path.resolve(outputDir, prop._id);

                // Render ejs-template
                result = ejs.render(result, { locals: prop });

                // Write contents
                fs.writeFile(resName, result, function(err) {
                  // Throw errors
                  if (err)
                    return cb(err);

                  // `__written` hook
                  if (hooks.__writeAfter)
                    hooks.__writeAfter(master, prop, writeAfterCB);
                  else
                    writeAfterCB(null);

                  function writeAfterCB(err) {
                    if (err)
                      return cb(err);

                    // Log status on success
                    console.log('  * ' + resName + ' written.');

                    // When file counter is zero
                    if (!--todo) {
                      // `__complete` hook
                      if (hooks.__complete)
                        hooks.__complete(master, prop, cb);
                      else
                        return cb(null);
                    }
                  }
                });
              });
            }
          });
        }
      });
    }
  });
};

module.exports = bake;
<commit_msg>Fix first slash bug<commit_after>var fs = require('fs');
var path = require('path');
var props = require('props');
var dive = require('dive');
var ejs = require('ejs');
var async = require('async');
var clone = require('clone');
var append = require('append');

// Main function
var bake = function(conf, hooks, cb) {

  // File counter
  var todo = 0;

  if (typeof conf != 'object')
    return cb(new Error('parameter conf must be a valid configuration object'));

  // Set values for `inputDir`, `outputDir` and `tplDir`
  var root = conf.root || process.cwd();
  var inputDir = conf.directories.input || 'pub';
  var outputDir = conf.directories.output || 'pub';
  var tplDir = conf.directories.templates || 'tpl';

  inputDir = path.resolve(root, inputDir);
  outputDir = path.resolve(root, outputDir);
  tplDir = path.resolve(root, tplDir);

  // Set values for `fileExt`
  var fileExt = conf.fileExtensions || { txt: 'html' };
  var fileExtPattern
      = new RegExp('\.(' + Object.keys(fileExt).join('|') + ')$', 'i');

  // Status log
  console.log('Beginning to bake ' + inputDir + '.');

  // Dive into the public directory
  dive(inputDir, function(err, master) {
    // Throw errors
    if (err)
      return cb(err);

    // Matching variable
    var match;

    // Match the master-file's name against enabled file extensions
    if (match = master.match(fileExtPattern)) {

      // Get the file extension of the master file
      var masterExt = match[1];

      // Increase file counter
      ++todo;

      // Read the master-file's contents
      fs.readFile(master, 'utf8', function(err, data) {
        // Throw errors
        if (err)
          return cb(err);

        // Get the properties
        // `prop` is the file specific property object
        var prop = props(data);

        // Amend `prop` by properties in `conf.properties` if defined
        if (conf.properties)
          prop = append(clone(conf.properties), prop);

        // Assert that `prop.template` is set
        if (typeof prop.template == 'undefined')
          prop.template = 'default.tpl';

        // `__propBefore` hook
        if (hooks.__propBefore)
          hooks.__propBefore(master, prop, propBeforeCB);
        else
          propBeforeCB(null, prop);

        function propBeforeCB(err, prop) {
          if (err)
            return cb(err);

          // tasks for async
          var tasks = {};

          // Various property hooks
          for (var key in prop) {(function (prop, key) {
            if (hooks[key])
              tasks[key] = function (callback) {
                return hooks[key](master, prop, callback);
              };
            else
              tasks[key] = function (callback) {
                return callback(null, prop[key]);
              };
          })(prop, key);}

          // run tasks in parallel
          async.parallel(tasks, function (err, prop) {
            if (err)
              return cb(err);

            // `__propAfter` hook
            if (hooks.__propAfter)
              hooks.__propAfter(master, prop, propAfterCB);
            else
              propAfterCB(null, prop);

            function propAfterCB(err, prop) {
              if (err)
                return cb(err);

              // Read the template file
              fs.readFile(path.resolve(tplDir, prop.template), 'utf8',
                  function(err, result) {
                // Throw errors
                if (err)
                  return cb(err);

                // (Pre-)Insert the content (so ejs-tags in
                // `prop.__content` are parsed, too.
                result = result.replace(/<%=\s+__content\s+%>/g,
                    prop.__content);

                // Result's filename
                var resName = master.replace(fileExtPattern,
                    '.' + fileExt[masterExt]);

                // New file's path
                if (typeof prop._id == 'undefined') {
                  prop._id = resName.replace(inputDir, '');
                  prop._id = prop._id.replace(/\/, '/');
                }

                // Add output dir
                resName = path.resolve(outputDir, prop._id);

                // Render ejs-template
                result = ejs.render(result, { locals: prop });

                // Remove first slash
                if (/^\//, prop._id)
                  prop._id = prop._id.substring(1)

                // Write contents
                fs.writeFile(resName, result, function(err) {
                  // Throw errors
                  if (err)
                    return cb(err);

                  // `__written` hook
                  if (hooks.__writeAfter)
                    hooks.__writeAfter(master, prop, writeAfterCB);
                  else
                    writeAfterCB(null);

                  function writeAfterCB(err) {
                    if (err)
                      return cb(err);

                    // Log status on success
                    console.log('  * ' + resName + ' written.');

                    // When file counter is zero
                    if (!--todo) {
                      // `__complete` hook
                      if (hooks.__complete)
                        hooks.__complete(master, prop, cb);
                      else
                        return cb(null);
                    }
                  }
                });
              });
            }
          });
        }
      });
    }
  });
};

module.exports = bake;
<|endoftext|>


<commit_before>'use strict';

var queue = require('queue-async');

function LayerMetadata(layerMetadataIterator) {
    this.layerMetadataIterator = layerMetadataIterator;
}

LayerMetadata.prototype.getMetadata = function (rendererCache, params, mapConfig, callback) {
    var self = this;
    var metadata = [];

    var metaQueue = queue(mapConfig.getLayers().length);

    mapConfig.getLayers().forEach(function(layer, layerId) {
        var layerType = mapConfig.layerType(layerId);

        for (var i = 0; i < self.layerMetadataIterator.length; i++) {
            if (self.layerMetadataIterator[i].is(layerType)) {
                var getMetadata = self.layerMetadataIterator[i].getMetadata.bind(self.layerMetadataIterator[i]);
                metaQueue.defer(getMetadata, mapConfig, layer, layerId, params, rendererCache);
                break;
            }
        }
    });

    metaQueue.awaitAll(function (err, results) {
        if (err) {
            return callback(err);
        }

        if (!results) {
            return callback(null, null);
        }

        mapConfig.getLayers().forEach(function(layer, layerIndex) {
            var layerType = mapConfig.layerType(layerIndex);

            metadata[layerIndex] = {
                type: layerType,
                id: mapConfig.getLayerId(layerIndex),
                meta: results[layerIndex]
            };

            if (layer.options.cartocss) {
                metadata[layerIndex].meta.cartocss = layer.options.cartocss;
            }
        });

        return callback(err, metadata);
    });

};

module.exports = LayerMetadata;
<commit_msg>Avoid TypeError: Cannot set property 'cartocss' of undefined<commit_after>'use strict';

var queue = require('queue-async');

function LayerMetadata(layerMetadataIterator) {
    this.layerMetadataIterator = layerMetadataIterator;
}

LayerMetadata.prototype.getMetadata = function (rendererCache, params, mapConfig, callback) {
    var self = this;
    var metadata = [];

    var metaQueue = queue(mapConfig.getLayers().length);

    mapConfig.getLayers().forEach(function(layer, layerId) {
        var layerType = mapConfig.layerType(layerId);

        for (var i = 0; i < self.layerMetadataIterator.length; i++) {
            if (self.layerMetadataIterator[i].is(layerType)) {
                var getMetadata = self.layerMetadataIterator[i].getMetadata.bind(self.layerMetadataIterator[i]);
                metaQueue.defer(getMetadata, mapConfig, layer, layerId, params, rendererCache);
                break;
            }
        }
    });

    metaQueue.awaitAll(function (err, results) {
        if (err) {
            return callback(err);
        }

        if (!results) {
            return callback(null, null);
        }

        mapConfig.getLayers().forEach(function(layer, layerIndex) {
            var layerType = mapConfig.layerType(layerIndex);

            metadata[layerIndex] = {
                type: layerType,
                id: mapConfig.getLayerId(layerIndex),
                meta: results[layerIndex]
            };

            if (layer.options.cartocss && metadata[layerIndex].meta) {
                metadata[layerIndex].meta.cartocss = layer.options.cartocss;
            }
        });

        return callback(err, metadata);
    });

};

module.exports = LayerMetadata;
<|endoftext|>


<commit_before>(function() {
    "use strict";

    var website = openerp.website;
    var _t = openerp._t;
    website.is_editable = true;
    website.is_editable_button = true;

    website.EditorBar.include({
        start: function() {
            var res = this._super();
            this.$("a[data-action=new_page]").parents("li").removeClass("hidden");
            this.$(".oe_content_menu li.divider").removeClass("hidden");
            return res;
        },
        events: _.extend({}, website.EditorBar.prototype.events, {
            'click a[data-action=new_page]': function (ev) {
                ev.preventDefault();
                website.prompt({
                    id: "editor_new_page",
                    window_title: _t("New Page"),
                    input: _t("Page Title"),
                    init: function () {
                        var $group = this.$dialog.find("div.form-group");
                        $group.removeClass("mb0");

                        var $add = $(
                            '
'+
                                ''+
                                '    <input type="checkbox" checked="checked" required="required"/> '+
                                ''+
                            '
');
                        $add.find('label').append(_t("Add page in menu"));
                        $group.after($add);
                    }
                }).then(function (val, field, $dialog) {
                    if (val) {
                        console.log('/website/add/' + encodeURI(val) + "?add_menu=" + $dialog.find('input[type="checkbox"]').is(':checked'));
                        document.location = '/website/add/' + encodeURI(val) + "?add_menu=" + $dialog.find('input[type="checkbox"]').is(':checked');
                    }
                });
            }
        }),
    });
})();<commit_msg>[FIX] website: Page is added to menu even if the checkbox is unchecked at adding time<commit_after>(function() {
    "use strict";

    var website = openerp.website;
    var _t = openerp._t;
    website.is_editable = true;
    website.is_editable_button = true;

    website.EditorBar.include({
        start: function() {
            var res = this._super();
            this.$("a[data-action=new_page]").parents("li").removeClass("hidden");
            this.$(".oe_content_menu li.divider").removeClass("hidden");
            return res;
        },
        events: _.extend({}, website.EditorBar.prototype.events, {
            'click a[data-action=new_page]': function (ev) {
                ev.preventDefault();
                website.prompt({
                    id: "editor_new_page",
                    window_title: _t("New Page"),
                    input: _t("Page Title"),
                    init: function () {
                        var $group = this.$dialog.find("div.form-group");
                        $group.removeClass("mb0");

                        var $add = $(
                            '
'+
                                ''+
                                '    <input type="checkbox" checked="checked" required="required"/> '+
                                ''+
                            '
');
                        $add.find('label').append(_t("Add page in menu"));
                        $group.after($add);
                    }
                }).then(function (val, field, $dialog) {
                    if (val) {
                        var url = '/website/add/' + encodeURI(val);
                        if ($dialog.find('input[type="checkbox"]').is(':checked')) url +="?add_menu=1";
                        document.location = url;
                    }
                });
            }
        }),
    });
})();<|endoftext|>


<commit_before>function ColorMapService() {
    //an array of colors for coded values
    this.colorMap = [
        'NaN',
        'rgb(228,26,28)',
        'rgb(69,117,180)',
        'rgb(77,146,33)',
        'rgb(152,78,163)',
        'rgb(255,127,0)',
        'rgb(255,255,51)',
        'rgb(166,86,40)',
        'rgb(247,129,191)',
        'rgb(153,153,153)',
        'rgb(0,68,27)',
        'rgb(171,217,233)',
        'rgb(73,0,106)',
        'rgb(174,1,126)',
        'rgb(179,222,105)',
        'rgb(8,48,107)',
        'rgb(255,255,153)',
        'rgb(82,82,82)',
        'rgb(0,0,0)',
        'rgb(103,1,13)'
    ];
    // converts hsl to rgb
    function hslToRgb(h, s, l) {
        if (h < 0) h += 360;
        if (h >= 360) h = h % 360;
        var r, g, b;
        var r1, g1, b1;
        chroma = (1 - Math.abs(2*l - 1)) * s;

        _h = h / 60;

        x = chroma*(1 - Math.abs(_h % 2 - 1));

        if (_h >= 0 && _h < 1) {
            r1 = chroma;
            g1 = x;
            b1 = 0;
        } else if (_h >= 1 && _h < 2) {
            r1 = x;
            g1 = chroma;
            b1 = 0;
        } else if (_h >= 2 && _h < 3) {
            r1 = 0;
            g1 = chroma;
            b1 = x;
        } else if (_h >= 3 && _h < 4) {
            r1 = 0;
            g1 = x;
            b1 = chroma;
        } else if (_h >= 4 && _h < 5) {
            r1 = x;
            g1 = 0;
            b1 = chroma;
        } else if (_h >= 5 && _h < 6) {
            r1 = chroma;
            g1 = 0;
            b1 = x;
        } else if (!h) {
            r1 = 0; g1 = 0; b1 = 0;
        }
        m = l - (0.5 * chroma);
        rgb = [Math.round((r1 + m)*255), Math.round((g1 + m)*255), Math.round((b1 + m)*255)];
        return rgb;
    }

    //blue to red gradient for environmental variables
    this.tempColor = function(index, min, max, name) {
    if (name == "Net Primary Production" || name == "Mean Growing Season NPP") {
        hue = 30 + (((index - min) / (max - min)) * 88);
    } else if (name == "Annual Mean Precipitation"){
        color = this.mapColorMonochrome(min, max, index, 252);
        return color;
    }
    else {
        hue = 240 - (((index - min) / (max - min))*240);
    }
        rgb = hslToRgb(hue, 1, 0.5);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    //normal gradient
    this.mapColor = function(index, count) {
        hue = (index / count)*240;
        rgb = hslToRgb(hue, 1, 0.5);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.mapColorMonochrome = function(min, max, value, color) {
        var lum = (((value-min)/(max-min))) * 78; lum = 100 - lum;
        rgb = hslToRgb(color, 0.65, lum/100);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.generateRandomHue = function(value, codes, index, count) {
        hue = (index / count) * 300;
        lum = 85 - ((value / codes) * 90)
        rgb = hslToRgb(hue, 0.65, lum/100);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.generateColorMap = function(results) {
        var colors = {};
        for (var i = 0; i < results.societies.length; i++) {
            var society = results.societies[i];

            if (society.geographic_regions) {
                for (var j = 0; j < society.geographic_regions.length; j++) {
                    var color = this.mapColor(society.geographic_regions[j].tdwg_code, results.geographic_regions.length);
                    colors[society.society.id] = color;
                }
            }

            if (results.languages.length > 0 && society.environmental_values.length == 0 && society.variable_coded_values.length == 0) {
                    var color = this.mapColor(society.society.language.family.id, results.classifications.length);
                    colors[society.society.id] = color;

            }

            for (var j = 0; j < society.environmental_values.length; j++) {
                variable = results.environmental_variables.filter(function(env_var) {
                    return env_var.id == society.environmental_values[j].variable;
                });
                if (variable.length > 0) {
                    var color = this.tempColor(society.environmental_values[j].value,  variable[0].min, variable[0].max, variable[0].name);
                    colors[society.society.id] = color;
                }
            }

            for (var j = 0; j < society.variable_coded_values.length; j++) {
                variable_description = results.variable_descriptions.filter(function(variable) {
                    return variable.variable.id == society.variable_coded_values[j].variable;
                });

                if (variable_description[0].variable.data_type.toUpperCase() == 'ORDINAL') {
                    // there are 5 ordinal variables in the database
                    var color = this.generateRandomHue(society.variable_coded_values[j].coded_value, variable_description[0].codes.length, variable_description[0].variable.id, 5);
                    colors[society.society.id] = color;
                } else if (variable_description[0].variable.data_type.toUpperCase() == 'CONTINUOUS') {
                    var color = this.mapColorMonochrome(variable_description[0].variable.min, variable_description[0].variable.max, society.variable_coded_values[j].coded_value, 0);
                    colors[society.society.id] = color;
                } else {
                    if (society.variable_coded_values[j].coded_value == 'NA') {
                        colors[society.society.id] = 'rgb(255,255,255)';
                    } else {
                        if (variable_description[0].variable.label == "EA094") { //this variable's codes range from 11-99, for some reason
                            for (var k = 0; k < variable_description[0].codes.length; k++) {
                                if (variable_description[0].codes[k].code == society.variable_coded_values[j].coded_value) {
                                    colors[society.society.id] = this.colorMap[k+1];
                                    break;
                                }
                            }
                        } else
                            colors[society.society.id] = this.colorMap[parseInt(society.variable_coded_values[j].coded_value)];
                    }
                }
            }

        }
        return colors;
    };
}
<commit_msg>Changing Annual to Monthly for precipitation<commit_after>function ColorMapService() {
    //an array of colors for coded values
    this.colorMap = [
        'NaN',
        'rgb(228,26,28)',
        'rgb(69,117,180)',
        'rgb(77,146,33)',
        'rgb(152,78,163)',
        'rgb(255,127,0)',
        'rgb(255,255,51)',
        'rgb(166,86,40)',
        'rgb(247,129,191)',
        'rgb(153,153,153)',
        'rgb(0,68,27)',
        'rgb(171,217,233)',
        'rgb(73,0,106)',
        'rgb(174,1,126)',
        'rgb(179,222,105)',
        'rgb(8,48,107)',
        'rgb(255,255,153)',
        'rgb(82,82,82)',
        'rgb(0,0,0)',
        'rgb(103,1,13)'
    ];
    // converts hsl to rgb
    function hslToRgb(h, s, l) {
        if (h < 0) h += 360;
        if (h >= 360) h = h % 360;
        var r, g, b;
        var r1, g1, b1;
        chroma = (1 - Math.abs(2*l - 1)) * s;

        _h = h / 60;

        x = chroma*(1 - Math.abs(_h % 2 - 1));

        if (_h >= 0 && _h < 1) {
            r1 = chroma;
            g1 = x;
            b1 = 0;
        } else if (_h >= 1 && _h < 2) {
            r1 = x;
            g1 = chroma;
            b1 = 0;
        } else if (_h >= 2 && _h < 3) {
            r1 = 0;
            g1 = chroma;
            b1 = x;
        } else if (_h >= 3 && _h < 4) {
            r1 = 0;
            g1 = x;
            b1 = chroma;
        } else if (_h >= 4 && _h < 5) {
            r1 = x;
            g1 = 0;
            b1 = chroma;
        } else if (_h >= 5 && _h < 6) {
            r1 = chroma;
            g1 = 0;
            b1 = x;
        } else if (!h) {
            r1 = 0; g1 = 0; b1 = 0;
        }
        m = l - (0.5 * chroma);
        rgb = [Math.round((r1 + m)*255), Math.round((g1 + m)*255), Math.round((b1 + m)*255)];
        return rgb;
    }

    //blue to red gradient for environmental variables
    this.tempColor = function(index, min, max, name) {
    if (name == "Net Primary Production" || name == "Mean Growing Season NPP") {
        hue = 30 + (((index - min) / (max - min)) * 88);
    } else if (name == "Monthly Mean Precipitation"){
        color = this.mapColorMonochrome(min, max, index, 252);
        return color;
    }
    else {
        hue = 240 - (((index - min) / (max - min))*240);
    }
        rgb = hslToRgb(hue, 1, 0.5);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    //normal gradient
    this.mapColor = function(index, count) {
        hue = (index / count)*240;
        rgb = hslToRgb(hue, 1, 0.5);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.mapColorMonochrome = function(min, max, value, color) {
        var lum = (((value-min)/(max-min))) * 78; lum = 100 - lum;
        rgb = hslToRgb(color, 0.65, lum/100);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.generateRandomHue = function(value, codes, index, count) {
        hue = (index / count) * 300;
        lum = 85 - ((value / codes) * 90)
        rgb = hslToRgb(hue, 0.65, lum/100);
        return 'rgb('+rgb[0]+','+rgb[1]+','+rgb[2]+')';
    }

    this.generateColorMap = function(results) {
        var colors = {};
        for (var i = 0; i < results.societies.length; i++) {
            var society = results.societies[i];

            if (society.geographic_regions) {
                for (var j = 0; j < society.geographic_regions.length; j++) {
                    var color = this.mapColor(society.geographic_regions[j].tdwg_code, results.geographic_regions.length);
                    colors[society.society.id] = color;
                }
            }

            if (results.languages.length > 0 && society.environmental_values.length == 0 && society.variable_coded_values.length == 0) {
                    var color = this.mapColor(society.society.language.family.id, results.classifications.length);
                    colors[society.society.id] = color;

            }

            for (var j = 0; j < society.environmental_values.length; j++) {
                variable = results.environmental_variables.filter(function(env_var) {
                    return env_var.id == society.environmental_values[j].variable;
                });
                if (variable.length > 0) {
                    var color = this.tempColor(society.environmental_values[j].value,  variable[0].min, variable[0].max, variable[0].name);
                    colors[society.society.id] = color;
                }
            }

            for (var j = 0; j < society.variable_coded_values.length; j++) {
                variable_description = results.variable_descriptions.filter(function(variable) {
                    return variable.variable.id == society.variable_coded_values[j].variable;
                });

                if (variable_description[0].variable.data_type.toUpperCase() == 'ORDINAL') {
                    // there are 5 ordinal variables in the database
                    var color = this.generateRandomHue(society.variable_coded_values[j].coded_value, variable_description[0].codes.length, variable_description[0].variable.id, 5);
                    colors[society.society.id] = color;
                } else if (variable_description[0].variable.data_type.toUpperCase() == 'CONTINUOUS') {
                    var color = this.mapColorMonochrome(variable_description[0].variable.min, variable_description[0].variable.max, society.variable_coded_values[j].coded_value, 0);
                    colors[society.society.id] = color;
                } else {
                    if (society.variable_coded_values[j].coded_value == 'NA') {
                        colors[society.society.id] = 'rgb(255,255,255)';
                    } else {
                        if (variable_description[0].variable.label == "EA094") { //this variable's codes range from 11-99, for some reason
                            for (var k = 0; k < variable_description[0].codes.length; k++) {
                                if (variable_description[0].codes[k].code == society.variable_coded_values[j].coded_value) {
                                    colors[society.society.id] = this.colorMap[k+1];
                                    break;
                                }
                            }
                        } else
                            colors[society.society.id] = this.colorMap[parseInt(society.variable_coded_values[j].coded_value)];
                    }
                }
            }

        }
        return colors;
    };
}
<|endoftext|>


<commit_before>import store from './store'
import * as types from './constants'

import { showNotification, initializeApp, updateChannel, updateChannelVolume, removeMessage }
  from './actions'

export default function(eventType, data) {
  switch (eventType) {
    case 'echo':
      console.log('>>> echo >>>')
      console.log(data)
      console.log('<<<<<<<<<<<<')
      break
    case 'initialize':
      store.dispatch(initializeApp(data))
      break
    case 'channelUpdate':
      Object.keys(data).forEach(key => {
        const chan = data[key]
        if (chan) {
          store.dispatch(updateChannel(key, chan))
          if ('ring' == chan.mode) {
            new Notification(`Incoming call from ${chan.number}.`)
          }
        } else {
          //
        }
      })
      break
    case 'channelVolumeChange':
      Object.keys(data).forEach(id => {
        store.dispatch(updateChannelVolume(id, data[id]))
      })
      break
    case 'inboxUpdate':
      Object.keys(data).forEach(id => {
        const message = data[id]
        if (message) {
          //
        } else {
          store.dispatch(removeMessage(id))
        }
      })
      break
    case 'event_error':
    case 'input_error':
      console.log(`error: ${eventType}`)
      break
    default:
      console.error(`Unknown event type: ${eventType}.`)
      break
  }
}
<commit_msg>fix addMessage dispatch<commit_after>import store from './store'
import * as types from './constants'

import { showNotification, initializeApp, updateChannel, updateChannelVolume, updateAppStatus, addMessage, removeMessage }
  from './actions'

export default function(eventType, data) {
  switch (eventType) {
    case 'echo':
      console.log('>>> echo >>>')
      console.log(data)
      console.log('<<<<<<<<<<<<')
      break
    case 'initialize':
      store.dispatch(initializeApp(data))
//      store.dispatch(updateAppStatus('APP_STATUS_INITIALIZED')) // temp
      break
    case 'channelUpdate':
      Object.keys(data).forEach(key => {
        const chan = data[key]
        if (chan) {
          store.dispatch(updateChannel(key, chan))
          if ('ring' == chan.mode) {
            new Notification(`Incoming call from ${chan.number}.`)
          }
        } else {
          //
        }
      })
      break
    case 'channelVolumeChange':
      Object.keys(data).forEach(id => {
        store.dispatch(updateChannelVolume(id, data[id]))
      })
      break
    case 'inboxUpdate':
      Object.keys(data).forEach(id => {
        const message = data[id]
        if (message) {
          store.dispatch(addMessage(id, message))
        } else {
          store.dispatch(removeMessage(id))
        }
      })
      break
    case 'event_error':
    case 'input_error':
      console.log(`error: ${eventType}`)
      break
    default:
      console.error(`Unknown event type: ${eventType}.`)
      break
  }
}
<|endoftext|>


<commit_before>// evilService.js
module.exports = function EvilService(dependencies) {
    this.dependencies = dependencies;

    this.random = dependencies.random;

    var data = [
        {
            count: 0,
            friendly_url: "instalar-baidu",
            title: "instalar o BAIDU!",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/baidu.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 42,
            friendly_url: "chamar-taxi-e-uber-ao-mesmo-tempo",
            title: "chamar taxi e Uber ao mesmo tempo!",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/uber.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 87,
            friendly_url: "fazer-while-true-no-codigo",
            title: "fazer WHILE true no código",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/whiletrue.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 9,
            friendly_url: "abrir-o-ie",
            title: "abrir o IE",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/ie8.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 52,
            friendly_url: "escutar-funk-proibidao-no-spotify-no-ultimo-volume",
            title: "escutar funk proibidão no spotify no ultimo volume",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/bondetigrao.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 17,
            friendly_url: "passar-correndo-na-frente-dos-camelos-e-gritar-o-rapa",
            title: "passar correndo nos camelos e gritar OOOh Rapaaaa!",
            img: "http://oglobo.globo.com/fotos/2011/09/15/15_MHG_RIO_camelo.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 0,
            friendly_url: "passar-sorvete-no-arroz",
            title: "passar sorvete no arroz",
            img: "https://i.ytimg.com/vi/H52kepS9tO4/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 12,
            friendly_url: "engordar-para-valer",
            title: "engordar para valer",
            img: "https://i.ytimg.com/vi/H52kepS9tO4/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 2,
            friendly_url: "peidar-na-fila-do-banco-e-sair-correndo",
            title: "peidar na fila do banco e sair correndo",
            img: "http://www.polemicaparaiba.com.br/wp-content/uploads/2015/09/fila-de-banco.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 3,
            friendly_url: "ir-no-mcdonalds-e-pedir-uma-salada",
            title: "ir no McDonalds e pedir uma salada",
            img: "https://venancios.files.wordpress.com/2013/04/gordo.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 1,
            friendly_url: "fazer-um-site-de-maldade",
            title: "fazer um site de maldade",
            img: "https://i.ytimg.com/vi/oR13iPNv9wI/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "colocar-filtro-do-cachorro",
            title: "colocar o filtro do cachorro",
            img: "http://static1.purebreak.com.br/articles/1/30/98/1/@/154968-kendall-jenner-tambem-adora-usar-o-filtr-950x0-1.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "pegar-homem-pegar-mulher",
            title: "pegar homem, pegar mulher! BORAA",
            img: "https://i.ytimg.com/vi/M81ke9svVXo/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "pisar-na-grama",
            title: "pisar na grama",
            img: "http://redeemancipa.org.br/wp-content/uploads/2012/12/n%C3%A3o-pise.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "logar-no-notebook-com-capslock-ligado",
            title: "logar no notebook com o capslock ligado",
            img: "https://secure.logitech.com/assets/32508/35/k800-top.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "visualizar-e-nao-responder",
            title: "visualizar e não responder",
            img: "http://lounge.obviousmag.org/monica_montone/assets_c/2015/10/visualizar%20e%20n%C3%A3o%20responder%20(1)-thumb-800x600-125118.png",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "like-proprio-video",
            title: "dar like no próprio video",
            img: "http://www.uhull.com.br/wp-content/uploads/2008/10/017_pics-399x263.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "curtir-proprio-comentario",
            title: "curtir o proprio comentário",
            img: "http://www.uhull.com.br/wp-content/uploads/2008/10/017_pics-399x263.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "nao-respoder-amem-no-grupo-da-familia",
            title: "não responder amém no grupo da famila",
            img: "https://www.whatsapp.com/img/v2/logo-promo.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "mandar-video-de-gemido-para-avo",
            title: "mandar video de gemido para a Avó",
            img: "http://www.tribunahoje.com/vgmidia/imagens/21533_ext_arquivo.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "espalhar-que-o-whatsapp-sera-pago",
            title: "espalhar que o whatsapp será pago",
            img: "http://franquiaautomatica.com/blog/wp-content/uploads/2014/07/whatsapp-pago-whatsapp-gratis-whatsapp-vai-ser-pago.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "dar-like-em-baranga-no-tinder",
            title: "dar like em baranga no Tinter",
            img: "http://www.eonline.com/eol_images/Entire_Site/2014817/rs_560x415-140917143530-1024.Tinder-Logo.ms.091714_copy.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "mandar-indireta-para-o-vizinho-com-o-nome-da-rede-wifi",
            title: "mandar indireta para o vizinho com o nome da rede wifi",
            img: "http://img.ibxk.com.br/ns/rexposta/2015/05/14/14213459278002.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "pedir-vida-no-candycrush",
            title: "pedir vida no Candy Crush",
            img: "http://i2.wp.com/candycrushsodasagatips.com/wp-content/uploads/2014/10/candy-crush-soda-level-13-new-screenshot.png",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "alterar-fonte-notepad",
            title: "alterar o fonte no notepad",
            img: "http://www.tutorials4u.com/html/graphics/notepad/notepad-new-page.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "debug-em-producao",
            title: "fazer debug em produção",
            img: "http://i.istockimg.com/file_thumbview_approve/68886757/6/stock-photo-68886757-it-background-binary-code-a08.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "fechar-chamado-no-ultimo-dia-do-sla",
            title: "fechar o chamado no ultimo dia do SLA",
            img: "http://i.istockimg.com/file_thumbview_approve/68886757/6/stock-photo-68886757-it-background-binary-code-a08.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "fazer-style-inline",
            title: "fazer style inline",
            img: "http://img.pandawhale.com/56193-Whenever-I-try-to-open-blinds-1kSs.gif",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        }

    ];

    var newEvil = function() {
        var randomInt = random.randomInt(0,data.length);
        return data[randomInt];
    };

    var doEvil = function (friendlyUrl) {
        var evil = findByFriendlyURL(friendlyUrl);
        evil.count = evil.count+1;
    };

    var evilsDone = function () {
        return data.map(evil => evil.count ).reduce((first, second) => first + second);
    };

    var totalEvils = function () {
        return data.length;
    };

    var findByFriendlyURL = function(friendlyUrl) {
        for (var i = 0; i < data.length; i++) {
            var evil = data[i];
            if(evil.friendly_url === friendlyUrl){
                return evil;
            }
        }
        return {};
    };

    return {
        evilsDone: evilsDone,
        totalEvils: totalEvils,
        newEvil: newEvil,
        doEvil: doEvil,
        findByFriendlyURL: findByFriendlyURL
    }
};
<commit_msg>Update evilService.js<commit_after>// evilService.js
module.exports = function EvilService(dependencies) {
    this.dependencies = dependencies;

    this.random = dependencies.random;

    var data = [
        {
            count: 0,
            friendly_url: "instalar-baidu",
            title: "instalar o BAIDU!",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/baidu.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 42,
            friendly_url: "chamar-taxi-e-uber-ao-mesmo-tempo",
            title: "chamar taxi e Uber ao mesmo tempo!",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/uber.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 87,
            friendly_url: "fazer-while-true-no-codigo",
            title: "fazer WHILE true no código",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/whiletrue.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 9,
            friendly_url: "abrir-o-ie",
            title: "abrir o IE",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/ie8.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 52,
            friendly_url: "escutar-funk-proibidao-no-spotify-no-ultimo-volume",
            title: "escutar funk proibidão no spotify no ultimo volume",
            img: "https://s3.amazonaws.com/elasticbeanstalk-us-east-1-141499087849/static/bondetigrao.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 17,
            friendly_url: "passar-correndo-na-frente-dos-camelos-e-gritar-o-rapa",
            title: "passar correndo nos camelôs e gritar OOOh Rapaaaa!",
            img: "http://oglobo.globo.com/fotos/2011/09/15/15_MHG_RIO_camelo.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 0,
            friendly_url: "passar-sorvete-no-arroz",
            title: "passar sorvete no arroz",
            img: "https://i.ytimg.com/vi/H52kepS9tO4/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 12,
            friendly_url: "engordar-para-valer",
            title: "engordar para valer",
            img: "https://i.ytimg.com/vi/H52kepS9tO4/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 2,
            friendly_url: "peidar-na-fila-do-banco-e-sair-correndo",
            title: "peidar na fila do banco e sair correndo",
            img: "http://www.polemicaparaiba.com.br/wp-content/uploads/2015/09/fila-de-banco.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 3,
            friendly_url: "ir-no-mcdonalds-e-pedir-uma-salada",
            title: "ir no McDonalds e pedir uma salada",
            img: "https://venancios.files.wordpress.com/2013/04/gordo.jpg",
            css: {
                background: "303030",
                accent: "F44336",
                accent_dark: "B71C1C"
            }
        },
        {
            count: 1,
            friendly_url: "fazer-um-site-de-maldade",
            title: "fazer um site de maldade",
            img: "https://i.ytimg.com/vi/oR13iPNv9wI/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "colocar-filtro-do-cachorro",
            title: "colocar o filtro do cachorro",
            img: "http://static1.purebreak.com.br/articles/1/30/98/1/@/154968-kendall-jenner-tambem-adora-usar-o-filtr-950x0-1.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "pegar-homem-pegar-mulher",
            title: "pegar homem, pegar mulher! BORAA",
            img: "https://i.ytimg.com/vi/M81ke9svVXo/hqdefault.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },
        {
            count: 0,
            friendly_url: "pisar-na-grama",
            title: "pisar na grama",
            img: "http://redeemancipa.org.br/wp-content/uploads/2012/12/n%C3%A3o-pise.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "logar-no-notebook-com-capslock-ligado",
            title: "logar no notebook com o capslock ligado",
            img: "https://secure.logitech.com/assets/32508/35/k800-top.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "visualizar-e-nao-responder",
            title: "visualizar e não responder",
            img: "http://lounge.obviousmag.org/monica_montone/assets_c/2015/10/visualizar%20e%20n%C3%A3o%20responder%20(1)-thumb-800x600-125118.png",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "like-proprio-video",
            title: "dar like no próprio video",
            img: "http://www.uhull.com.br/wp-content/uploads/2008/10/017_pics-399x263.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "curtir-proprio-comentario",
            title: "curtir o proprio comentário",
            img: "http://www.uhull.com.br/wp-content/uploads/2008/10/017_pics-399x263.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "nao-respoder-amem-no-grupo-da-familia",
            title: "não responder amém no grupo da famila",
            img: "https://www.whatsapp.com/img/v2/logo-promo.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "mandar-video-de-gemido-para-avo",
            title: "mandar video de gemido para a Avó",
            img: "http://www.tribunahoje.com/vgmidia/imagens/21533_ext_arquivo.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "espalhar-que-o-whatsapp-sera-pago",
            title: "espalhar que o whatsapp será pago",
            img: "http://franquiaautomatica.com/blog/wp-content/uploads/2014/07/whatsapp-pago-whatsapp-gratis-whatsapp-vai-ser-pago.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "dar-like-em-baranga-no-tinder",
            title: "dar like em baranga no Tinter",
            img: "http://www.eonline.com/eol_images/Entire_Site/2014817/rs_560x415-140917143530-1024.Tinder-Logo.ms.091714_copy.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "mandar-indireta-para-o-vizinho-com-o-nome-da-rede-wifi",
            title: "mandar indireta para o vizinho com o nome da rede wifi",
            img: "http://img.ibxk.com.br/ns/rexposta/2015/05/14/14213459278002.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "pedir-vida-no-candycrush",
            title: "pedir vida no Candy Crush",
            img: "http://i2.wp.com/candycrushsodasagatips.com/wp-content/uploads/2014/10/candy-crush-soda-level-13-new-screenshot.png",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "alterar-fonte-notepad",
            title: "alterar o fonte no notepad",
            img: "http://www.tutorials4u.com/html/graphics/notepad/notepad-new-page.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "debug-em-producao",
            title: "fazer debug em produção",
            img: "http://i.istockimg.com/file_thumbview_approve/68886757/6/stock-photo-68886757-it-background-binary-code-a08.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "fechar-chamado-no-ultimo-dia-do-sla",
            title: "fechar o chamado no ultimo dia do SLA",
            img: "http://i.istockimg.com/file_thumbview_approve/68886757/6/stock-photo-68886757-it-background-binary-code-a08.jpg",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        },

        {
            count: 0,
            friendly_url: "fazer-style-inline",
            title: "fazer style inline",
            img: "http://img.pandawhale.com/56193-Whenever-I-try-to-open-blinds-1kSs.gif",
            css: {
                background: "303030",
                accent: "0288D1"
            }
        }

    ];

    var newEvil = function() {
        var randomInt = random.randomInt(0,data.length);
        return data[randomInt];
    };

    var doEvil = function (friendlyUrl) {
        var evil = findByFriendlyURL(friendlyUrl);
        evil.count = evil.count+1;
    };

    var evilsDone = function () {
        return data.map(evil => evil.count ).reduce((first, second) => first + second);
    };

    var totalEvils = function () {
        return data.length;
    };

    var findByFriendlyURL = function(friendlyUrl) {
        for (var i = 0; i < data.length; i++) {
            var evil = data[i];
            if(evil.friendly_url === friendlyUrl){
                return evil;
            }
        }
        return {};
    };

    return {
        evilsDone: evilsDone,
        totalEvils: totalEvils,
        newEvil: newEvil,
        doEvil: doEvil,
        findByFriendlyURL: findByFriendlyURL
    }
};
<|endoftext|>


<commit_before>//This is An OOP Model of a bank account
//OOP is suitable for when you have relatively
//few operations and and large data sets

//Base account model implements the standard features

class Account {
	constructor(name, age, amount) {
		this._name = name;
		this._age = age;
		this._balance = amount;
	}

	//deposit method for account class
	deposit(amount){
		this._balance += amount;
		return "TRANSACTION SUCCESSFUL: You have deposited " + amount;
	}

	//withdraw method for account class
	withdraw(amount){
		if (amount < this._balance) {
			this._balance -= amount;
			return "TRANSACTION SUCCESSFUL: You have withdrawn " + amount;
		}

	}

	//balance method for account class
	balance(){
		this._balance;
		return "TRANSACTION SUCCESSFUL: You have " + this._balance + " in your account";
	}
}

//export an instance
module.exports = {
	Ade : new Account("Adeoluwa Adejumo", 5, 5000)
	Victoria: new SavingsAcc("Victoria Offoma" 19, 50000)
}<commit_msg>implement savings account class<commit_after>//This is An OOP Model of a bank account
//OOP is suitable for when you have relatively
//few operations and and large data sets

//Base account model implements the standard features

class Account {
	constructor(name, age, amount) {
		this._name = name;
		this._age = age;
		this._balance = amount;
	}

	//deposit method for account class
	deposit(amount){
		this._balance += amount;
		return "TRANSACTION SUCCESSFUL: You have deposited " + amount;
	}

	//withdraw method for account class
	withdraw(amount){
		if (amount < this._balance) {
			this._balance -= amount;
			return "TRANSACTION SUCCESSFUL: You have withdrawn " + amount;
		}

	}

	//balance method for account class
	balance(){
		this._balance;
		return "TRANSACTION SUCCESSFUL: You have " + this._balance + " in your account";
	}
}

class SavingsAcc extends Account {
	super(name, age, amount) {
	}
}

//export an instance
module.exports = {
	Ade : new Account("Adeoluwa Adejumo", 20, 5000),
	Victoria: new SavingsAcc("Victoria Offoma", 19, 50000)
}<|endoftext|>