<commit_before>/* global goog, lime, obacht */
/* jshint devel:true */

goog.provide('obacht.Bonus');
goog.require('lime.RoundedRect');

/**
 * Bonus Object.
 *
 * @constructor
 *
 * @author Lukas Jaborsky
 */
obacht.Bonus = function(type) {
	"use strict";
	console.log("new Bonus");

	////////////////
    // ATTRIBUTES //
    ////////////////
    var self = this;
    this.type = type;
	this.fill = obacht.options.bonus.general.path + this.type + '.png';

	//this.time = new Date();
	this.drawtime = 0;
	this.clicktime = 0;

	////////////////////
    // LIMEJS OBJECTS //
    ////////////////////
	this.bonusButton = new lime.RoundedRect().setSize(obacht.options.bonus.general.size, obacht.options.bonus.general.size).setPosition(obacht.options.bonus.general.x, obacht.options.bonus.general.y).setFill(this.fill).setAnchorPoint(0, 0).setRadius(15);
    this.layer = new lime.Layer().setSize(obacht.options.graphics.VIEWPORT_WIDTH, obacht.options.graphics.VIEWPORT_HEIGHT);
    self.drawBonus();

    //this.layer.appendChild(this.bonusButton);

    /////////////////////////
    // SUBSCRIBE TO EVENTS //
    /////////////////////////
    goog.events.listen(this.bonusButton, ['touchstart', 'mousedown'], function(e) {
        self.checkReactiontime();
        self.deleteBonus();
    });
};

obacht.Bonus.prototype = {

     /**
     * Draw the bonus-button
     */
    drawBonus: function() {
        "use strict";
        this.layer.appendChild(this.bonusButton);
        this.drawtime = this.getTime();
        this.bonusTimer();
    },

    bonusTimer: function() {
        "use strict";

    },

    /**
     * Delete the bonus-button
     */
    deleteBonus: function() {
        "use strict";
        this.layer.removeChild(this.bonusButton);
    },

    /**
     * Check the reaction time
     */
    checkReactiontime: function() {
        "use strict";
        this.clicktime = this.getTime();
        var reactiontime = this.clicktime - this.drawtime;
        console.log('Reaktionszeit in ms: ' + reactiontime);
    },

    getTime: function() {
        "use strict";
        var time = new Date(),
            ms = time.getTime();

        return ms;
    }

};
<commit_msg>Bonus Timer verbessert<commit_after>/* global goog, lime, obacht */
/* jshint devel:true */

goog.provide('obacht.Bonus');
goog.require('lime.RoundedRect');

/**
 * Bonus Object.
 *
 * @constructor
 *
 * @author Lukas Jaborsky
 */
obacht.Bonus = function(type) {
	"use strict";
	console.log("new Bonus");

	////////////////
    // ATTRIBUTES //
    ////////////////
    var self = this;
    this.type = type;
	this.fill = obacht.options.bonus.general.path + this.type + '.png';

	//this.time = new Date();
	this.drawtime = 0;
	this.clicktime = 0;

	////////////////////
    // LIMEJS OBJECTS //
    ////////////////////
	this.bonusButton = new lime.RoundedRect().setSize(obacht.options.bonus.general.size, obacht.options.bonus.general.size).setPosition(obacht.options.bonus.general.x, obacht.options.bonus.general.y).setFill(this.fill).setAnchorPoint(0, 0).setRadius(15);
    this.layer = new lime.Layer().setSize(obacht.options.graphics.VIEWPORT_WIDTH, obacht.options.graphics.VIEWPORT_HEIGHT);
    self.drawBonus();

    //this.layer.appendChild(this.bonusButton);

    /////////////////////////
    // SUBSCRIBE TO EVENTS //
    /////////////////////////
    goog.events.listen(this.bonusButton, ['touchstart', 'mousedown'], function(e) {
        self.checkReactiontime();
        self.deleteBonus();
    });
};

obacht.Bonus.prototype = {

     /**
     * Draw the bonus-button
     */
    drawBonus: function() {
        "use strict";
        this.layer.appendChild(this.bonusButton);
        this.drawtime = this.getTime();
        this.bonusTimer();
    },

    bonusTimer: function() {
        "use strict";
        var self = this;
        setTimeout(function(){
           self.deleteBonus();
        },2000);
    },

    /**
     * Delete the bonus-button
     */
    deleteBonus: function() {
        "use strict";
        this.layer.removeChild(this.bonusButton);
    },

    /**
     * Check the reaction time
     */
    checkReactiontime: function() {
        "use strict";
        this.clicktime = this.getTime();
        var reactiontime = this.clicktime - this.drawtime;
        console.log('Reaktionszeit in ms: ' + reactiontime);
    },

    getTime: function() {
        "use strict";
        var time = new Date(),
            ms = time.getTime();

        return ms;
    }

};
<|endoftext|>


<commit_before>import request from 'superagent'

/**
 * @param  {Object} options
 * @return {Promise}
 */
function ajax(options) {
    const defaults = {
        type: 'post',
        url: null,
        data: {},
        'Content-Type': 'application/json'
    }
    let promise

    options = Object.assign({}, defaults, options)
    promise = request[options.type](options.url).withCredentials()
    Object.keys(options).forEach(key => {
        if (!key.match(/type|url|data/)) {
            promise.set(key, options[key])
        }
    })

    return new Promise(resolve => {
        promise.send(options.data).then(res => {
            resolve(res.body)
        }).catch(err => {
            console.log(err)
        })
    })
}

/**
 * @param  {number} timestamp
 * @param  {String} format
 * @return {String}
 */
function formatDate(timestamp, format) {
    const date = new Date(timestamp),
        years = date.getFullYear().toString(),
        month = date.getMonth().toString(),
        day = date.getDate().toString(),
        hours = date.getMonth().toString(),
        minutes = date.getMinutes().toString(),
        seconds = date.getSeconds().toString()

    return format.replace(/y+|M+|d+|h+|m+|s+/g, match => {
        const length = match.length

        switch (match.charAt(0)) {
            case 'y':
                return years.substr(-length)
            case 'M':
                return (month.length === 1 ? `0${month}` : month).substr(-length)
            case 'd':
                return (day.length === 1 ? `0${day}` : day).substr(-length)
            case 'h':
                return (hours.length === 1 ? `0${hours}` : hours).substr(-length)
            case 'm':
                return (minutes.length === 1 ? `0${minutes}` : minutes).substr(-length)
            case 's':
                return (seconds.length === 1 ? `0${seconds}` : seconds).substr(-length)
        }
    })
}

/**
 * @param  {String} str
 * @return {Date}
 */
function parseDate(str) {
    let results

    if (results = str.match(/^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s*$/)) {
        return new Date(+results[1], +results[2] - 1, +results[3])
    } else if (results = str.match(/^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/)) {
        return new Date(+results[1], +results[2] - 1, +results[3], +results[4], +results[5], +results[6])
    }
}

/**
 * @return {Object}
 */
function getUrlParams() {
    const search = location.search.slice(1),
        rParam = /([^&]*)=([^&]*)/g
    let ret = {},
        param

    while (param = rParam.exec(search)) {
        ret[param[1]] = param[2]
    }

    return ret
}

export default {
    ajax,
    formatDate,
    parseDate,
    getUrlParams
}
<commit_msg>Optimize formatDate util using es6<commit_after>import request from 'superagent'

/**
 * @param  {Object} options
 * @return {Promise}
 */
function ajax(options) {
    const defaults = {
        type: 'post',
        url: null,
        data: {},
        'Content-Type': 'application/json'
    }
    let promise

    options = Object.assign({}, defaults, options)
    promise = request[options.type](options.url).withCredentials()
    Object.keys(options).forEach(key => {
        if (!key.match(/type|url|data/)) {
            promise.set(key, options[key])
        }
    })

    return new Promise(resolve => {
        promise.send(options.data).then(res => {
            resolve(res.body)
        }).catch(err => {
            console.log(err)
        })
    })
}

/**
 * @param  {number} timestamp
 * @param  {String} format
 * @return {String}
 */
function formatDate(timestamp, format) {
    const date = new Date(timestamp),
        years = `${date.getFullYear()}`,
        month = `${date.getMonth()}`,
        day = `${date.getDate()}`,
        hours = `${date.getMonth()}`,
        minutes = `${date.getMinutes()}`,
        seconds = `${date.getSeconds()}`

    return format.replace(/y+|M+|d+|h+|m+|s+/g, match => {
        const length = match.length

        switch (match.charAt(0)) {
            case 'y':
                return years.substr(-length)
            case 'M':
                return (month.length === 1 ? `0${month}` : month).substr(-length)
            case 'd':
                return (day.length === 1 ? `0${day}` : day).substr(-length)
            case 'h':
                return (hours.length === 1 ? `0${hours}` : hours).substr(-length)
            case 'm':
                return (minutes.length === 1 ? `0${minutes}` : minutes).substr(-length)
            case 's':
                return (seconds.length === 1 ? `0${seconds}` : seconds).substr(-length)
        }
    })
}

/**
 * @param  {String} str
 * @return {Date}
 */
function parseDate(str) {
    let results

    if (results = str.match(/^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s*$/)) {
        return new Date(+results[1], +results[2] - 1, +results[3])
    } else if (results = str.match(/^\s*(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/)) {
        return new Date(+results[1], +results[2] - 1, +results[3], +results[4], +results[5], +results[6])
    }
}

/**
 * @return {Object}
 */
function getUrlParams() {
    const search = location.search.slice(1),
        rParam = /([^&]*)=([^&]*)/g
    let ret = {},
        param

    while (param = rParam.exec(search)) {
        ret[param[1]] = param[2]
    }

    return ret
}

export default {
    ajax,
    formatDate,
    parseDate,
    getUrlParams
}
<|endoftext|>


<commit_before>var utils = require('../utils');

module.exports = function Bound () {

  this.defaults = utils.defaults({}, this.defaults, {
    data: null,
    binding: null
  });

  this.update = function (obj) {
    if (obj) {
      this.data = obj;
    }
    var traverse = function (obj, key) {
      var value;
      for (var name in obj) {
        value = obj[name];
        var newKey = key ? key + '.' + name : name;
        if ('object' === typeof value) {
          traverse(value, newKey);
        } else {
          this.setDOMValue(newKey, value);
        }
      }
    }.bind(this);
    traverse(this.data, '');
  };

  this.set = function (key, value) {
    this.setDataValue(key, value);
    this.setDOMValue(key, value);
  };

  this.get = function (key) {
    return utils.getObjectPath(this.data, key);
  };

  this.bind = function () {
    if (this.binding) {
      this._keyBinding = this._keyBinding || {};
      utils.forIn(this.binding, function (binding, selector) {
        if (utils.isString(binding)) {
          binding = { key: binding };
        }
        var nodes, key = binding.key, events = binding.events || ['change'];
        if (selector[0] === '@') {
          nodes = this.ui[selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(selector));
        }
        nodes.forEach(function (node) {
          if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            utils.forIn(events, function (eventName) {
              this.listenTo(node, eventName + ':bound', function (event) {
                var value, el = event.target;
                if (el.type.toLowerCase() === 'checkbox' || el.type.toLowerCase() === 'radio') {
                  value = 'undefined' === typeof el.value ? true : el.value;
                  value = el.checked ? value : undefined;
                } else {
                  value = el.value;
                }
                this.set(key, value);
              });
            }, this);
          }
        }.bind(this));
        binding.selector = selector;
        this._keyBinding[key] = this._keyBinding[key] || [];
        this._keyBinding[key].push(binding);
      }, this);
      this._isBound = true;
    }
  };

  this.unbind = function () {
    if (this.binding && this._isBound) {
      this._keyBinding = {};
      utils.forIn(this.binding, function (binding, selector) {
        if (utils.isString(binding)) {
          binding = { key: binding };
        }
        var nodes, events = binding.events || ['change'];
        if (selector[0] === '@') {
          nodes = this.ui[selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(selector));
        }
        nodes.forEach(function (node) {
          if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            utils.forIn(events, function (eventName) {
              this.stopListening(node, eventName + ':bound');
            }, this);
          }
        }.bind(this));
      }, this);
    }
  };

  this.setDOMValue = function (key, value) {
    var nodes;
    if (utils.has(this._keyBinding, key)) {
      utils.forIn(this._keyBinding[key], function (binding) {
        if (binding.selector[0] === '@') {
          nodes = this.ui[binding.selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (binding.selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(binding.selector));
        }
        if (binding.format) {
          if (utils.isString(binding.format)) {
            binding.format = this[binding.format];
          }
          value = binding.format.call(this, value);
        }
        nodes.forEach(function (node) {
          if (binding.property) {
            utils.setObjectPath(node, binding.property, value);
          } else if (binding.attribute) {
            node.setAttribute(binding.attribute, value.toString());
          } else if (binding.html) {
            node.innerHTML = value.toString();
          } else if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            if (node.type.toLowerCase() === 'checkbox') {
              node.checked = (value === true || value === 1 || value === 'true' || value === 'on');
            } else if (node.type.toLowerCase() === 'radio') {
              node.checked = node.value === value.toString();
            } else {
              node.value = value.toString();
            }
          } else {
            node.textContent = value.toString();
          }
        });
      }, this);
    }
  };

  this.setDataValue = function (key, value) {
    var e, oldValue = utils.getObjectPath(this.data, key);
    if (oldValue !== value) {
      utils.setObjectPath(this.data, key, value);
      e = utils.createEvent('datachange', { key: key, oldValue: oldValue, newValue: value });
      this.el.dispatchEvent(e);
    }
  };

  if (utils.has(this, 'render')) {
    this.around('render', function (render, data) {
      this.unbind();
      render.call(this, data);
      this.bind();
      this.update(data);
    });
  }

  this.before('initialize', function (options) {
    this.data = this.data || options.data || {};
    this.bind();
    this.update();
  });
};
<commit_msg>fixes checkbox binding<commit_after>var utils = require('../utils');

module.exports = function Bound () {

  this.defaults = utils.defaults({}, this.defaults, {
    data: null,
    binding: null
  });

  this.update = function (obj) {
    if (obj) {
      this.data = obj;
    }
    var traverse = function (obj, key) {
      var value;
      for (var name in obj) {
        value = obj[name];
        var newKey = key ? key + '.' + name : name;
        if ('object' === typeof value) {
          traverse(value, newKey);
        } else {
          this.setDOMValue(newKey, value);
        }
      }
    }.bind(this);
    traverse(this.data, '');
  };

  this.set = function (key, value) {
    this.setDataValue(key, value);
    this.setDOMValue(key, value);
  };

  this.get = function (key) {
    return utils.getObjectPath(this.data, key);
  };

  this.bind = function () {
    if (this.binding) {
      this._keyBinding = this._keyBinding || {};
      utils.forIn(this.binding, function (binding, selector) {
        if (utils.isString(binding)) {
          binding = { key: binding };
        }
        var nodes, key = binding.key, events = binding.events || ['change'];
        if (selector[0] === '@') {
          nodes = this.ui[selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(selector));
        }
        nodes.forEach(function (node) {
          if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            utils.forIn(events, function (eventName) {
              this.listenTo(node, eventName + ':bound', function (event) {
                var value, el = event.target;
                if (el.type.toLowerCase() === 'checkbox') {
                  value = el.checked;
                } else if (el.type.toLowerCase() === 'radio') {
                  value = 'undefined' === typeof el.value ? 1 : el.value;
                  value = el.checked ? value : undefined;
                } else {
                  value = el.value;
                }
                this.set(key, value);
              });
            }, this);
          }
        }.bind(this));
        binding.selector = selector;
        this._keyBinding[key] = this._keyBinding[key] || [];
        this._keyBinding[key].push(binding);
      }, this);
      this._isBound = true;
    }
  };

  this.unbind = function () {
    if (this.binding && this._isBound) {
      this._keyBinding = {};
      utils.forIn(this.binding, function (binding, selector) {
        if (utils.isString(binding)) {
          binding = { key: binding };
        }
        var nodes, events = binding.events || ['change'];
        if (selector[0] === '@') {
          nodes = this.ui[selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(selector));
        }
        nodes.forEach(function (node) {
          if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            utils.forIn(events, function (eventName) {
              this.stopListening(node, eventName + ':bound');
            }, this);
          }
        }.bind(this));
      }, this);
    }
  };

  this.setDOMValue = function (key, value) {
    var nodes;
    if (utils.has(this._keyBinding, key)) {
      utils.forIn(this._keyBinding[key], function (binding) {
        if (binding.selector[0] === '@') {
          nodes = this.ui[binding.selector.substr(1)];
          if (!Array.isArray(nodes) && !(nodes instanceof NodeList)) {
            nodes = [nodes];
          }
        } else if (binding.selector === '$') {
          nodes = [this.el];
        } else {
          nodes = [].slice.call(this.selectAll(binding.selector));
        }
        if (binding.format) {
          if (utils.isString(binding.format)) {
            binding.format = this[binding.format];
          }
          value = binding.format.call(this, value);
        }
        nodes.forEach(function (node) {
          if (binding.property) {
            utils.setObjectPath(node, binding.property, value);
          } else if (binding.attribute) {
            node.setAttribute(binding.attribute, value.toString());
          } else if (binding.html) {
            node.innerHTML = value.toString();
          } else if (node.tagName === 'INPUT' || node.tagName === 'SELECT' || node.tagName === 'TEXTAREA') {
            if (node.type.toLowerCase() === 'checkbox') {
              node.checked = (value === true || value === 1 || value === 'true' || value === 'on');
            } else if (node.type.toLowerCase() === 'radio') {
              node.checked = node.value === value.toString();
            } else {
              node.value = value.toString();
            }
          } else {
            node.textContent = value.toString();
          }
        });
      }, this);
    }
  };

  this.setDataValue = function (key, value) {
    var e, oldValue = utils.getObjectPath(this.data, key);
    if (oldValue !== value) {
      utils.setObjectPath(this.data, key, value);
      e = utils.createEvent('datachange', { key: key, oldValue: oldValue, newValue: value });
      this.el.dispatchEvent(e);
    }
  };

  if (utils.has(this, 'render')) {
    this.around('render', function (render, data) {
      this.unbind();
      render.call(this, data);
      this.bind();
      this.update(data);
    });
  }

  this.before('initialize', function (options) {
    this.data = this.data || options.data || {};
    this.bind();
    this.update();
  });
};
<|endoftext|>


<commit_before>var exec = require('child_process').exec;
var fs = require('fs');
var glob = require('glob');

glob('dist/**/*.css', (err, files) =>
    files.forEach(file =>
        fs.readFile(file, 'utf8', (err, data) => {

            let lessfile = file.replace('.css', '.less');

            data = `.uk-noconflict {\n${data}\n}`;

            fs.writeFile(lessfile, data, err => {

                if (err) {
                    throw err;
                }

                exec(`lessc ${lessfile} > ${file}`, (error, stdout, stderr) => {

                    if (stderr) {
                        console.log(`Error building: ${file}`, stderr);
                    } else {

                        fs.readFile(file, 'utf8', (err, data) => {

                            data = data.replace(/\.uk-noconflict \{(.|[\r\n])*?\}/, '')
                                       .replace(`.uk-noconflict html`, `.uk-noconflict`)
                                       .replace(/\.uk-noconflict\s(\.(uk-(drag|modal-page|offcanvas-page|offcanvas-flip)))/g, '$1');

                            fs.writeFile(file, data);
                        });

                        console.log(`${file} build`);
                    }

                    fs.unlink(lessfile);

                });
            });

        })
    )
);
<commit_msg>cleanup no-conflict.js<commit_after>var fs = require('fs');
var glob = require('glob');
var less = require('less');
var util = require('./util');

glob('dist/**/*.css', (err, files) =>
    files.forEach(file =>
        fs.readFile(file, 'utf8', (err, data) => {

            less.render(`.uk-noconflict {\n${data}\n}`).then(output => {

                data = output.css.replace(/\.uk-noconflict \{(.|[\r\n])*?\}/, '')
                    .replace(`.uk-noconflict html`, `.uk-noconflict`)
                    .replace(/\.uk-noconflict\s(\.(uk-(drag|modal-page|offcanvas-page|offcanvas-flip)))/g, '$1');

                fs.writeFile(file, data, err => {

                    if (err) {
                        throw err;
                    }

                    console.log(`${util.cyan(file)} ${util.getSize(data)}`);

                });

            });

        })
    )
);
<|endoftext|>


<commit_before>const fetch = require ('fetch-ponyfill') ().fetch

function style(s, style) {
    return style + s + '\033[0m'
}

const colors = {
    'black': 30,
    'red': 31,
    'green': 32,
    'yellow': 33,
    'blue': 34,
    'white': 37,
    'gray': 90,
}

let colorFunctions = {}
for (let color of Object.keys (colors)) {
    colorFunctions[color] = (s) => console.log (style (s, '\033[' + colors[color].toString () + 'm'))
}

let ascii = [
    '                                                         ',
    '                         :Siiiiiiiiiiir    rSiiiiiiiiiiS:',
    '                         r&9hh&&&&&&&A5    SG99h&&&&&&GHr',
    '                         ;hX32;::::::;,    i9X9S:;:::::;,',
    '                         ;hX9S             ihXhr         ',
    '                         ;hX32::::::,:,    i9X9i::::::,:.',
    '                         rG999GGGGGGGAS    iG99hGGGGGGGAr',
    '                         ;2S55SSSSSSS2r    r2555SSSSSSS2;',
    '                         ;2S5s    ;2S2r    r2SS555555SS2;',
    '                         rAh&2    sAhAS    SAGGh9999GGGAr',
    '                         .:,::rrrs::::,    ,:,,;9X3X:,,:.',
    '                              &A&H,            ,hX33     ',
    '                         ,;:;;;;;r;;:;,        ,hX3X.    ',
    '                         rHGAX    sAGA5        :&9h9.    ',
    '                         :Ssir    ;isir        ,Siii     ',
    '                                                         ',
]

let footer = [
    '                                                                 ',
    '              ---------------------------------------------------',
    '                                                                 ',
    '                     You can contribute in crypto directly:      ',
    '                                                                 ',
    '                 ETH 0xa7c2b18b7c8b86984560cad3b1bc3224b388ded0  ',
    '                 BTC 33RmVRfhK2WZVQR1R83h2e9yXoqRNDvJva          ',
    '                 BCH 1GN9p233TvNcNQFthCgfiHUnj5JRKEc2Ze          ',
    '                 LTC LbT8mkAqQBphc4yxLXEDgYDfEax74et3bP          ',
    '                                                                 ',
    '              ---------------------------------------------------',
    '                                                                 ',
    '                                   Thank you!                    ',
    '                                                                 ',
]

async function getData () {
    let data =  {}
    let collectiveData = await (await fetch ('https://opencollective.com/ccxt.json')).json ()
    let githubData = await (await fetch ('https://api.github.com/repos/ccxt/ccxt')).json ()
    data['contributors'] = collectiveData['contributorsCount'].toLocaleString ()
    data['backers'] = collectiveData['backersCount'].toLocaleString ()
    data['balance'] = Math.floor (collectiveData['balance'] / 100).toLocaleString ()
    data['budget'] = Math.floor (collectiveData['yearlyIncome'] / 100).toLocaleString ()
    data['stars'] = githubData['stargazers_count'].toLocaleString ()
    data['forks'] = githubData['forks_count'].toLocaleString ()
    data['size'] = (githubData['size'] / 1000000).toFixed (2)
    return data
}

function pad (string) {
    const padding = 80 - string.length
    const half = Math.floor (padding / 2)
    return ' '.repeat (half + (padding % 2)) + string + ' '.repeat (half)
}

getData().then ((data) => {
    colorFunctions['blue'] (ascii.join ('\n'))
    colorFunctions['red'] (pad (`Stars: ${data['stars']}`))
    colorFunctions['red'] (pad (`Forks: ${data['forks']}`))
    colorFunctions['red'] (pad (`Contributors: ${data['contributors']}`))
    colorFunctions['red'] (pad (`Size: ${data['size']}MB`))
    colorFunctions['yellow'] ('\n' + pad ('Thanks for installing ccxt 🙏'))
    colorFunctions['gray'] (pad ('Please consider donating to our open collective'))
    colorFunctions['gray'] (pad ('to help us maintain this package.'))
    colorFunctions['yellow'] (pad ('👉 Donate: https://opencollective.com/ccxt/donate 🎉'))
    colorFunctions['white'] (pad (`Thanks to our ${data['backers']} backers we are operating on an annual budget of $${data['budget']}`))
    colorFunctions['black'] (footer.join ('\n'))
})
<commit_msg>update build/postinstall.js<commit_after>const fetch = require ('fetch-ponyfill') ().fetch

function style(s, style) {
    return style + s + '\033[0m'
}

const colors = {
    'black': 30,
    'red': 31,
    'green': 32,
    'yellow': 33,
    'blue': 34,
    'white': 37,
    'gray': 90,
}

let colorFunctions = {}
for (let color of Object.keys (colors)) {
    colorFunctions[color] = (s) => console.log (style (s, '\033[' + colors[color].toString () + 'm'))
}

let ascii = [
    '                                                         ',
    '                         :Siiiiiiiiiiir    rSiiiiiiiiiiS:',
    '                         r&9hh&&&&&&&A5    SG99h&&&&&&GHr',
    '                         ;hX32;::::::;,    i9X9S:;:::::;,',
    '                         ;hX9S             ihXhr         ',
    '                         ;hX32::::::,:,    i9X9i::::::,:.',
    '                         rG999GGGGGGGAS    iG99hGGGGGGGAr',
    '                         ;2S55SSSSSSS2r    r2555SSSSSSS2;',
    '                         ;2S5s    ;2S2r    r2SS555555SS2;',
    '                         rAh&2    sAhAS    SAGGh9999GGGAr',
    '                         .:,::rrrs::::,    ,:,,;9X3X:,,:.',
    '                              &A&H,            ,hX33     ',
    '                         ,;:;;;;;r;;:;,        ,hX3X.    ',
    '                         rHGAX    sAGA5        :&9h9.    ',
    '                         :Ssir    ;isir        ,Siii     ',
    '                                                         ',
]

let footer = [
    '                                                                 ',
    '              ---------------------------------------------------',
    '                                                                 ',
    '                     You can contribute in crypto directly:      ',
    '                                                                 ',
    '                 ETH 0x26a3CB49578F07000575405a57888681249c35Fd  ',
    '                 BTC 33RmVRfhK2WZVQR1R83h2e9yXoqRNDvJva          ',
    '                 BCH 1GN9p233TvNcNQFthCgfiHUnj5JRKEc2Ze          ',
    '                 LTC LbT8mkAqQBphc4yxLXEDgYDfEax74et3bP          ',
    '                                                                 ',
    '              ---------------------------------------------------',
    '                                                                 ',
    '                                   Thank you!                    ',
    '                                                                 ',
]

async function getData () {
    let data =  {}
    let collectiveData = await (await fetch ('https://opencollective.com/ccxt.json')).json ()
    let githubData = await (await fetch ('https://api.github.com/repos/ccxt/ccxt')).json ()
    data['contributors'] = collectiveData['contributorsCount'].toLocaleString ()
    data['backers'] = collectiveData['backersCount'].toLocaleString ()
    data['balance'] = Math.floor (collectiveData['balance'] / 100).toLocaleString ()
    data['budget'] = Math.floor (collectiveData['yearlyIncome'] / 100).toLocaleString ()
    data['stars'] = githubData['stargazers_count'].toLocaleString ()
    data['forks'] = githubData['forks_count'].toLocaleString ()
    data['size'] = (githubData['size'] / 1000000).toFixed (2)
    return data
}

function pad (string) {
    const padding = 80 - string.length
    const half = Math.floor (padding / 2)
    return ' '.repeat (half + (padding % 2)) + string + ' '.repeat (half)
}

getData().then ((data) => {
    colorFunctions['blue'] (ascii.join ('\n'))
    colorFunctions['red'] (pad (`Stars: ${data['stars']}`))
    colorFunctions['red'] (pad (`Forks: ${data['forks']}`))
    colorFunctions['red'] (pad (`Contributors: ${data['contributors']}`))
    colorFunctions['red'] (pad (`Size: ${data['size']}MB`))
    colorFunctions['yellow'] ('\n' + pad ('Thanks for installing ccxt 🙏'))
    colorFunctions['gray'] (pad ('Please consider donating to our open collective'))
    colorFunctions['gray'] (pad ('to help us maintain this package.'))
    colorFunctions['yellow'] (pad ('👉 Donate: https://opencollective.com/ccxt/donate 🎉'))
    colorFunctions['white'] (pad (`Thanks to our ${data['backers']} backers we are operating on an annual budget of $${data['budget']}`))
    colorFunctions['black'] (footer.join ('\n'))
})
<|endoftext|>


<commit_before>"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var controller_1 = require("./controller");
var joltronVersion = 'v1.1.1-beta';
var https = require('follow-redirects').https;
function doTheThing() {
    return __awaiter(this, void 0, void 0, function () {
        var executable, binDir, file, remoteExecutable, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    executable = controller_1.getExecutable();
                    binDir = path.dirname(executable);
                    return [4 /*yield*/, new Promise(function (resolve, reject) {
                            mkdirp(binDir, function (err) {
                                if (err) {
                                    return reject(err);
                                }
                                return resolve();
                            });
                        })];
                case 1:
                    _a.sent();
                    file = fs.createWriteStream(executable, { mode: 493 });
                    switch (process.platform) {
                        case 'win32':
                            remoteExecutable = 'joltron_win32.exe';
                            break;
                        case 'linux':
                            remoteExecutable = 'joltron_linux';
                            break;
                        case 'darwin':
                            remoteExecutable = 'joltron_osx';
                            break;
                    }
                    options = {
                        host: 'github.com',
                        path: "/gamejolt/joltron/releases/download/" + joltronVersion + "/" + remoteExecutable,
                    };
                    return [4 /*yield*/, new Promise(function (resolve, reject) {
                            https
                                .get(options, function (res) {
                                if (res.statusCode !== 200) {
                                    throw new Error("Invalid status code. Expected 200 got " + res.statusCode);
                                }
                                res.pipe(file);
                            })
                                .on('error', reject)
                                .on('end', function () { return resolve; })
                                .end();
                        })];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
doTheThing();
<commit_msg>Oops, forgot to bump build<commit_after>"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
var fs = require("fs");
var path = require("path");
var mkdirp = require("mkdirp");
var controller_1 = require("./controller");
var joltronVersion = 'v1.1.2-beta';
var https = require('follow-redirects').https;
function doTheThing() {
    return __awaiter(this, void 0, void 0, function () {
        var executable, binDir, file, remoteExecutable, options;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    executable = controller_1.getExecutable();
                    binDir = path.dirname(executable);
                    return [4 /*yield*/, new Promise(function (resolve, reject) {
                            mkdirp(binDir, function (err) {
                                if (err) {
                                    return reject(err);
                                }
                                return resolve();
                            });
                        })];
                case 1:
                    _a.sent();
                    file = fs.createWriteStream(executable, { mode: 493 });
                    switch (process.platform) {
                        case 'win32':
                            remoteExecutable = 'joltron_win32.exe';
                            break;
                        case 'linux':
                            remoteExecutable = 'joltron_linux';
                            break;
                        case 'darwin':
                            remoteExecutable = 'joltron_osx';
                            break;
                    }
                    options = {
                        host: 'github.com',
                        path: "/gamejolt/joltron/releases/download/" + joltronVersion + "/" + remoteExecutable,
                    };
                    return [4 /*yield*/, new Promise(function (resolve, reject) {
                            https
                                .get(options, function (res) {
                                if (res.statusCode !== 200) {
                                    throw new Error("Invalid status code. Expected 200 got " + res.statusCode);
                                }
                                res.pipe(file);
                            })
                                .on('error', reject)
                                .on('end', function () { return resolve; })
                                .end();
                        })];
                case 2:
                    _a.sent();
                    return [2 /*return*/];
            }
        });
    });
}
doTheThing();
<|endoftext|>


<commit_before>import path from 'path';
import webpack from 'webpack';
import express, { Router } from 'express';
import sessionMiddleware from 'express-session';
import bodyParser from 'body-parser';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { Spinner } from 'cli-spinner';
import { watch } from 'chokidar';
import opn from 'opn';
import config from 'config';
import 'colors';
import { generateViewsIndex } from '../services/indexer';
import reportWebpackStats from '../services/webpack-stats-reporter';
import configureDevRoutes from '../services/configure-dev-routes';
import invalidateRequireCache from '../services/invalidate-require-cache';
import watchChange from '../../server/services/watch-change';
import webpackConfig from '../webpack/webpack.dev';
import paths from '../../build/paths';

const devConfig = config.get('dev-server');

// dev server configuration (used by both webpack dev middleware and express)
const serverConfig = {
	host: '0.0.0.0',
	publicPath: webpackConfig.output.publicPath,
	overlay: {
		warnings: true,
		errors: true,
	},
	stats: {
		colors: false,
	},
	quiet: true,
	noInfo: true,
	index: 'index.html',
	port: 3000,
	...devConfig,
};

// setup compiler and dev server
const compiler = webpack(webpackConfig);

// create the express server app
const app = express();

// configure webpack dev and hot-reload middlewares
const devMiddleware = webpackDevMiddleware(compiler, serverConfig);
const hotMiddleware = webpackHotMiddleware(compiler, {
	log: null, // disable logs
});

// add the webpack middlewares
app.use(devMiddleware);
app.use(hotMiddleware);

// add support for various payloads
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// add support for sessions
app.use(sessionMiddleware({
	resave: false,
	saveUninitialized: false,
	...devConfig.session,
}));

// keep track of how long compile takes and whether it was the first compile
let startTime = Date.now();
let isFirstDone = true;

// setup spinner
const spinner = new Spinner('Please wait..');
spinner.setSpinnerString(19);

// called when the compiler starts compiling
compiler.plugin('compile', (_params) => {
	startTime = Date.now();

	spinner.setSpinnerTitle('Updating, please wait..');
	spinner.start();
});

// called when compiling fails hard
compiler.plugin('failed', (error) => {
	console.error(`${' FAILED '.bgRed.black} -${error}`);
});

// called when compiler finishes update
compiler.plugin('done', (stats) => {
	spinner.stop(true);

	reportWebpackStats(stats);

	if (stats.hasErrors()) {
		return;
	}

	const timeTaken = Date.now() - startTime;

	// open web browser on first done event
	if (isFirstDone) {
		const indexUrl = `http://localhost${serverConfig.port !== 80 ? `:${serverConfig.port}` : ''}/`;

		console.log(
			`${' SERVER STARTED '.bgGreen.black} on ${indexUrl.bold} ` +
			`in ${Math.round(timeTaken / 100) / 10}s (${process.env.NODE_ENV})`,
		);
		console.log(`> This is a development server. For production server use ${'> npm run production'.bold}`);
		console.log(`> Press ${'CTRL+C'.bold} to stop the server`);

		// open in browser
		opn(indexUrl);

		isFirstDone = false;
	} else {
		// console.log(`${' UPDATED '.bgGreen.black} in ${compileTimeTaken}ms`);
	}
});

// the router can be replaced to hot-reload server resources
let router = new Router();

// all the requests go to this router
app.use((request, response, next) => {
	router(request, response, next);
});

// configure initial dev routes
configureDevRoutes(router);

// watch for server js and graphql files
const watchPatterns = [
	path.join(paths.server, '**/*.js'),
	path.join(paths.server, '**/*.gql'),
];

// watch for server file changes
watchChange(watchPatterns, () => {
	const reloadStartTime = Date.now();

	invalidateRequireCache(/[/\\]server[/\\]/);

	// create new router
	router = new Router();

	// reconfigure dev routes
	configureDevRoutes(router);

	console.log(`${'reloaded server'.bold} in ${Date.now() - reloadStartTime}ms`);
});

// default route, serve the single-page app
app.use('*', (request, response, next) => {
	const filename = path.join(compiler.outputPath, 'index.html');

	// use the in-memory compiler file system
	compiler.outputFileSystem.readFile(filename, (err, result) => {
		if (err) {
			return next(err);
		}

		response.set('content-type', 'text/html');
		response.send(result);
		response.end();

		return null;
	});
});

// generate indexes
generateViewsIndex();

// watch for view file changes and regenerate the index
const viewsWatcher = watch(paths.views, {
	ignoreInitial: true,
});

// regenerate views index if the changed file is in views directory
viewsWatcher.on('all', () => {
	generateViewsIndex();
});

// start the dev server on given port
app.listen(serverConfig, () => {
	spinner.setSpinnerTitle('Starting development server, please wait..'.bold);
	spinner.start();
});
<commit_msg>Dev server now opens the graphiql interface.<commit_after>import path from 'path';
import webpack from 'webpack';
import express, { Router } from 'express';
import sessionMiddleware from 'express-session';
import bodyParser from 'body-parser';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { Spinner } from 'cli-spinner';
import { watch } from 'chokidar';
import opn from 'opn';
import config from 'config';
import 'colors';
import { generateViewsIndex } from '../services/indexer';
import reportWebpackStats from '../services/webpack-stats-reporter';
import configureDevRoutes from '../services/configure-dev-routes';
import invalidateRequireCache from '../services/invalidate-require-cache';
import watchChange from '../../server/services/watch-change';
import webpackConfig from '../webpack/webpack.dev';
import paths from '../../build/paths';

const devConfig = config.get('dev-server');

// dev server configuration (used by both webpack dev middleware and express)
const serverConfig = {
	host: '0.0.0.0',
	publicPath: webpackConfig.output.publicPath,
	overlay: {
		warnings: true,
		errors: true,
	},
	stats: {
		colors: false,
	},
	quiet: true,
	noInfo: true,
	index: 'index.html',
	port: 3000,
	...devConfig,
};

// setup compiler and dev server
const compiler = webpack(webpackConfig);

// create the express server app
const app = express();

// configure webpack dev and hot-reload middlewares
const devMiddleware = webpackDevMiddleware(compiler, serverConfig);
const hotMiddleware = webpackHotMiddleware(compiler, {
	log: null, // disable logs
});

// add the webpack middlewares
app.use(devMiddleware);
app.use(hotMiddleware);

// add support for various payloads
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// add support for sessions
app.use(sessionMiddleware({
	resave: false,
	saveUninitialized: false,
	...devConfig.session,
}));

// keep track of how long compile takes and whether it was the first compile
let startTime = Date.now();
let isFirstDone = true;

// setup spinner
const spinner = new Spinner('Please wait..');
spinner.setSpinnerString(19);

// called when the compiler starts compiling
compiler.plugin('compile', (_params) => {
	startTime = Date.now();

	spinner.setSpinnerTitle('Updating, please wait..');
	spinner.start();
});

// called when compiling fails hard
compiler.plugin('failed', (error) => {
	console.error(`${' FAILED '.bgRed.black} -${error}`);
});

// called when compiler finishes update
compiler.plugin('done', (stats) => {
	spinner.stop(true);

	reportWebpackStats(stats);

	if (stats.hasErrors()) {
		return;
	}

	const timeTaken = Date.now() - startTime;

	// open web browser on first done event
	if (isFirstDone) {
		const indexUrl = `http://localhost${serverConfig.port !== 80 ? `:${serverConfig.port}` : ''}/`;
		const graphiqlUrl = `http://localhost${serverConfig.port !== 80 ? `:${serverConfig.port}` : ''}/graphql`;

		console.log(
			`${' SERVER STARTED '.bgGreen.black} on ${indexUrl.bold} ` +
			`in ${Math.round(timeTaken / 100) / 10}s (${process.env.NODE_ENV})`,
		);
		console.log(`> This is a development server. For production server use ${'> npm run production'.bold}`);
		console.log(`> Press ${'CTRL+C'.bold} to stop the server`);

		// open both the application and Graphqiql interface in the browser
		opn(indexUrl);
		opn(graphiqlUrl);

		isFirstDone = false;
	} else {
		// console.log(`${' UPDATED '.bgGreen.black} in ${compileTimeTaken}ms`);
	}
});

// the router can be replaced to hot-reload server resources
let router = new Router();

// all the requests go to this router
app.use((request, response, next) => {
	router(request, response, next);
});

// configure initial dev routes
configureDevRoutes(router);

// watch for server js and graphql files
const watchPatterns = [
	path.join(paths.server, '**/*.js'),
	path.join(paths.server, '**/*.gql'),
];

// watch for server file changes
watchChange(watchPatterns, () => {
	const reloadStartTime = Date.now();

	invalidateRequireCache(/[/\\]server[/\\]/);

	// create new router
	router = new Router();

	// reconfigure dev routes
	configureDevRoutes(router);

	console.log(`${'reloaded server'.bold} in ${Date.now() - reloadStartTime}ms`);
});

// default route, serve the single-page app
app.use('*', (request, response, next) => {
	const filename = path.join(compiler.outputPath, 'index.html');

	// use the in-memory compiler file system
	compiler.outputFileSystem.readFile(filename, (err, result) => {
		if (err) {
			return next(err);
		}

		response.set('content-type', 'text/html');
		response.send(result);
		response.end();

		return null;
	});
});

// generate indexes
generateViewsIndex();

// watch for view file changes and regenerate the index
const viewsWatcher = watch(paths.views, {
	ignoreInitial: true,
});

// regenerate views index if the changed file is in views directory
viewsWatcher.on('all', () => {
	generateViewsIndex();
});

// start the dev server on given port
app.listen(serverConfig, () => {
	spinner.setSpinnerTitle('Starting development server, please wait..'.bold);
	spinner.start();
});
<|endoftext|>


<commit_before>/*
 *  Helpers related to node standard library.
 */

var fs = require('fs');

var nodeHelpers = {

  isFn: function (callback) {
    return callback !== undefined
      && typeof (callback) === 'function';
  },

  /**
   * Properly invoke a callback function.
   *
   * @param {Function} callback Callback function to invoke.
   */
  invoke: function (callback) {
    if ( nodeHelpers.isFn(callback) ) {
      var args = Array.prototype.slice.call(arguments, 0);
      args.shift();
      callback.apply(null, args);
    }
  },

  /**
   * Clear from the require cache, the given app path.
   *
   * @param {String} modulePath App path to clear from require cache.
   */
  clearRequireCache: function (modulePath) {
    if ( fs.existsSync(modulePath) ){
      modulePath = fs.realpathSync(modulePath);
    }
    for (var name in require.cache) {
      if (name.match(new RegExp('^' + modulePath))) {
        delete require.cache[name];
      }
    }
  },

  /**
   * Tells if the current process has freed
   * it s resources and thus is ready to quit properly
   */
  hasFreedResources: function () {
    /*eslint-disable */
    var handlesC = process._getActiveHandles().length;
    var requestsC = process._getActiveRequests().length;
    /*eslint-enable */
    return handlesC + requestsC === 0;
  },

  /**
   * Close a node server by calling each socket.destroy on close event
   *
   * @param {Object} server Server to clean.
   */
  clearCloseServer: function (server) {
    var sockets = [];
    server.on('connection', function removeSockets (socket) {
      sockets.push(socket);
      socket.on('close', function () {
        sockets.splice(sockets.indexOf(socket), 1);
      });
    });
    server.on('close', function() {
      sockets.forEach(function destroySocket (socket){
        socket.destroy();
      });
    });
  }
};

module.exports = nodeHelpers;<commit_msg>change isFn to isFunction<commit_after>/*
 *  Helpers related to node standard library.
 */

var fs = require('fs');

var nodeHelpers = {

  isFunction: function (callback) {
    return callback !== undefined
      && typeof (callback) === 'function';
  },

  /**
   * Properly invoke a callback function.
   *
   * @param {Function} callback Callback function to invoke.
   */
  invoke: function (callback) {
    if ( nodeHelpers.isFunction(callback) ) {
      var args = Array.prototype.slice.call(arguments, 0);
      args.shift();
      callback.apply(null, args);
    }
  },

  /**
   * Clear from the require cache, the given app path.
   *
   * @param {String} modulePath App path to clear from require cache.
   */
  clearRequireCache: function (modulePath) {
    if ( fs.existsSync(modulePath) ){
      modulePath = fs.realpathSync(modulePath);
    }
    for (var name in require.cache) {
      if (name.match(new RegExp('^' + modulePath))) {
        delete require.cache[name];
      }
    }
  },

  /**
   * Tells if the current process has freed
   * it s resources and thus is ready to quit properly
   */
  hasFreedResources: function () {
    /*eslint-disable */
    var handlesC = process._getActiveHandles().length;
    var requestsC = process._getActiveRequests().length;
    /*eslint-enable */
    return handlesC + requestsC === 0;
  },

  /**
   * Close a node server by calling each socket.destroy on close event
   *
   * @param {Object} server Server to clean.
   */
  clearCloseServer: function (server) {
    var sockets = [];
    server.on('connection', function removeSockets (socket) {
      sockets.push(socket);
      socket.on('close', function () {
        sockets.splice(sockets.indexOf(socket), 1);
      });
    });
    server.on('close', function() {
      sockets.forEach(function destroySocket (socket){
        socket.destroy();
      });
    });
  }
};

module.exports = nodeHelpers;<|endoftext|>


<commit_before>/*!
 * node-libnmap
 * Copyright(c) 2014 Jason Gerfen <jason.gerfen@gmail.com>
 * License: MIT
 */
var libnmap = function(method, options){

  'use strict'

  /**
   * @object defaults
   * @abstract Default set of options
   *
   * @param {String} path - Location of nmap binary
   * @param {String} scripts - Location of nmap lua scripts
   * @param {String} defaults - Default scan options
   * @param {Object} range - Must contain start & end key with value
   * @param {String} ports - Comma separated list of ports to scan
   */
  var defaults = {
    path: '/usr/bin/nmap',
    scripts: '/usr/bin/nmap/scripts/',
    defaults: '-T4 -Pn -A',
    range: '',
    ports: '',
    flags: ''
  }

  /**
   * @object methods
   * @abstract Public API
   */
  var methods = methods || {

    /**
     * @function scan
     * @abstract Performs scan of network device(s)
     *
     * @param {Object} opts - User supplied options
     */
    scan: function(opts){
      opts = setup.init(opts)

    },

    /**
     * @function discover
     * @abstract Performs auto-discovery of network devices
     *
     * @param {Object} opts - User supplied options
     */
    discover: function(opts){
      opts = setup.init(opts)

      var range = tools.range()
        , exec = require('child_process').exec
        , cmd = opts.path+' '+opts.defaults+' '+range[0].start+', '+range[0].end

console.log(cmd)

      exec(cmd, function (error, stdout, stderr){
        console.log('ERROR '+error)
        console.log('STDOUT '+stdout)
        console.log('STDERR '+stderr)
      })
    }
  }

  /**
   * @object setup
   * @abstract Performs initial setup requirements
   */
  var setup = setup || {

    /**
     * @function init
     * @abstract Initializes application env requirements
     *
     * @param {Object} opts - User supplied options
     */
    init: function(opts){
      return tools.merge(opts, defaults)
    }
  }

  /**
   * @object tools
   * @abstract General utilities
   */
  var tools = tools || {

    /**
     * @function merge
     * @abstract Merge/replace default options with user supplied options
     *
     * @param {Object} opts - User supplied options
     * @param {Object} defaults - Default options
     */
    merge: function(opts, defaults){
      opts = opts || {}

      for (var item in defaults){
        if (defaults.hasOwnProperty(item))
          opts[item] = defaults[item]

        opts[item] = defaults[item]
      }

      return opts;
    },

    /**
     * @function adapters
     * @abstract Obtains object containing network adapters while filtering
     *           local & loopback interfaces
     *
     * @returns {Array} An array network interface objects
     */
    adapters: function(){
      var ifaces = require('os').networkInterfaces()
        , obj = []

      for (var i in ifaces) {
        if (/array|object/.test(ifaces[i])){
          for (var x in ifaces[i]){
            if (/false/.test(ifaces[i][x].internal) &&
                /ipv4/i.test(ifaces[i][x].family)){
              var tmp = { interface: i, properties: ifaces[i][x] }
              obj.push(tmp)
            }
          }
        }
      }

      return obj
    },

    /**
     * @function getRange
     * @abstract Determines range of subnet from IPv4/IPv6 addresses
     *
     * @returns {Object} Object of a start & end range
     */
    range: function(){
      var Netmask = require('netmask').Netmask
        , ranges = []

      this.adapters().forEach(function(element){
        var block = new Netmask(element.properties.address+'/'+
                                element.properties.netmask)

        ranges.push({
          start: block.first,
          end: block.last
        })
      })

      return ranges
    }
  }

  /* Robot, do work */
  if (methods[method]){
    return methods[method].apply(this, Array.prototype.slice.call(arguments, 1))
  } else if ((typeof method==='object')||(!method)){
    return methods.init.apply(this, argumentss)
  } else {
    throw 'Method "'+method+'" does not exist, please see node-libnmap API'
  }
}

exports.libnmap = libnmap
<commit_msg>Mon Jan  6 19:52:18 MST 2014<commit_after>/*!
 * node-libnmap
 * Copyright(c) 2014 Jason Gerfen <jason.gerfen@gmail.com>
 * License: MIT
 */
var libnmap = function(method, options){

  'use strict'

  /**
   * @object defaults
   * @abstract Default set of options
   *
   * @param {String} path - Location of nmap binary
   * @param {String} scripts - Location of nmap lua scripts
   * @param {String} defaults - Default scan options
   * @param {Object} range - Must contain start & end key with value
   * @param {String} ports - Comma separated list of ports to scan
   */
  var defaults = {
    path: '/usr/bin/nmap',
    scripts: '/usr/bin/nmap/scripts/',
    defaults: '-T4 -Pn -A',
    range: '',
    ports: '',
    flags: ''
  }

  /**
   * @object methods
   * @abstract Public API
   */
  var methods = methods || {

    /**
     * @function scan
     * @abstract Performs scan of network device(s)
     *
     * @param {Object} opts - User supplied options
     */
    scan: function(opts){
      opts = setup.init(opts)

    },

    /**
     * @function discover
     * @abstract Performs auto-discovery of network devices
     *
     * @param {Object} opts - User supplied options
     */
    discover: function(opts){
      opts = setup.init(opts)

      var range = tools.range()
        , exec = require('child_process').exec
        , cmd = false

      range.forEach(function(subnet){
        cmd = opts.path+' '+opts.defaults+' '+subnet

        exec(cmd, function (error, stdout, stderr){
          console.log('ERROR '+error)
          console.log('STDOUT '+stdout)
          console.log('STDERR '+stderr)
        })
      })
    }
  }

  /**
   * @object setup
   * @abstract Performs initial setup requirements
   */
  var setup = setup || {

    /**
     * @function init
     * @abstract Initializes application env requirements
     *
     * @param {Object} opts - User supplied options
     */
    init: function(opts){
      return tools.merge(opts, defaults)
    }
  }

  /**
   * @object tools
   * @abstract General utilities
   */
  var tools = tools || {

    /**
     * @function merge
     * @abstract Merge/replace default options with user supplied options
     *
     * @param {Object} opts - User supplied options
     * @param {Object} defaults - Default options
     */
    merge: function(opts, defaults){
      opts = opts || {}

      for (var item in defaults){
        if (defaults.hasOwnProperty(item))
          opts[item] = defaults[item]

        opts[item] = defaults[item]
      }

      return opts;
    },

    /**
     * @function adapters
     * @abstract Obtains object containing network adapters while filtering
     *           local & loopback interfaces
     *
     * @returns {Array} An array network interface objects
     */
    adapters: function(){
      var ifaces = require('os').networkInterfaces()
        , obj = []

      for (var i in ifaces) {
        if (/array|object/.test(ifaces[i])){
          for (var x in ifaces[i]){
            if (/false/.test(ifaces[i][x].internal) &&
                /ipv4/i.test(ifaces[i][x].family)){
              var tmp = { interface: i, properties: ifaces[i][x] }
              obj.push(tmp)
            }
          }
        }
      }

      return obj
    },

    /**
     * @function getRange
     * @abstract Determines range of subnet from IPv4/IPv6 addresses
     *
     * @returns {Object} Object of a start & end range
     */
    range: function(){
      var Netmask = require('netmask').Netmask
        , ranges = []

      this.adapters().forEach(function(element){
        var block = new Netmask(element.properties.address+'/'+
                                element.properties.netmask)

        ranges.push(block.base+'/'+block.bitmask)
      })

      return ranges
    }
  }

  /* Robot, do work */
  if (methods[method]){
    return methods[method].apply(this, Array.prototype.slice.call(arguments, 1))
  } else if ((typeof method==='object')||(!method)){
    return methods.init.apply(this, argumentss)
  } else {
    throw 'Method "'+method+'" does not exist, please see node-libnmap API'
  }
}

exports.libnmap = libnmap
<|endoftext|>


<commit_before>var _ = require('lodash');
var async = require('async');
var utils = require('hoodie-utils-plugins')('cordova-notification:messages');
var ExtendedDatabaseAPI = utils.ExtendedDatabaseAPI;

var templateMessages = {
  'requestFriend': {
    to: '${ name } quer ser seu amigo',
  },
  'acceptedFriend': {
    from: '${ name } aceitou o seu pedido de amizade'
  }
};

module.exports = function (hoodie) {
  var profileDb = new ExtendedDatabaseAPI(hoodie, hoodie.database('plugins/hoodie-plugin-profile'));
  var pushService = require('./push-service')(hoodie);
  var MessagesAPI = {};

  var _replace = function (str, vars) {
    Object.keys(vars).forEach(function (v) {
      str = str.replace(new RegExp('\\${(\\s+)?' + v + '(\\s+)?}'), vars[v]);
    });

    return str;
  };

  var _getProfile = function (userIds, callback) {
    profileDb.findSome('profile', userIds, function (err, profiles) {
      if (err) return callback(err);
      var indexedProfiles = profiles
        .map(function (v) {
          return v.doc;
        })
        .reduce(function (o, k) {
          o[k.userId] = k;
          return o;
        }, {});
      callback(null, indexedProfiles);
    });
  };

  var _sendMessage = function (message, to, profiles, callback) {
    if (!message) return callback();

    var profile = profiles[to];
    console.log(profile)
    var compiledMessage = _replace(message, { name: profile.name || profile.userName });
    var registrationIDs = {
      android: [],
      ios: []
    };
    var messageObj = {
      title: 'Pedido de amizade',
      message: compiledMessage
    };
      debugger;

    Object.keys(profile.devices).forEach(function (platform) {
      Object.keys(profile.devices[platform]).forEach(function (uuid) {
        var device = profile.devices[platform][uuid];
        registrationIDs[platform].push(device.regId || device.tokenId);
      });
    });

    async.series([
      async.apply(pushService.gcmPush, messageObj, registrationIDs.android),
      async.apply(pushService.apnPush, messageObj, registrationIDs.ios)
    ], callback);
  };

  MessagesAPI.send = function (notificationType, from, to, callback) {
    // exixts message for notificationType notification?
    if (templateMessages[notificationType]) {
      _getProfile([from, to], function (err, profiles) {
        async.parallel([
          async.apply(_sendMessage, templateMessages[notificationType].to, to, profiles),
          async.apply(_sendMessage, templateMessages[notificationType].from, from, profiles)
        ], function (err) {
          console.log('done');
        });
      });
    } else {
      callback();
    }
  };

  MessagesAPI.init = function (callback) {
    pushService.init(callback);
  };

  return MessagesAPI;
};
<commit_msg>handle error<commit_after>var _ = require('lodash');
var async = require('async');
var utils = require('hoodie-utils-plugins')('cordova-notification:messages');
var ExtendedDatabaseAPI = utils.ExtendedDatabaseAPI;

var templateMessages = {
  'requestFriend': {
    to: '${ name } quer ser seu amigo',
  },
  'acceptedFriend': {
    from: '${ name } aceitou o seu pedido de amizade'
  }
};

module.exports = function (hoodie) {
  var profileDb = new ExtendedDatabaseAPI(hoodie, hoodie.database('plugins/hoodie-plugin-profile'));
  var pushService = require('./push-service')(hoodie);
  var MessagesAPI = {};

  var _replace = function (str, vars) {
    Object.keys(vars).forEach(function (v) {
      str = str.replace(new RegExp('\\${(\\s+)?' + v + '(\\s+)?}'), vars[v]);
    });

    return str;
  };

  var _getProfile = function (userIds, callback) {
    profileDb.findSome('profile', userIds, function (err, profiles) {
      if (err) return callback(err);
      var indexedProfiles = profiles
        .map(function (v) {
          return v.doc;
        })
        .reduce(function (o, k) {
          o[k.userId] = k;
          return o;
        }, {});
      callback(null, indexedProfiles);
    });
  };

  var _sendMessage = function (message, to, profiles, callback) {
    if (!message) return callback();

    var profile = profiles[to];
    var compiledMessage = _replace(message, { name: profile.name || profile.userName });
    var registrationIDs = {
      android: [],
      ios: []
    };
    var messageObj = {
      title: 'Pedido de amizade',
      message: compiledMessage
    };

    if (profile.devices) {
      return callback();
    }

    Object.keys(profile.devices).forEach(function (platform) {
      Object.keys(profile.devices[platform]).forEach(function (uuid) {
        var device = profile.devices[platform][uuid];
        registrationIDs[platform].push(device.regId || device.tokenId);
      });
    });

    async.series([
      async.apply(pushService.gcmPush, messageObj, registrationIDs.android),
      async.apply(pushService.apnPush, messageObj, registrationIDs.ios)
    ], callback);
  };

  MessagesAPI.send = function (notificationType, from, to, callback) {
    // exixts message for notificationType notification?
    if (templateMessages[notificationType]) {
      _getProfile([from, to], function (err, profiles) {
        async.parallel([
          async.apply(_sendMessage, templateMessages[notificationType].to, to, profiles),
          async.apply(_sendMessage, templateMessages[notificationType].from, from, profiles)
        ], function (err) {
          console.log('done');
        });
      });
    } else {
      callback();
    }
  };

  MessagesAPI.init = function (callback) {
    pushService.init(callback);
  };

  return MessagesAPI;
};
<|endoftext|>


<commit_before>'use strict';

const rRepoURL = /^(?:(?:git|https?|git\+https|git\+ssh):\/\/)?(?:[^@]+@)?([^\/]+?)[\/:](.+?)\.git$/; // eslint-disable-line no-useless-escape
const rGithubPage = /\.github\.(io|com)$/;

function parseRepo(repo) {
  const split = repo.split(',');
  const url = split.shift();
  let branch = split[0];

  if (!branch && rRepoURL.test(url)) {
    const match = url.match(rRepoURL);
    const host = match[1];
    const path = match[2];

    if (host === 'github.com') {
      branch = rGithubPage.test(path) ? 'master' : 'gh-pages';
    } else if (host === 'coding.net') {
      branch = 'coding-pages';
    }
  }

  return {
    url: url,
    branch: branch || 'master'
  };
}

module.exports = function(args) {
  const repo = args.repo || args.repository;
  if (!repo) throw new TypeError('repo is required!');

  if (typeof repo === 'string') {
    const data = parseRepo(repo);
    data.branch = args.branch || data.branch;

    return [data];
  }

  const result = [];
  const keys = Object.keys(repo);

  for (let i = 0, len = keys.length; i < len; i++) {
    result.push(parseRepo(repo[keys[i]]));
  }

  return result;
};
<commit_msg>refactor: array.map()<commit_after>'use strict';

const rRepoURL = /^(?:(?:git|https?|git\+https|git\+ssh):\/\/)?(?:[^@]+@)?([^\/]+?)[\/:](.+?)\.git$/; // eslint-disable-line no-useless-escape
const rGithubPage = /\.github\.(io|com)$/;

function parseRepo(repo) {
  const split = repo.split(',');
  const url = split.shift();
  let branch = split[0];

  if (!branch && rRepoURL.test(url)) {
    const match = url.match(rRepoURL);
    const host = match[1];
    const path = match[2];

    if (host === 'github.com') {
      branch = rGithubPage.test(path) ? 'master' : 'gh-pages';
    } else if (host === 'coding.net') {
      branch = 'coding-pages';
    }
  }

  return {
    url: url,
    branch: branch || 'master'
  };
}

module.exports = function(args) {
  const repo = args.repo || args.repository;
  if (!repo) throw new TypeError('repo is required!');

  if (typeof repo === 'string') {
    const data = parseRepo(repo);
    data.branch = args.branch || data.branch;

    return [data];
  }

  const result = Object.keys(repo).map(key => {
    return parseRepo(repo[key]);
  });

  return result;
};
<|endoftext|>


<commit_before>//
// BEGIN LICENSE BLOCK
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Raül Pérez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// END LICENSE BLOCK
//

var child = require('child_process');
var childsync = require('execSync');

/**
 * @namespace bashprompt.partials.git
 */
var git = {};

/**
 * Get the branch name of a Git repository asynchronously.
 *
 * {@link bashprompt.partials.git.branchInfo}
 *
 * @param callback {function} - Function to execute once info is retrieved.
 */
git.branchInfo = function (callback) {
    'use strict';

    var cmd = 'git status -sb --ignore-submodules';

    child.exec(cmd, function (err, stdout, stderr) {

        // Check for errors
        if (err || !stdout) { return callback(err); }

        // Supprocess results all lines
        var lines = stdout.trim().split('\n');

        // First line ( it contains branch name )
        var status = lines.shift().trim();

        // Get the branch name
        var matches = status.match(/^## ([A-Za-z0-9.-]+)/);
        if (matches) { branchInfo.name = matches[1]; }

        callback(branchInfo);
    });
};

/**
 * Get the branch name of a Git repository synchronously.
 *
 * {@link bashprompt.partials.git.branchInfoSync}
 *
 * @returns {branchInfo} - Current branch info.
 */
git.branchInfoSync = function () {

    'use strict';

    var cmd = 'git status -sb --ignore-submodules';

    var branchInfo = childsync.exec(cmd);

    // Check if error code > 0. Means that has occurred an error!
    if (branchInfo.code>0) { return branchInfo; }

    // Supprocess results all lines
    var lines = branchInfo.stdout.trim().split('\n');

    // First line ( it contains branch name )
    var status = lines.shift().trim();

    // Get the branch name
    var matches = status.match(/^## ([A-Za-z0-9.-]+)/);
    if (matches) { branchInfo.name = matches[1]; }

    return branchInfo;
};

/** @module bashprompt/partials/git */
module.exports = git;
<commit_msg>stub for pending and untracked changes on git partial<commit_after>//
// BEGIN LICENSE BLOCK
//
// The MIT License (MIT)
//
// Copyright (c) 2014 Raül Pérez
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// END LICENSE BLOCK
//

var childsync = require('execSync');

function getBranchName(status) {
    'use strict';
    var name = '';
    var matches = status.match(/^## ([A-Za-z0-9.-]+)/);
    if (matches) { name = matches[1]; }
    return name;
}

function hasPendingCommits(lines) {
    'use strict';
    // TODO
    // Check for pending commits
    return false;
}

function hasUntrackedFiles(lines) {
    'use strict';
    // TODO
    // Check for untracked files
    return false;
}

exports.branchInfoSync = function () {

    'use strict';

    var cmd = 'git status -sb --ignore-submodules';

    var branchInfo = childsync.exec(cmd);

    // Check if error code > 0. Means that has occurred an error!
    if (branchInfo.code > 0) { return branchInfo; }

    // Supprocess results all lines
    var lines = branchInfo.stdout.trim().split('\n');

    // First line ( it contains branch name )
    var status = lines.shift().trim();

    branchInfo.name = getBranchName(status);

    branchInfo.has_pending_commits = hasPendingCommits(lines);

    branchInfo.has_untracked_files = hasUntrackedFiles(lines);

    return branchInfo;
};
<|endoftext|>


<commit_before>'use strict'
var Event = require('vigour-js/lib/event')
var Property = require('../property')
var Element = require('../element')
var test = /\$vp/
var cnt = 0

function render (node, event, player) {
  let exec = this.exec
  if (exec) {
    // node fix
    if (player.ready.val === true) {// || player.ready.val === true) {
      exec.apply(this, arguments)
    }
  }
}

var VideoProperty = new Property({
  inject: [
    require('vigour-js/lib/operator/type')
  ],
  define: {
    render,
    set (val, event) {
      let type = typeof val
      if (type === 'boolean' || type === 'number' || type === 'string') {
        if (val !== this._input) {
          this._input = val
          if (event === void 0) {
            this._on.data.execInternal(this, event = new Event('data'))
            event.trigger()
          } else {
            this._on.data.execInternal(this, event)
          }
        }
      } else {
        Property.prototype.set.apply(this, arguments)
      }
    }
  },
  properties: {
    exec (val) {
      this.define({
        exec: val
      })
    }
  },
  ChildConstructor: 'Constructor'
}).Constructor

var Player = new Element({
  properties: {
    options: true,
    _interval: true,
    _timeouts: {
      val: {}
    }
  },
  // inject: require('vigour-track'),
  ChildConstructor: VideoProperty,
  define: {
    isProgress (event) {
      return test.test(event.stamp)
    },
    toggle () {
      this.play.origin.set(!this.play.val)
    },
    getNodeDelete (block, blocknode, hashed) {
      for (var id in this._timeouts) {
        clearTimeout(this._timeouts[id])
        this._timeouts[id] = null
      }
      if (this._interval) {
        clearInterval(this._interval)
        this._interval = null
      }
      this.dispose()
      this.each(function () {
      }, function (prop) {
        if (prop instanceof VideoProperty) {
          let type = typeof prop._input
          if (type === 'boolean' || type === 'number' || type === 'string') {
            delete prop._input
          }
        }
      })

      // clean up all values
      // here

      Element.prototype.getNodeDelete.apply(this, arguments)
    },
    timeout (id, fn, time) {
      if (typeof id === 'function') {
        time = fn
        fn = id
      }
      if (this._timeouts[id]) {
        clearTimeout(this._timeouts[id])
        this._timeouts[id] = null
      }
      let player = this
      let store = player.storeContext()
      this._timeouts[id] = setTimeout(function () {
        player.applyContext(store)
        fn(player)
      }, time)
    }
  },
  time: {},
  ready: {
    render (node, event, player) {
      var val = this.val
      if (val === true) {
        player.each(function (prop, key) {
        }, function (prop, key) {
          if (prop && prop.exec && key !== 'ready') {
            prop.exec(node, event, player)
          }
        })
      }
    }
  },
  play: {
    val: false,
    exec (node, e, player) {
      if (this.val) {
        if (!player._interval) {
          let store = player.storeContext()
          player._interval = setInterval(function () {
            player.applyContext(store)
            let time = player.getTime()
            if (time) {
              let stamp = '$vp' + (cnt++)
              let event = new Event(
                'data',
                stamp
              )
              player.time.origin.set(time, event)//, event)
              event.trigger()
            }
            // let buffer = player.getBuffer()
            // player.buffer.origin.set(buffer, event)
          }, 500)
        }
      } else {
        if (player._interval) {
          clearInterval(player._interval)
          player._interval = null
        }
      }
    },
    track: {
      data: true
    }
  },
  duration: 0,
  volume: {
    $type: { range: [ 0, 1 ] }
  },
  mute: {
    $type: 'boolean'
  },
  fullscreen: {
    $type: 'boolean'
  },
  buffer: {
    $type: { range: [ 0, 1 ] }
  },
  ad: {
    src: {
      $type: 'string'
    },
    play: {
      $type: 'boolean'
    },
    volume: {
      $type: { range: [ 0, 1 ] }
    },
    duration: {
      $type: 'number'
    },
    buffer: {
      $type: { range: [ 0, 1 ] }
    },
    canSkip: {
      $type: 'boolean'
    },
    skip: {
      $type: 'boolean'
    }
  }
})

module.exports = exports = Player.Constructor
exports.Property = VideoProperty
<commit_msg>player<commit_after>'use strict'
var Event = require('vigour-js/lib/event')
var Property = require('../property')
var Element = require('../element')
var test = /\$vp/
var cnt = 0

function render (node, event, player) {
  let exec = this.exec
  if (exec) {
    console.log('kanker:', this.key, this.val, 'ready:', player.ready.val === true)
    if (player.ready.val === true) {
      exec.apply(this, arguments)
    }
  }
}

var VideoProperty = new Property({
  inject: [
    require('vigour-js/lib/operator/type')
  ],
  define: {
    render,
    set (val, event) {
      let type = typeof val
      if (!val || type === 'boolean' || type === 'number' || type === 'string') {
        if (val !== this._input) {
          this._input = val
          if (event === void 0) {
            this._on.data.execInternal(this, event = new Event('data'))
            event.trigger()
          } else {
            this._on.data.execInternal(this, event)
          }
        }
      } else {
        Property.prototype.set.apply(this, arguments)
      }
    }
  },
  properties: {
    exec (val) {
      this.define({
        exec: val
      })
    }
  },
  ChildConstructor: 'Constructor'
}).Constructor

var Player = new Element({
  properties: {
    options: true,
    _interval: true,
    _timeouts: {
      val: {}
    }
  },
  // inject: require('vigour-track'),
  ChildConstructor: VideoProperty,
  define: {
    isProgress (event) {
      return test.test(event.stamp)
    },
    toggle () {
      this.play.origin.set(!this.play.val)
    },
    getNodeDelete (block, blocknode, hashed) {
      for (var id in this._timeouts) {
        clearTimeout(this._timeouts[id])
        this._timeouts[id] = null
      }
      if (this._interval) {
        clearInterval(this._interval)
        this._interval = null
      }
      this.dispose()
      this.each(function () {
      }, function (prop) {
        if (prop instanceof VideoProperty) {
          let type = typeof prop._input
          if (type === 'boolean' || type === 'number' || type === 'string') {
            delete prop._input
          }
        }
      })

      Element.prototype.getNodeDelete.apply(this, arguments)
    },
    timeout (id, fn, time) {
      if (typeof id === 'function') {
        time = fn
        fn = id
      }
      if (this._timeouts[id]) {
        clearTimeout(this._timeouts[id])
        this._timeouts[id] = null
      }
      let player = this
      let store = player.storeContext()
      this._timeouts[id] = setTimeout(function () {
        player.applyContext(store)
        fn(player)
      }, time)
    }
  },
  time: {},
  ready: {
    render (node, event, player) {
      var val = this.val
      if (val === true) {
        player.each(function (prop, key) {
        }, function (prop, key) {
          if (prop && prop.exec && key !== 'ready') {
            prop.exec(node, event, player)
          }
        })
      }
    }
  },
  play: {
    val: false,
    exec (node, e, player) {
      console.log('play:', this.val)
      if (this.val) {
        console.log('interval:', player._interval)
        if (!player._interval) {
          let store = player.storeContext()
          player._interval = setInterval(function () {
            player.applyContext(store)
            let time = player.getTime()
            if (time) {
              let stamp = '$vp' + (cnt++)
              let event = new Event(
                'data',
                stamp
              )
              console.log('time:', time)
              player.time.origin.set(time, event)//, event)
              event.trigger()
            }
            // let buffer = player.getBuffer()
            // player.buffer.origin.set(buffer, event)
          }, 500)
        }
      } else {
        if (player._interval) {
          clearInterval(player._interval)
          player._interval = null
        }
      }
    },
    track: {
      data: true
    }
  },
  duration: 0,
  volume: {
    $type: { range: [ 0, 1 ] }
  },
  mute: {
    $type: 'boolean'
  },
  fullscreen: {
    $type: 'boolean'
  },
  buffer: {
    $type: { range: [ 0, 1 ] }
  },
  ad: {
    src: {
      $type: 'string'
    },
    play: {
      $type: 'boolean'
    },
    volume: {
      $type: { range: [ 0, 1 ] }
    },
    duration: {
      $type: 'number'
    },
    buffer: {
      $type: { range: [ 0, 1 ] }
    },
    canSkip: {
      $type: 'boolean'
    },
    skip: {
      $type: 'boolean'
    }
  }
})

module.exports = exports = Player.Constructor
exports.Property = VideoProperty
<|endoftext|>


<commit_before>var assert = require('assert')
  , quoteMeta = require('quotemeta')
  , LEGAL_CHARS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»§'
  , CHAT_LENGTH_LIMIT = 100

module.exports = inject;

var quotedLegalChars = quoteMeta(LEGAL_CHARS);
var incomingFilter = new RegExp("([^" + quotedLegalChars + "]|§.)", 'g');
var outgoingFilter = new RegExp("([^" + quotedLegalChars + "])", 'g');

function inject(bot) {
  bot.client.on(0x03, function(packet) {
    var message = packet.message;
    var legalContent = message.replace(incomingFilter, '');
    bot.emit('message', legalContent, message);
    var match, username, content;
    if (match = legalContent.match(/^<(?:.+? )?(.+?)> (.*)$/)) {
      // spoken chat
      username = match[1];
      content = match[2];
      bot.emit('chat', username, content, message);
    } else if (match = legalContent.match(/^(?:.+? )?(.+?) whispers to you: (.*)$/)) {
      // whispered chat
      username = match[1];
      content = match[2];
      bot.emit('whisper', username, content, message);
    }
  });
  function chatWithHeader(header, message) {
    message = message.replace(outgoingFilter, '');
    var lengthLimit = CHAT_LENGTH_LIMIT - header.length;
    message.split("\n").forEach(function(subMessage) {
      if (! subMessage) return;
      var i, smallMsg;
      for (i = 0; i < subMessage.length; i += lengthLimit) {
        smallMsg = header + subMessage.substring(i, i + lengthLimit);
        bot.client.write(0x03, {message: smallMsg});
      }
    });
  }
  bot.whisper = function(username, message) {
    chatWithHeader("/tell " + username + " ", message);
  };
  bot.chat = function(message) {
    chatWithHeader("", message);
  };
}
<commit_msg>Chat messages format updated to support 1.6.2<commit_after>var assert = require('assert')
  , quoteMeta = require('quotemeta')
  , LEGAL_CHARS = ' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_abcdefghijklmnopqrstuvwxyz{|}~⌂ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø×ƒáíóúñÑªº¿®¬½¼¡«»§'
  , CHAT_LENGTH_LIMIT = 100

module.exports = inject;

var quotedLegalChars = quoteMeta(LEGAL_CHARS);
var incomingFilter = new RegExp("([^" + quotedLegalChars + "]|§.)", 'g');
var outgoingFilter = new RegExp("([^" + quotedLegalChars + "])", 'g');

function inject(bot) {
  bot.client.on(0x03, function(packet) {
    var jsonMsg, username, content;
    jsonMsg = JSON.parse(packet.message);
    bot.emit('message', jsonMsg);
    if (jsonMsg.translate.match(/^chat\./)) {
      username = jsonMsg.using[0];
      content = jsonMsg.using[1].replace(incomingFilter, '');
      bot.emit('chat', username, content, jsonMsg.translate, jsonMsg);
    }
    if (jsonMsg.translate === "commands.message.display.incoming") {
      username = jsonMsg.using[0];
      content = jsonMsg.using[1].replace(incomingFilter, '');
      bot.emit('whisper', username, content, jsonMsg.translate, jsonMsg);
    }
  });
  function chatWithHeader(header, message) {
    message = message.replace(outgoingFilter, '');
    var lengthLimit = CHAT_LENGTH_LIMIT - header.length;
    message.split("\n").forEach(function(subMessage) {
      if (! subMessage) return;
      var i, smallMsg;
      for (i = 0; i < subMessage.length; i += lengthLimit) {
        smallMsg = header + subMessage.substring(i, i + lengthLimit);
        bot.client.write(0x03, {message: smallMsg});
      }
    });
  }
  bot.whisper = function(username, message) {
    chatWithHeader("/tell " + username + " ", message);
  };
  bot.chat = function(message) {
    chatWithHeader("", message);
  };
}
<|endoftext|>


<commit_before>'use strict';

function jsonPlugin(rail, opt_options) {
  opt_options = opt_options || {};

  rail.use('buffer');

  var pluginOptions = {
    auto: opt_options.auto || false,
    max: opt_options.max || 1048576 // 1 MiB
  };

  function interceptResponse(call, options, response) {
    if (response.buffer) {
      if (response.buffer.length > pluginOptions.max) {
        call.emit('warn', 'json', 'blocked', 'max length exceeded');
      } else {
        try {
          response.json = JSON.parse(response.buffer);
        } catch (err) {
          call.emit('warn', 'json', 'failed', 'parse error');
        }
      }
    }
    call.__emit('response', response);
  }

  rail.on('plugin-response', function(call, options, response) {
    if (options.json || pluginOptions.auto &&
        response.headers['content-type'] === 'application/json') {
      rail.plugins.buffer.intercept(call);
      call.__intercept('response', interceptResponse);
    }
  });

  return pluginOptions;
}
module.exports = jsonPlugin;
<commit_msg>plugins/json: rewrite as class<commit_after>'use strict';

function JSONPlugin(rail, options) {
  if (!(this instanceof JSONPlugin)) {
    return new JSONPlugin(rail, options);
  }
  rail.use('buffer');

  this._rail = rail;

  this.auto = options.auto || false;
  this.max = options.max || 1048576; // 1 MiB

  this._setup();
}
module.exports = JSONPlugin;

JSONPlugin.prototype._setup = function() {
  var self = this;
  var rail = this._rail;

  this._rail.on('plugin-response', function(call, options, response) {
    if (options.json || self.auto &&
        response.headers['content-type'] === 'application/json') {
      self.intercept(call);
    }
  });

  this._intercept = function(call, options, response) {
    self._interceptResponse(call, options, response);
  };
};

JSONPlugin.prototype.intercept = function(call) {
  this._rail.plugins.buffer.intercept(call);
  call.__intercept('response', this._intercept);
};

JSONPlugin.prototype._interceptResponse = function(call, options, response) {
  if (response.buffer) {

    if (response.buffer.length > this.max) {
      call.emit('warn', 'json', 'blocked', 'max length exceeded');

    } else {
      try {
        response.json = JSON.parse(response.buffer);
      } catch (err) {
        call.emit('warn', 'json', 'failed', 'parse error');
      }
    }
  }

  call.__emit('response', response);
};
<|endoftext|>