<commit_before>'use strict';

module.exports = {
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true,
    },
  },
  parser: 'babel-eslint',
  env: {
    es6: true,
    browser: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:import/errors',
  ],
  plugins: [
    'babel',
    'react',
    'import',
  ],
  rules: {
    'no-cond-assign': 2,
    'no-console': 1,
    'no-debugger': 2,
    'no-irregular-whitespace': 2,
    'no-unexpected-multiline': 2,
    'no-unsafe-negation': 2,
    'valid-jsdoc': [2, {
      requireParamDescription: false,
      requireReturn: false,
      prefer: { returns: 'return' },
    }],
    curly: 2,
    'default-case': 2,
    'dot-notation': 2,
    eqeqeq: 2,
    'guard-for-in': 2,
    'no-alert': 1,
    'no-caller': 2,
    'no-empty-function': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-label': 2,
    'no-global-assign': 2,
    'no-invalid-this': 0,
    'no-labels': 2,
    'no-loop-func': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-new-func': 2,
    'no-new-wrappers': 2,
    'no-new': 2,
    'no-return-assign': 0,
    'no-throw-literal': 2,
    'no-unmodified-loop-condition': 2,
    'no-useless-concat': 2,
    'no-void': 2,
    'no-warning-comments': 1,
    'no-with': 2,
    radix: [2, 'as-needed'],
    'no-shadow': 0,
    'no-undef': 2,
    'no-undefined': 2,
    'no-unused-vars': [2, { args: 'after-used' }],
    'no-use-before-define': 2,
    'array-bracket-spacing': [2, 'never'],
    'brace-style': 2,
    camelcase: 2,
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    'consistent-this': 2,
    'eol-last': 2,
    'func-call-spacing': 2,
    indent: [2, 2, { SwitchCase: 1 }],
    'jsx-quotes': [2, 'prefer-double'],
    'key-spacing': 2,
    'keyword-spacing': 2,
    'linebreak-style': 2,
    'max-len': [2, {
      code: 120,
      tabWidth: 2,
      ignoreComments: true,
      ignoreUrls: true,
      ignoreStrings: true,
      ignoreTemplateLiterals: true,
    }],
    'new-cap': 0,
    'new-parens': 2,
    'no-array-constructor': 2,
    'no-lonely-if': 2,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    'no-nested-ternary': 2,
    'no-new-object': 2,
    'no-trailing-spaces': 2,
    'no-unneeded-ternary': 2,
    'no-whitespace-before-property': 2,
    'object-curly-spacing': 0,
    'one-var': [2, {
      var: 'never',
      let: 'never',
      const: 'never',
    }],
    'operator-linebreak': [2, 'before'],
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'as-needed'],
    quotes: [2, 'single', { allowTemplateLiterals: true }],
    semi: 0,
    'semi-spacing': 2,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, 'never'],
    'spaced-comment': [2, 'always'],
    'arrow-body-style': [2, 'as-needed'],
    'arrow-parens': [2, 'as-needed'],
    'arrow-spacing': 2,
    'constructor-super': 2,
    'generator-star-spacing': [2, 'before'],
    'no-duplicate-imports': 2,
    'no-new-symbol': 2,
    'no-this-before-super': 2,
    'no-useless-constructor': 2,
    'no-var': 2,
    'object-shorthand': [2, 'always'],
    'prefer-const': 2,
    'prefer-rest-params': 2,
    'prefer-spread': 2,
    'prefer-template': 2,
    'rest-spread-spacing': 2,
    'yield-star-spacing': [2, 'before'],
    'react/forbid-prop-types': [2, { forbid: ['any', 'array', 'object'] }],
    'react/no-children-prop': 2,
    'react/no-danger-with-children': 2,
    'react/no-deprecated': 2,
    'react/no-direct-mutation-state': 2,
    'react/no-typos': 2,
    'react/no-string-refs': 2,
    'react/no-will-update-set-state': 2,
    'react/prop-types': [2, {}],
    'react/react-in-jsx-scope': 2,
    'react/require-render-return': 2,
    'react/self-closing-comp': 2,
    'react/sort-comp': [2, {
      order: [
        'static-methods',
        'lifecycle',
        'everything-else',
        '/^render.+$/',
        'render',
      ],
    }],
    'react/jsx-boolean-value': [2, 'never'],
    'react/jsx-closing-bracket-location': [2, 'line-aligned'],
    'react/jsx-closing-tag-location': 2,
    'react/jsx-curly-spacing': [2, 'never'],
    'react/jsx-equals-spacing': [2, 'never'],
    'react/jsx-first-prop-new-line': [2, 'multiline'],
    'react/jsx-indent': [2, 2],
    'react/jsx-key': 2,
    'react/jsx-no-bind': [2, { ignoreRefs: true }],
    'react/jsx-no-duplicate-props': 2,
    'react/jsx-no-target-blank': 2,
    'react/jsx-pascal-case': 2,
    'import/no-unresolved': [2, { commonjs: true, amd: true }],
    'import/named': 2,
    'import/default': 2,
    'import/export': 2,
    'import/no-named-as-default': 2,
    'import/no-named-as-default-member': 2,
    'import/no-extraneous-dependencies': 2,
    'import/first': 2,
    'import/no-duplicates': 2,
    'import/no-namespace': 2,
    'import/extensions': [2, { js: 'never', jsx: 'never', json: 'never' }],
    'import/newline-after-import': 2,
    'import/no-named-default': 2,
    'babel/object-curly-spacing': [2, 'always'],
    'babel/no-invalid-this': 2,
    'babel/semi': 2,
  },
};
<commit_msg>Added class-methods-use-this rule<commit_after>'use strict';

module.exports = {
  parserOptions: {
    ecmaVersion: 6,
    sourceType: 'module',
    ecmaFeatures: {
      jsx: true,
      experimentalObjectRestSpread: true,
    },
  },
  parser: 'babel-eslint',
  env: {
    es6: true,
    browser: true,
    node: true,
  },
  extends: [
    'eslint:recommended',
    'plugin:react/recommended',
    'plugin:import/errors',
  ],
  plugins: [
    'babel',
    'react',
    'import',
  ],
  rules: {
    'no-cond-assign': 2,
    'no-console': 1,
    'no-debugger': 2,
    'no-irregular-whitespace': 2,
    'no-unexpected-multiline': 2,
    'no-unsafe-negation': 2,
    'valid-jsdoc': [2, {
      requireParamDescription: false,
      requireReturn: false,
      prefer: { returns: 'return' },
    }],
    'class-methods-use-this': 2,
    curly: 2,
    'default-case': 2,
    'dot-notation': 2,
    eqeqeq: 2,
    'guard-for-in': 2,
    'no-alert': 1,
    'no-caller': 2,
    'no-empty-function': 2,
    'no-extend-native': 2,
    'no-extra-bind': 2,
    'no-extra-label': 2,
    'no-global-assign': 2,
    'no-invalid-this': 0,
    'no-labels': 2,
    'no-loop-func': 2,
    'no-multi-spaces': 2,
    'no-multi-str': 2,
    'no-new-func': 2,
    'no-new-wrappers': 2,
    'no-new': 2,
    'no-return-assign': 0,
    'no-throw-literal': 2,
    'no-unmodified-loop-condition': 2,
    'no-useless-concat': 2,
    'no-void': 2,
    'no-warning-comments': 1,
    'no-with': 2,
    radix: [2, 'as-needed'],
    'no-shadow': 0,
    'no-undef': 2,
    'no-undefined': 2,
    'no-unused-vars': [2, { args: 'after-used' }],
    'no-use-before-define': 2,
    'array-bracket-spacing': [2, 'never'],
    'brace-style': 2,
    camelcase: 2,
    'comma-dangle': [2, 'always-multiline'],
    'comma-spacing': 2,
    'comma-style': 2,
    'computed-property-spacing': 2,
    'consistent-this': 2,
    'eol-last': 2,
    'func-call-spacing': 2,
    indent: [2, 2, { SwitchCase: 1 }],
    'jsx-quotes': [2, 'prefer-double'],
    'key-spacing': 2,
    'keyword-spacing': 2,
    'linebreak-style': 2,
    'max-len': [2, {
      code: 120,
      tabWidth: 2,
      ignoreComments: true,
      ignoreUrls: true,
      ignoreStrings: true,
      ignoreTemplateLiterals: true,
    }],
    'new-cap': 0,
    'new-parens': 2,
    'no-array-constructor': 2,
    'no-lonely-if': 2,
    'no-mixed-spaces-and-tabs': 2,
    'no-multiple-empty-lines': [2, { max: 2 }],
    'no-nested-ternary': 2,
    'no-new-object': 2,
    'no-trailing-spaces': 2,
    'no-unneeded-ternary': 2,
    'no-whitespace-before-property': 2,
    'object-curly-spacing': 0,
    'one-var': [2, {
      var: 'never',
      let: 'never',
      const: 'never',
    }],
    'operator-linebreak': [2, 'before'],
    'padded-blocks': [2, 'never'],
    'quote-props': [2, 'as-needed'],
    quotes: [2, 'single', { allowTemplateLiterals: true }],
    semi: 0,
    'semi-spacing': 2,
    'space-before-blocks': 2,
    'space-before-function-paren': [2, 'never'],
    'spaced-comment': [2, 'always'],
    'arrow-body-style': [2, 'as-needed'],
    'arrow-parens': [2, 'as-needed'],
    'arrow-spacing': 2,
    'constructor-super': 2,
    'generator-star-spacing': [2, 'before'],
    'no-duplicate-imports': 2,
    'no-new-symbol': 2,
    'no-this-before-super': 2,
    'no-useless-constructor': 2,
    'no-var': 2,
    'object-shorthand': [2, 'always'],
    'prefer-const': 2,
    'prefer-rest-params': 2,
    'prefer-spread': 2,
    'prefer-template': 2,
    'rest-spread-spacing': 2,
    'yield-star-spacing': [2, 'before'],
    'react/forbid-prop-types': [2, { forbid: ['any', 'array', 'object'] }],
    'react/no-children-prop': 2,
    'react/no-danger-with-children': 2,
    'react/no-deprecated': 2,
    'react/no-direct-mutation-state': 2,
    'react/no-typos': 2,
    'react/no-string-refs': 2,
    'react/no-will-update-set-state': 2,
    'react/prop-types': [2, {}],
    'react/react-in-jsx-scope': 2,
    'react/require-render-return': 2,
    'react/self-closing-comp': 2,
    'react/sort-comp': [2, {
      order: [
        'static-methods',
        'lifecycle',
        'everything-else',
        '/^render.+$/',
        'render',
      ],
    }],
    'react/jsx-boolean-value': [2, 'never'],
    'react/jsx-closing-bracket-location': [2, 'line-aligned'],
    'react/jsx-closing-tag-location': 2,
    'react/jsx-curly-spacing': [2, 'never'],
    'react/jsx-equals-spacing': [2, 'never'],
    'react/jsx-first-prop-new-line': [2, 'multiline'],
    'react/jsx-indent': [2, 2],
    'react/jsx-key': 2,
    'react/jsx-no-bind': [2, { ignoreRefs: true }],
    'react/jsx-no-duplicate-props': 2,
    'react/jsx-no-target-blank': 2,
    'react/jsx-pascal-case': 2,
    'import/no-unresolved': [2, { commonjs: true, amd: true }],
    'import/named': 2,
    'import/default': 2,
    'import/export': 2,
    'import/no-named-as-default': 2,
    'import/no-named-as-default-member': 2,
    'import/no-extraneous-dependencies': 2,
    'import/first': 2,
    'import/no-duplicates': 2,
    'import/no-namespace': 2,
    'import/extensions': [2, { js: 'never', jsx: 'never', json: 'never' }],
    'import/newline-after-import': 2,
    'import/no-named-default': 2,
    'babel/object-curly-spacing': [2, 'always'],
    'babel/no-invalid-this': 2,
    'babel/semi': 2,
  },
};
<|endoftext|>


<commit_before>var request = require('request');
var async = require('async');
var ip = require('ip');

exports.getPublicIP = function(callback) {
	var url = 'http://169.254.169.254/latest/meta-data';
	var count = 5;
	var publicIP;
	if (!callback) {
		return;
	}
	async.doWhilst(function(fn) {
		request.get(url, function(err, response, body) {
			count--;
			if (count < 0) {
				return fn('timedout');
			}
			if (!err && response.statusCode == 200) {
				console.log(body);
			} else {
				return fn(null);
			}
		});
	},
	function() {
		return !(publicIP !== undefined && ip.isV4Format(publicIP));
	},
	function(err) {
		callback(err, publicIP)
	});
};

exports.getPublicIP(function(err, ip) {
	console.log(err, ip);
});
<commit_msg>return publicip<commit_after>var request = require('request');
var async = require('async');
var ip = require('ip');

exports.getPublicIP = function(callback) {
	var url = 'http://169.254.169.254/latest/meta-data/public-ipv4';
	var count = 5;
	var publicIP;
	if (!callback) {
		return;
	}
	async.doWhilst(function(fn) {
		request.get(url, function(err, response, body) {
			count--;
			if (count < 0) {
				return fn('timedout');
			}
			if (!err && response.statusCode == 200) {
				publicIP = body;
			}
			return fn(null);
		});
	},
	function() {
		return !(publicIP !== undefined && ip.isV4Format(publicIP));
	},
	function(err) {
		callback(err, publicIP)
	});
};

exports.getPublicIP(function(err, ip) {
	console.log(err, ip);
});
<|endoftext|>


<commit_before>var thunkify = require('thunkify');
var assert = require('assert');
var usergrid = require('usergrid');

function addThunkMethods(obj, methods){
  methods.forEach(function (method) {
    console.log("method", method);
    obj.prototype[method + "T"] = thunkify(obj.prototype[method]);
  });

  return obj;
}

addThunkMethods(usergrid.client, [
  'request',
  'createGroup',
  'createEntity',
  'getEntity',
  'restoreEntity',
  'createCollection',
  'restoreCollection',
  'getFeedForUser',
  'createUserActivity',
  'createUserActivityWithEntity',
  'signup',
  'login',
  'reAuthenticateLite',
  'reAuthenticate',
  'loginFacebook',
  'getLoggedInUser'
]);

addThunkMethods(usergrid.entity, [
  'save',
  'fetch',
  'destroy',
  'connect',
  'getConnections',
  'getGroups',
  'getActivities',
  'getFollowing',
  'getFollowers',
  'getRoles',
  'getPermissions',
  'disconnect'
]);

addThunkMethods(usergrid.collection, [
  'addCollection',
  'fetch',
  'addEntity',
  'destroyEntity',
  'getEntityByUUID',
  'getNextPage',
  'getPreviousPage'
]);

addThunkMethods(usergrid.group, [
  'fetch',
  'members',
  'add',
  'remove',
  'feed',
  'createGroupActivity'
]);

module.exports = usergrid;<commit_msg>need to "fix" error handling<commit_after>var thunkify = require('thunkify');
var assert = require('assert');
var usergrid = require('usergrid');

function thunkifyFixErrors(fn, fixError){
  assert('function' == typeof fn, 'function required');

  return function(){
    var args = new Array(arguments.length);
    var ctx = this;

    for(var i = 0; i < args.length; ++i) {
      args[i] = arguments[i];
    }

    return function(done){
      var called;

      args.push(function(){
        if (called) return;
        called = true;

        var fixedArgs = fixError(arguments);
        done.apply(null, arguments);
      });

      try {
        fn.apply(ctx, args);
      } catch (err) {
        done(err);
      }
    }
  }
};

function fixErrors(args) {
  if (args['0'] == true && (args['1']||{}).error) {
    var error = new Error(args['1'].error_description);
    error.error = args['1'];
    args['0'] = error;

    return args;
  } else {
    return args;
  }
};

function addThunkMethods(obj, methods){
  methods.forEach(function (method) {
    console.log("method", method);
    //obj.prototype[method + "T"] = thunkify(obj.prototype[method]);
    obj.prototype[method + "T"] = thunkifyFixErrors(obj.prototype[method], fixErrors);
  });

  return obj;
};

addThunkMethods(usergrid.client, [
  'request',
  'createGroup',
  'createEntity',
  'getEntity',
  'restoreEntity',
  'createCollection',
  'restoreCollection',
  'getFeedForUser',
  'createUserActivity',
  'createUserActivityWithEntity',
  'signup',
  'login',
  'reAuthenticateLite',
  'reAuthenticate',
  'loginFacebook',
  'getLoggedInUser'
]);

addThunkMethods(usergrid.entity, [
  'save',
  'fetch',
  'destroy',
  'connect',
  'getConnections',
  'getGroups',
  'getActivities',
  'getFollowing',
  'getFollowers',
  'getRoles',
  'getPermissions',
  'disconnect'
]);

addThunkMethods(usergrid.collection, [
  'addCollection',
  'fetch',
  'addEntity',
  'destroyEntity',
  'getEntityByUUID',
  'getNextPage',
  'getPreviousPage'
]);

addThunkMethods(usergrid.group, [
  'fetch',
  'members',
  'add',
  'remove',
  'feed',
  'createGroupActivity'
]);

module.exports = usergrid;<|endoftext|>


<commit_before>'use strict';

/**
 * Simplified http request.
 * (C) 2013-2014 MediaSmart Mobile.
 */

// requires
require('prototypes');
var http = require('http');
var https = require('https');

/**
 * Access a URL, send to callback. Parameters:
 *	- url: the URL to access.
 *	- callback(error, body): error is null only if result is 200.
 *		If there is an error, the body can contain the following attributes:
 *		- statusCode: if status code is not 200.
 *		- readingResponse: if response could not be read.
 */
exports.get = function(url, callback)
{
	var finished = false;
	var protocol = http;
	if (url.startsWith('https'))
	{
		protocol = https;
	}
	var request = protocol.get(url, function(response)
	{
		if (response.statusCode == 301 || response.statusCode == 302)
		{
			// follow redirection
			var location = response.headers.location;
			request.abort();
			return exports.get(location, callback);
		}
		if (response.statusCode != 200)
		{
			finished = true;
			request.abort();
			return callback('Invalid status code ' + response.statusCode, {statusCode: response.statusCode});
		}
		var body = '';
		response.on('data', function (chunk)
		{
			body += chunk;
		});
		response.on('error', function(error)
		{
			finished = true;
			return callback('Error reading response: ' + error, {readingResponse: true});
		});
		response.on('end', function()
		{
			if (finished)
			{
				return;
			}
			request.end();
			return callback(null, body);
		});
	});

};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	console.log('Use in your code as:');
	console.log('  request.get(url, function(error, body) {});');
}

<commit_msg>Added user agent to request.<commit_after>'use strict';

/**
 * Simplified http request.
 * (C) 2013-2014 MediaSmart Mobile.
 */

// requires
require('prototypes');
var http = require('http');
var https = require('https');
var urlLib = require('url');

/**
 * Access a URL, send to callback. Parameters:
 *	- url: the URL to access.
 *	- callback(error, body): error is null only if result is 200.
 *		If there is an error, the body can contain the following attributes:
 *		- statusCode: if status code is not 200.
 *		- readingResponse: if response could not be read.
 */
exports.get = function(url, callback)
{
	var finished = false;
	var protocol = http;
	if (url.startsWith('https'))
	{
		protocol = https;
	}
	var options = urlLib.parse(url);
	options.headers = {
		'user-agent': 'node.js basic-request bot',
	};
	var request = protocol.get(options, function(response)
	{
		if (response.statusCode == 301 || response.statusCode == 302)
		{
			// follow redirection
			var location = response.headers.location;
			request.abort();
			return exports.get(location, callback);
		}
		if (response.statusCode != 200)
		{
			finished = true;
			request.abort();
			return callback('Invalid status code ' + response.statusCode, {statusCode: response.statusCode});
		}
		var body = '';
		response.on('data', function (chunk)
		{
			body += chunk;
		});
		response.on('error', function(error)
		{
			finished = true;
			return callback('Error reading response: ' + error, {readingResponse: true});
		});
		response.on('end', function()
		{
			if (finished)
			{
				return;
			}
			request.end();
			return callback(null, body);
		});
	});

};

// run tests if invoked directly
if (__filename == process.argv[1])
{
	console.log('Use in your code as:');
	console.log('  request.get(url, function(error, body) {});');
}

<|endoftext|>


<commit_before>
var c;
var ctx;

var WIDTH = 800, HEIGHT = 300;
var TAIL_HEIGHT = 60;

function init() {
    c = document.getElementById("mainCanvas");
    c.width = WIDTH;
    c.height = HEIGHT;
    ctx = c.getContext("2d");
}

function line(x1, y1, x2, y2) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
}

// scaled so that duration 1 -> quarter note, 2 -> half note, etc.
function drawNote(x, y, duration, noteRadius) {
    noteRadius = noteRadius || 6;
    ctx.save();

    ctx.translate(x, y);
    ctx.scale(1.3, 1);

    ctx.beginPath();
    ctx.arc(0, 0, noteRadius, 0, Math.PI*2);
    ctx.closePath();

    if (duration == 1) {
        ctx.fill();
        ctx.moveTo(noteRadius, 0);
        ctx.lineTo(noteRadius, -TAIL_HEIGHT);
        ctx.stroke();
    } else if (duration == 2) {
        ctx.stroke();
        ctx.moveTo(noteRadius, 0);
        ctx.lineTo(noteRadius, -TAIL_HEIGHT);
        ctx.stroke();
    } else if (duration == 4) {
        ctx.stroke();
    }

    ctx.restore();
}

// x coordinate of leftmost end of staff
// y is the vertical position of middle c line
function Staff(x, y, length, lineGap, beatDist) {
    this.x = x;
    this.y = y;
    this.length = length;
    this.lineGap = lineGap;
    this.stepHeight = lineGap / 2;
    this.beatDist = beatDist;

    this.currentX = x;
    this.notes = [];
}

Staff.prototype.render = function() {
    var staffX = this.x;
    var staffY = this.y;

    // treble staff
    var y = staffY - this.lineGap;
    for (var i = 0; i < 5; i++) {
        line(staffX, y, staffX + this.length, y);
        y -= this.lineGap;
    }

    y = staffY + this.lineGap;
    for (i = 0; i < 5; i++) {
        line(staffX, y, staffX + this.length, y);
        y += this.lineGap;
    }
    var noteRadius = this.stepHeight;
    this.notes.map(function(note, i) {
        drawNote( note.x, note.y, note.duration, noteRadius );
    });
};

// numerical indices, octave 0 note 0 is middle c, note 0 is always c, note 1 is d and so on
Staff.prototype.addNote = function(octave, note, duration) {
    var offset = (octave * 7 * this.stepHeight) + note * this.stepHeight;
    this.notes.push({
        x: this.currentX,
        y: this.y - offset,
        duration: duration
    });

    this.currentX += this.beatDist * duration;
};

init();
var staff = new Staff(25, 150, 750, 20, 50);

staff.addNote(0, 0, 1); // C
staff.addNote(0, 1, 1); // D
staff.addNote(0, 2, 1); // E
staff.addNote(0, 3, 1); // F
staff.addNote(0, 4, 1); // G
staff.addNote(0, 5, 1); // A
staff.addNote(0, 6, 1); // B

staff.addNote(-1, 7, 1);
staff.addNote(-1, 6, 1);
staff.addNote(-1, 5, 1);
staff.addNote(-1, 4, 1);
staff.addNote(-1, 3, 1);
staff.addNote(-1, 2, 1);
staff.addNote(-1, 1, 1);

staff.render();
<commit_msg>add logic for animation loop, though still static<commit_after>
var c;
var ctx;
var staff;

var WIDTH = 800, HEIGHT = 300;
var TAIL_HEIGHT = 60;

function init() {
    c = document.getElementById("mainCanvas");
    c.width = WIDTH;
    c.height = HEIGHT;
    ctx = c.getContext("2d");

    staff = new Staff(25, 150, 750, 20, 50);

    staff.addNote(0, 0, 1); // C
    staff.addNote(0, 1, 1); // D
    staff.addNote(0, 2, 1); // E
    staff.addNote(0, 3, 1); // F
    staff.addNote(0, 4, 1); // G
    staff.addNote(0, 5, 1); // A
    staff.addNote(0, 6, 1); // B

    staff.addNote(-1, 7, 1);
    staff.addNote(-1, 6, 1);
    staff.addNote(-1, 5, 1);
    staff.addNote(-1, 4, 1);
    staff.addNote(-1, 3, 1);
    staff.addNote(-1, 2, 1);
    staff.addNote(-1, 1, 1);

    staff.processNote();
    staff.processNote();

    loop();
}

//document.body.onkeyup = function(e){
    //if(e.keyCode == 32){
        ////your code
    //}
//}

function loop() {
    requestAnimationFrame(loop);

    ctx.clearRect( 0, 0, WIDTH, HEIGHT );
    staff.render();
}

function line(x1, y1, x2, y2) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.stroke();
}

// scaled so that duration 1 -> quarter note, 2 -> half note, etc.
function drawNote(x, y, duration, noteRadius) {
    noteRadius = noteRadius || 6;
    ctx.save();

    ctx.translate(x, y);
    ctx.scale(1.3, 1);

    ctx.beginPath();
    ctx.arc(0, 0, noteRadius, 0, Math.PI*2);
    ctx.closePath();

    if (duration == 1) {
        ctx.fill();
        ctx.moveTo(noteRadius, 0);
        ctx.lineTo(noteRadius, -TAIL_HEIGHT);
        ctx.stroke();
    } else if (duration == 2) {
        ctx.stroke();
        ctx.moveTo(noteRadius, 0);
        ctx.lineTo(noteRadius, -TAIL_HEIGHT);
        ctx.stroke();
    } else if (duration == 4) {
        ctx.stroke();
    }

    ctx.restore();
}

// x coordinate of leftmost end of staff
// y is the vertical position of middle c line
function Staff(x, y, length, lineGap, beatDist) {
    this.x = x;
    this.y = y;
    this.length = length;
    this.lineGap = lineGap;
    this.stepHeight = lineGap / 2;
    this.beatDist = beatDist;

    this.currentX = x;
    this.notes = [];
    this.activeNote = 0;
}

Staff.prototype.render = function() {
    var staffX = this.x;
    var staffY = this.y;

    // treble staff
    var y = staffY - this.lineGap;
    for (var i = 0; i < 5; i++) {
        line(staffX, y, staffX + this.length, y);
        y -= this.lineGap;
    }

    // bass staff
    y = staffY + this.lineGap;
    for (i = 0; i < 5; i++) {
        line(staffX, y, staffX + this.length, y);
        y += this.lineGap;
    }

    // draw notes
    var noteRadius = this.stepHeight;
    var activeIndex = this.activeNote;
    this.notes.map(function(note, i) {
        if (activeIndex == i) {
            ctx.save();
            ctx.fillStyle = "rgb(255,165,0)";
            ctx.strokeStyle = "rgb(255,165,0)";
        }

        drawNote( note.x, note.y, note.duration, noteRadius );

        if (activeIndex == i) {
            ctx.restore();
        }
    });
};

// numerical indices, octave 0 note 0 is middle c, note 0 is always c, note 1 is d and so on
Staff.prototype.addNote = function(octave, note, duration) {
    var offset = (octave * 7 * this.stepHeight) + note * this.stepHeight;
    this.notes.push({
        x: this.currentX,
        y: this.y - offset,
        duration: duration
    });

    this.currentX += this.beatDist * duration;
};

Staff.prototype.processNote = function() {
    this.activeNote++;
};

init();
<|endoftext|>


<commit_before>/* eslint-env node */
'use strict';

var path = require('path');
var stew = require('broccoli-stew');
var writeFile = require('broccoli-file-creator');
var version = require('./package.json').version;

module.exports = {
  name: 'ember-pouch',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    var bowerDeps = this.project.bowerDependencies();

    if (bowerDeps['pouchdb']) {this.ui.writeWarnLine('Please remove `pouchdb` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
    if (bowerDeps['relational-pouch']) {this.ui.writeWarnLine('Please remove `relational-pouch` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
    if (bowerDeps['pouchdb-find']) {this.ui.writeWarnLine('Please remove `pouchdb-find` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
  },

  treeForVendor: function() {
    var pouchdb = stew.find(path.join(path.dirname(require.resolve('pouchdb')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.js']
    });

    var relationalPouch = stew.find(path.join(path.dirname(require.resolve('relational-pouch')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.relational-pouch.js']
    });

    var pouchdbFind = stew.find(path.join(path.dirname(require.resolve('pouchdb')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.find.js']
    });

    var shims = stew.find(__dirname + '/vendor/pouchdb', {
      destDir: 'pouchdb',
      files: ['shims.js']
    });

    var content = "Ember.libraries.register('Ember Pouch', '" + version + "');";
    var registerVersionTree = writeFile(
      'ember-pouch/register-version.js',
      content
    );

    return stew.find([
      pouchdb,
      relationalPouch,
      pouchdbFind,
      shims,
      registerVersionTree
    ]);
  },

  included(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    app.import('vendor/pouchdb/pouchdb.js');
    app.import('vendor/pouchdb/pouchdb.relational-pouch.js');
    app.import('vendor/pouchdb/pouchdb.find.js');
    app.import('vendor/pouchdb/shims.js', {
      exports: { 'pouchdb': [ 'default' ]}
    });
    app.import('vendor/ember-pouch/register-version.js');
  }
};
<commit_msg>Add warning for old `dontsavehasmany` use<commit_after>/* eslint-env node */
'use strict';

var path = require('path');
var stew = require('broccoli-stew');
var writeFile = require('broccoli-file-creator');
var version = require('./package.json').version;

module.exports = {
  name: 'ember-pouch',

  init: function() {
    this._super.init && this._super.init.apply(this, arguments);

    var bowerDeps = this.project.bowerDependencies();

    if (bowerDeps['pouchdb']) {this.ui.writeWarnLine('Please remove `pouchdb` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
    if (bowerDeps['relational-pouch']) {this.ui.writeWarnLine('Please remove `relational-pouch` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
    if (bowerDeps['pouchdb-find']) {this.ui.writeWarnLine('Please remove `pouchdb-find` from `bower.json`. As of ember-pouch 4.2.0, only the NPM package is needed.');}
  },

  treeForVendor: function() {
    var pouchdb = stew.find(path.join(path.dirname(require.resolve('pouchdb')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.js']
    });

    var relationalPouch = stew.find(path.join(path.dirname(require.resolve('relational-pouch')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.relational-pouch.js']
    });

    var pouchdbFind = stew.find(path.join(path.dirname(require.resolve('pouchdb')), '..', 'dist'), {
      destDir: 'pouchdb',
      files: ['pouchdb.find.js']
    });

    var shims = stew.find(__dirname + '/vendor/pouchdb', {
      destDir: 'pouchdb',
      files: ['shims.js']
    });

    var content = "Ember.libraries.register('Ember Pouch', '" + version + "');";
    var registerVersionTree = writeFile(
      'ember-pouch/register-version.js',
      content
    );

    return stew.find([
      pouchdb,
      relationalPouch,
      pouchdbFind,
      shims,
      registerVersionTree
    ]);
  },

  included(app) {
    this._super.included.apply(this, arguments);

    // see: https://github.com/ember-cli/ember-cli/issues/3718
    if (typeof app.import !== 'function' && app.app) {
      app = app.app;
    }

    app.import('vendor/pouchdb/pouchdb.js');
    app.import('vendor/pouchdb/pouchdb.relational-pouch.js');
    app.import('vendor/pouchdb/pouchdb.find.js');
    app.import('vendor/pouchdb/shims.js', {
      exports: { 'pouchdb': [ 'default' ]}
    });
    app.import('vendor/ember-pouch/register-version.js');

    let env = this.project.config(app.env);
    if (env.emberpouch) {
      if (env.emberpouch.hasOwnProperty('dontsavehasmany')) {
        this.ui.writeWarnLine('The `dontsavehasmany` flag is no longer needed in `config/environment.js`');
      }
    }
  }
};
<|endoftext|>


<commit_before>const async = require('async')
const Github = require('github')
const express = require('express')
const bodyParser = require('body-parser')
const semver = require('semver')
const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec

const app = express()
app.use(bodyParser.json())
app.set('etag', false)

function noop (returnValue) {
  return function (owner, repo, callback) {
    callback(null, returnValue)
  }
}

const cache = {}
app.get('/:owner/:repo', function (req, res, next) {
  const { owner, repo } = req.params
  const isOutdated = cache[req.path]
  let fn = noop(isOutdated)

  if (typeof isOutdated === 'undefined') {
    fn = checkDependencies
  }

  fn(owner, repo, function (err, isOutdated) {
    if (err) {
      return next(err)
    }

    const badgeName = isOutdated ? 'outdated' : 'uptodate'
    let badgePath = path.join(__dirname, './badges')
    badgePath = path.join(badgePath, badgeName) + '.svg'

    res.set('Connection', 'close')
    res.set('Content-Type', 'image/svg+xml')
    res.set('Cache-Control', 'no-cache')
    fs.createReadStream(badgePath).pipe(res)
  })
})

function checkDependencies (owner, repo, callback) {
  function downloadPackage(callback) {
    const github = new Github()

    github.authenticate({
      type: 'token',
      token: process.env.GH_TOKEN
    })

    github.repos.getContent({
      owner: owner,
      repo: repo,
      path: 'package.json'
    }, callback)
  }

  function parsePackage(file, callback) {
    let pkg = new Buffer(file.content, file.encoding)
    pkg = pkg.toString('ascii')

    try {
      callback(null, JSON.parse(pkg))
    } catch(err) {
      callback(err)
    }
  }

  function getLatestVersions (pkg, callback) {
    let dependencies = Object.assign({}, pkg.dependencies)
    dependencies = Object.assign(dependencies, pkg.devDependencies)

    async.mapValues(dependencies, function (version, name, cb) {
      exec(`npm info ${name}@latest version`, function (err, latest) {
        if (err) {
          return cb(err)
        }

        cb(null, {
          current: version,
          latest: latest.trim()
        })
      })
    }, callback)
  }

  function filterOutdated (packages, callback) {
    const outdated = Object.keys(packages).filter(function (pkg) {
      pkg = packages[pkg]
      return !semver.satisfies(pkg.latest, pkg.current)
    })

    callback(null, !!outdated.length)
  }

  function setCache (isOutdated, cb) {
    cache[`/${owner}/${repo}`] = isOutdated
    cb(null, isOutdated)
  }

  async.waterfall([
    downloadPackage,
    parsePackage,
    getLatestVersions,
    filterOutdated,
    setCache
  ], callback || function (err) {
    if (err) {
      console.log(err)
    }
  })
}

app.post('/commit', function (req, res, next) {
  res.status(202).json({})
  const repository = req.body.repository
  checkDependencies(repository.owner.login, repository.name)
})

app.listen(process.env.PORT || 3000)
<commit_msg>heroku deploy<commit_after>const async = require('async')
const Github = require('github')
const express = require('express')
const bodyParser = require('body-parser')
const semver = require('semver')
const fs = require('fs')
const path = require('path')
const exec = require('child_process').exec

const app = express()
app.use(bodyParser.json())
app.set('etag', false)

function noop (returnValue) {
  return function (owner, repo, callback) {
    callback(null, returnValue)
  }
}

const cache = {}
app.get('/:owner/:repo', function (req, res, next) {
  const { owner, repo } = req.params
  const isOutdated = cache[req.path]
  let fn = noop(isOutdated)

  if (typeof isOutdated === 'undefined') {
    fn = checkDependencies
  }

  fn(owner, repo, function (err, isOutdated) {
    if (err) {
      return next(err)
    }

    const badgeName = isOutdated ? 'outdated' : 'uptodate'
    let badgePath = path.join(__dirname, './badges')
    badgePath = path.join(badgePath, badgeName) + '.svg'

    res.set('Connection', 'close')
    res.set('Content-Type', 'image/svg+xml')
    res.set('Cache-Control', 'no-cache')
    fs.createReadStream(badgePath).pipe(res)
  })
})

function checkDependencies (owner, repo, callback) {
  console.log(owner, repo)

  function downloadPackage(callback) {
    const github = new Github()

    github.authenticate({
      type: 'token',
      token: process.env.GH_TOKEN
    })

    github.repos.getContent({
      owner: owner,
      repo: repo,
      path: 'package.json'
    }, callback)
  }

  function parsePackage(file, callback) {
    let pkg = new Buffer(file.content, file.encoding)
    pkg = pkg.toString('ascii')

    try {
      callback(null, JSON.parse(pkg))
    } catch(err) {
      callback(err)
    }
  }

  function getLatestVersions (pkg, callback) {
    let dependencies = Object.assign({}, pkg.dependencies)
    dependencies = Object.assign(dependencies, pkg.devDependencies)

    async.mapValues(dependencies, function (version, name, cb) {
      exec(`npm info ${name}@latest version`, function (err, latest) {
        if (err) {
          return cb(err)
        }

        cb(null, {
          current: version,
          latest: latest.trim()
        })
      })
    }, callback)
  }

  function filterOutdated (packages, callback) {
    const outdated = Object.keys(packages).filter(function (pkg) {
      pkg = packages[pkg]
      return !semver.satisfies(pkg.latest, pkg.current)
    })

    callback(null, !!outdated.length)
  }

  function setCache (isOutdated, cb) {
    cache[`/${owner}/${repo}`] = isOutdated
    cb(null, isOutdated)
  }

  async.waterfall([
    downloadPackage,
    parsePackage,
    getLatestVersions,
    filterOutdated,
    setCache
  ], callback || function (err) {
    if (err) {
      console.log(err)
    }
  })
}

app.post('/commit', function (req, res, next) {
  res.status(202).json({})
  const repository = req.body.repository
  checkDependencies(repository.owner.login, repository.name)
})

app.listen(process.env.PORT || 3000)
<|endoftext|>


<commit_before>'use strict';

var getYouTubeID = require('get-youtube-id');

module.exports = function(url){
  var id = getYouTubeID(url);

  if(!id && url.length === 11){
    id = url
  }

  return {
    default: {
      url: 'http://img.youtube.com/vi/' + id + '/default.jpg',
      width: 120,
      height: 90
    },
    medium: {
      url: 'http://img.youtube.com/vi/' + id + '/mqdefault.jpg',
      width: 320,
      height: 180
    },
    high: {
      url: 'http://img.youtube.com/vi/' + id + '/hqdefault.jpg',
      width: 480,
      height: 360
    },
  }
};
<commit_msg>Wrap "default" property in quotes<commit_after>'use strict';

var getYouTubeID = require('get-youtube-id');

module.exports = function(url){
  var id = getYouTubeID(url);

  if(!id && url.length === 11){
    id = url
  }

  return {
    'default': {
      url: 'http://img.youtube.com/vi/' + id + '/default.jpg',
      width: 120,
      height: 90
    },
    medium: {
      url: 'http://img.youtube.com/vi/' + id + '/mqdefault.jpg',
      width: 320,
      height: 180
    },
    high: {
      url: 'http://img.youtube.com/vi/' + id + '/hqdefault.jpg',
      width: 480,
      height: 360
    },
  }
};
<|endoftext|>


<commit_before>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})

controller.on('slash_command', function (slashCommand, message) {

    switch (message.command) {
        case "/afk": //handle the `/echo` slash command. We might have others assigned to this app too!
            // The rules are simple: If there is no text following the command, treat it as though they had requested "help"
            // Otherwise just echo back to them what they sent us.

            // but first, let's make sure the token matches!
            if (message.token !== process.env.VERIFICATION_TOKEN) return; //just ignore it.

            // if no text was supplied, treat it as a help command
            if (message.text === "" || message.text === "help") {
                slashCommand.replyPrivate(message,
                    "I echo back what you tell me. " +
                    "Try typing `/echo hello` to see.");
                return;
            }

            // If we made it here, just echo what the user typed back at them
            //TODO You do it!
            slashCommand.replyPublic(message, "1", function() {
                slashCommand.replyPublicDelayed(message, "2").then(slashCommand.replyPublicDelayed(message, "3"));
            });

            break;
        default:
            slashCommand.replyPublic(message, "I'm afraid I don't know how to " + message.command + " yet.");

    }

});
<commit_msg>fix whitespace<commit_after>var Botkit = require('botkit')

var token = process.env.SLACK_TOKEN

var controller = Botkit.slackbot({
  // reconnect to Slack RTM when connection goes bad
  retry: Infinity,
  debug: false
})

// Assume single team mode if we have a SLACK_TOKEN
if (token) {
  console.log('Starting in single-team mode')
  controller.spawn({
    token: token
  }).startRTM(function (err, bot, payload) {
    if (err) {
      throw new Error(err)
    }

    console.log('Connected to Slack RTM')
  })
// Otherwise assume multi-team mode - setup beep boop resourcer connection
} else {
  console.log('Starting in Beep Boop multi-team mode')
  require('beepboop-botkit').start(controller, { debug: true })
}

controller.on('bot_channel_join', function (bot, message) {
  bot.reply(message, "I'm here!")
})

controller.hears(['hello', 'hi'], ['direct_mention'], function (bot, message) {
  bot.reply(message, 'Hello.')
})

controller.hears(['hello', 'hi'], ['direct_message'], function (bot, message) {
  bot.reply(message, 'Hello.')
  bot.reply(message, 'It\'s nice to talk to you directly.')
})

controller.hears('.*', ['mention'], function (bot, message) {
  bot.reply(message, 'You really do care about me. :heart:')
})

controller.hears('help', ['direct_message', 'direct_mention'], function (bot, message) {
  var help = 'I will respond to the following messages: \n' +
      '`bot hi` for a simple message.\n' +
      '`bot attachment` to see a Slack attachment message.\n' +
      '`@<your bot\'s name>` to demonstrate detecting a mention.\n' +
      '`bot help` to see this again.'
  bot.reply(message, help)
})

controller.hears(['attachment'], ['direct_message', 'direct_mention'], function (bot, message) {
  var text = 'Beep Beep Boop is a ridiculously simple hosting platform for your Slackbots.'
  var attachments = [{
    fallback: text,
    pretext: 'We bring bots to life. :sunglasses: :thumbsup:',
    title: 'Host, deploy and share your bot in seconds.',
    image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
    title_link: 'https://beepboophq.com/',
    text: text,
    color: '#7CD197'
  }]

  bot.reply(message, {
    attachments: attachments
  }, function (err, resp) {
    console.log(err, resp)
  })
})

controller.hears('.*', ['direct_message', 'direct_mention'], function (bot, message) {
  bot.reply(message, 'Sorry <@' + message.user + '>, I don\'t understand. \n')
})

controller.on('slash_command', function (slashCommand, message) {

    switch (message.command) {
        case "/afk": //handle the `/echo` slash command. We might have others assigned to this app too!
            // The rules are simple: If there is no text following the command, treat it as though they had requested "help"
            // Otherwise just echo back to them what they sent us.

            // but first, let's make sure the token matches!
            if (message.token !== process.env.VERIFICATION_TOKEN) return; //just ignore it.

            // if no text was supplied, treat it as a help command
            if (message.text === "" || message.text === "help") {
                slashCommand.replyPrivate(message,
                    "I echo back what you tell me. " +
                    "Try typing `/echo hello` to see.");
                return;
            }

            // If we made it here, just echo what the user typed back at them
            //TODO You do it!
            slashCommand.replyPublic(message, "1", function() {
                slashCommand.replyPublicDelayed(message, "2").then(slashCommand.replyPublicDelayed(message, "3"));
            });

            break;
        default:
            slashCommand.replyPublic(message, "I'm afraid I don't know how to " + message.command + " yet.");
    }

});
<|endoftext|>


<commit_before>var widget = uploadcare.Widget('[role=uploadcare-uploader]');

function resize() {
    JFCustomWidget.requestFrameResize({
        width: 618,
        height: 500
    });
}

JFCustomWidget.subscribe('ready', function(){
    widget.onDialogOpen(function(){
        resize();
    });

    uploadcare.start({
      publicKey: 'demopublickey'
    });
});
<commit_msg>fix resize<commit_after>var widget = uploadcare.Widget('[role=uploadcare-uploader]');

function resize(w, h) {
    JFCustomWidget.requestFrameResize({
        width: w,
        height: h
    });
}

JFCustomWidget.subscribe('ready', function(){
    widget.onDialogOpen(function(dialog){
        resize(618, 500);

        dialog.always(function() {
            resize(300, 35);
        });
    });

    uploadcare.start({
      publicKey: 'demopublickey'
    });
});
<|endoftext|>


<commit_before>import "bootstrap/dist/css/bootstrap.min"
import "font-awesome/css/font-awesome.min"
import "./style/style.default"
import "./style"
import FontFaceObserver from 'fontfaceobserver'

const font = new FontFaceObserver('Open Sans')
font.load().then(console.log('Open Sans loaded!'))

import App from './components/App'

export default () => <App />;
<commit_msg>watch for specific weights<commit_after>import "bootstrap/dist/css/bootstrap.min"
import "font-awesome/css/font-awesome.min"
import "./style/style.default"
import "./style"
import FontFaceObserver from 'fontfaceobserver'

const font = new FontFaceObserver('Open Sans', {weight: [300, 700]})
font.load().then(console.log('Open Sans loaded!'))

import App from './components/App'

export default () => <App />;
<|endoftext|>


<commit_before>/*!
 * raw-body
 * Copyright(c) 2013-2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

/**
 * Module dependencies.
 * @private
 */

var bytes = require('bytes')
var iconv = require('iconv-lite')

/**
 * Module exports.
 * @public
 */

module.exports = getRawBody

/**
 * Get the raw body of a stream (typically HTTP).
 *
 * @param {object} stream
 * @param {object|string|function} [options]
 * @param {function} [done]
 * @public
 */

function getRawBody(stream, options, done) {
  if (options === true || typeof options === 'string') {
    // short cut for encoding
    options = {
      encoding: options
    }
  }

  options = options || {}

  if (typeof options === 'function') {
    done = options
    options = {}
  }

  // get encoding
  var encoding = options.encoding !== true
    ? options.encoding
    : 'utf-8'

  // convert the limit to an integer
  var limit = null
  if (typeof options.limit === 'number')
    limit = options.limit
  if (typeof options.limit === 'string')
    limit = bytes(options.limit)

  // convert the expected length to an integer
  var length = null
  if (options.length != null && !isNaN(options.length))
    length = parseInt(options.length, 10)

  // check the length and limit options.
  // note: we intentionally leave the stream paused,
  // so users should handle the stream themselves.
  if (limit !== null && length !== null && length > limit) {
    var err = makeError('request entity too large', 'entity.too.large')
    err.status = err.statusCode = 413
    err.length = err.expected = length
    err.limit = limit
    cleanup()
    halt(stream)
    process.nextTick(function () {
      done(err)
    })
    return defer
  }

  // streams1: assert request encoding is buffer.
  // streams2+: assert the stream encoding is buffer.
  //   stream._decoder: streams1
  //   state.encoding: streams2
  //   state.decoder: streams2, specifically < 0.10.6
  var state = stream._readableState
  if (stream._decoder || (state && (state.encoding || state.decoder))) {
    // developer error
    var err = makeError('stream encoding should not be set',
      'stream.encoding.set')
    err.status = err.statusCode = 500
    cleanup()
    halt(stream)
    process.nextTick(function () {
      done(err)
    })
    return defer
  }

  var received = 0
  var decoder

  try {
    decoder = getDecoder(encoding)
  } catch (err) {
    cleanup()
    halt(stream)
    process.nextTick(function () {
      done(err)
    })
    return defer
  }

  var buffer = decoder
    ? ''
    : []

  stream.on('aborted', onAborted)
  stream.on('data', onData)
  stream.once('end', onEnd)
  stream.once('error', onEnd)
  stream.once('close', cleanup)

  return defer

  // yieldable support
  function defer(fn) {
    done = fn
  }

  function onAborted() {
    var err = makeError('request aborted', 'request.aborted')
    err.code = 'ECONNABORTED'
    err.status = 400
    err.received = received
    err.length = err.expected = length

    cleanup()
    halt(stream)
    done(err)
  }

  function onData(chunk) {
    received += chunk.length
    decoder
      ? buffer += decoder.write(chunk)
      : buffer.push(chunk)

    if (limit !== null && received > limit) {
      var err = makeError('request entity too large', 'entity.too.large')
      err.status = err.statusCode = 413
      err.received = received
      err.limit = limit
      cleanup()
      halt(stream)
      done(err)
    }
  }

  function onEnd(err) {
    if (err) {
      cleanup()
      halt(stream)
      done(err)
    } else if (length !== null && received !== length) {
      err = makeError('request size did not match content length',
        'request.size.invalid')
      err.status = err.statusCode = 400
      err.received = received
      err.length = err.expected = length
      cleanup()
      done(err)
    } else {
      var string = decoder
        ? buffer + (decoder.end() || '')
        : Buffer.concat(buffer)
      cleanup()
      done(null, string)
    }
  }

  function cleanup() {
    received = buffer = null

    stream.removeListener('aborted', onAborted)
    stream.removeListener('data', onData)
    stream.removeListener('end', onEnd)
    stream.removeListener('error', onEnd)
    stream.removeListener('close', cleanup)
  }
}

/**
 * Get the decoder for a given encoding.
 *
 * @param {string} encoding
 * @private
 */

function getDecoder(encoding) {
  if (!encoding) return null

  try {
    return iconv.getCodec(encoding).decoder()
  } catch (e) {
    var err = makeError('specified encoding unsupported', 'encoding.unsupported')
    err.status = err.statusCode = 415
    err.encoding = encoding
    throw err
  }
}

/**
 * Halt a stream.
 *
 * @param {Object} stream
 * @private
 */

function halt(stream) {
  // unpipe everything from the stream
  unpipe(stream)

  // pause stream
  if (typeof stream.pause === 'function') {
    stream.pause()
  }
}

// to create serializable errors you must re-set message so
// that it is enumerable and you must re configure the type
// property so that is writable and enumerable
function makeError(message, type) {
  var error = new Error()
  error.message = message
  Object.defineProperty(error, 'type', {
    value: type,
    enumerable: true,
    writable: true,
    configurable: true
  })
  return error
}

/**
 * Unpipe everything from a stream.
 *
 * @param {Object} stream
 * @private
 */

/* istanbul ignore next: implementation differs between versions */
function unpipe(stream) {
  if (typeof stream.unpipe === 'function') {
    // new-style
    stream.unpipe()
    return
  }

  // Node.js 0.8 hack
  var listener
  var listeners = stream.listeners('close')

  for (var i = 0; i < listeners.length; i++) {
    listener = listeners[i]

    if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
      continue
    }

    // invoke the listener
    listener.call(stream)
  }
}
<commit_msg>Refactor internal code structure<commit_after>/*!
 * raw-body
 * Copyright(c) 2013-2014 Jonathan Ong
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */

/**
 * Module dependencies.
 * @private
 */

var bytes = require('bytes')
var iconv = require('iconv-lite')

/**
 * Module exports.
 * @public
 */

module.exports = getRawBody

/**
 * Get the decoder for a given encoding.
 *
 * @param {string} encoding
 * @private
 */

function getDecoder(encoding) {
  if (!encoding) return null

  try {
    return iconv.getCodec(encoding).decoder()
  } catch (e) {
    var err = makeError('specified encoding unsupported', 'encoding.unsupported')
    err.status = err.statusCode = 415
    err.encoding = encoding
    throw err
  }
}

/**
 * Get the raw body of a stream (typically HTTP).
 *
 * @param {object} stream
 * @param {object|string|function} [options]
 * @param {function} [callback]
 * @public
 */

function getRawBody(stream, options, callback) {
  var done = callback
  var opts = options || {}

  if (options === true || typeof options === 'string') {
    // short cut for encoding
    opts = {
      encoding: options
    }
  }

  if (typeof options === 'function') {
    done = options
    opts = {}
  }

  // get encoding
  var encoding = opts.encoding !== true
    ? opts.encoding
    : 'utf-8'

  // convert the limit to an integer
  var limit = typeof opts.limit === 'number' ? opts.limit
    : typeof opts.limit === 'string' ? bytes(opts.limit)
    : null

  // convert the expected length to an integer
  var length = opts.length != null && !isNaN(opts.length)
    ? parseInt(opts.length, 10)
    : null

  readStream(stream, encoding, length, limit, function () {
    done.apply(this, arguments)
  })

  return defer

  // yieldable support
  function defer(callback) {
    done = callback
  }
}

/**
 * Halt a stream.
 *
 * @param {Object} stream
 * @private
 */

function halt(stream) {
  // unpipe everything from the stream
  unpipe(stream)

  // pause stream
  if (typeof stream.pause === 'function') {
    stream.pause()
  }
}

/**
 * Make a serializable error object.
 *
 * To create serializable errors you must re-set message so
 * that it is enumerable and you must re configure the type
 * property so that is writable and enumerable.
 *
 * @param {string} message
 * @param {string} type
 * @param {object} props
 * @private
 */

function makeError(message, type, props) {
  var error = new Error()

  for (var prop in props) {
    error[prop] = props[prop]
  }

  error.message = message

  Object.defineProperty(error, 'type', {
    value: type,
    enumerable: true,
    writable: true,
    configurable: true
  })

  return error
}

/**
 * Read the data from the stream.
 *
 * @param {object} stream
 * @param {string} encoding
 * @param {number} length
 * @param {number} limit
 * @param {function} callback
 * @public
 */

function readStream(stream, encoding, length, limit, callback) {
  // check the length and limit options.
  // note: we intentionally leave the stream paused,
  // so users should handle the stream themselves.
  if (limit !== null && length !== null && length > limit) {
    var err = makeError('request entity too large', 'entity.too.large', {
      expected: length,
      length: length,
      limit: limit,
      status: 413,
      statusCode: 413
    })

    return process.nextTick(function () {
      done(err)
    })
  }

  // streams1: assert request encoding is buffer.
  // streams2+: assert the stream encoding is buffer.
  //   stream._decoder: streams1
  //   state.encoding: streams2
  //   state.decoder: streams2, specifically < 0.10.6
  var state = stream._readableState
  if (stream._decoder || (state && (state.encoding || state.decoder))) {
    // developer error
    var err = makeError('stream encoding should not be set', 'stream.encoding.set', {
      status: 500,
      statusCode: 500
    })

    return process.nextTick(function () {
      done(err)
    })
  }

  var received = 0
  var decoder

  try {
    decoder = getDecoder(encoding)
  } catch (err) {
    return process.nextTick(function () {
      done(err)
    })
  }

  var buffer = decoder
    ? ''
    : []

  stream.on('aborted', onAborted)
  stream.on('data', onData)
  stream.once('end', onEnd)
  stream.once('error', onEnd)
  stream.once('close', cleanup)

  function done(err) {
    cleanup()

    if (err) {
      // halt the stream on error
      halt(stream)
    }

    callback.apply(this, arguments)
  }

  function onAborted() {
    done(makeError('request aborted', 'request.aborted', {
      code: 'ECONNABORTED',
      expected: length,
      length: length,
      received: received,
      status: 400,
      statusCode: 400
    }))
  }

  function onData(chunk) {
    received += chunk.length
    decoder
      ? buffer += decoder.write(chunk)
      : buffer.push(chunk)

    if (limit !== null && received > limit) {
      done(makeError('request entity too large', 'entity.too.large', {
        limit: limit,
        received: received,
        status: 413,
        statusCode: 413
      }))
    }
  }

  function onEnd(err) {
    if (err) return done(err)

    if (length !== null && received !== length) {
      done(makeError('request size did not match content length', 'request.size.invalid', {
        expected: length,
        length: length,
        received: received,
        status: 400,
        statusCode: 400
      }))
    } else {
      var string = decoder
        ? buffer + (decoder.end() || '')
        : Buffer.concat(buffer)
      cleanup()
      done(null, string)
    }
  }

  function cleanup() {
    received = buffer = null

    stream.removeListener('aborted', onAborted)
    stream.removeListener('data', onData)
    stream.removeListener('end', onEnd)
    stream.removeListener('error', onEnd)
    stream.removeListener('close', cleanup)
  }
}

/**
 * Unpipe everything from a stream.
 *
 * @param {Object} stream
 * @private
 */

/* istanbul ignore next: implementation differs between versions */
function unpipe(stream) {
  if (typeof stream.unpipe === 'function') {
    // new-style
    stream.unpipe()
    return
  }

  // Node.js 0.8 hack
  var listener
  var listeners = stream.listeners('close')

  for (var i = 0; i < listeners.length; i++) {
    listener = listeners[i]

    if (listener.name !== 'cleanup' && listener.name !== 'onclose') {
      continue
    }

    // invoke the listener
    listener.call(stream)
  }
}
<|endoftext|>


<commit_before>// # Angular-Inview
// - Author: [Nicola Peduzzi](https://github.com/thenikso)
// - Repository: https://github.com/thenikso/angular-inview
// - Install with: `bower install angular-inview`
// - Version: **2.0-alpha1**
(function() {
'use strict';

// An [angular.js](https://angularjs.org) directive to evaluate an expression if
// a DOM element is or not in the current visible browser viewport.
// Use it in your AngularJS app by including the javascript and requireing it:
//
// `angular.module('myApp', ['angular-inview'])`
angular.module('angular-inview', [])

// ## in-view directive
//
// ### Usage
// ```html
// <any in-view="{expression}" [in-view-options="{object}"]></any>
// ```
.directive('inView', ['$parse', inViewDirective])

// ## in-view-container directive
.directive('inViewContainer', inViewContainerDirective);

// ## Implementation
function inViewDirective ($parse) {
  return {
    // Evaluate the expression passet to the attribute `in-view` when the DOM
    // element is visible in the viewport.
    restrict: 'A',
    require: '?^^inViewContainer',
    link: function inViewDirectiveLink (scope, element, attrs, container) {
      // in-view-options attribute can be specified with an object expression
      // containing:
      //   - `offset`: An array of values to offset the element position.
      //     Offsets are expressed as arrays of 4 numbers [top, right, bottom, left].
      //     Like CSS, you can also specify only 2 numbers [top/bottom, left/right].
      //     Instead of numbers, some array elements can be a string with a percentage.
      //     Positive numbers are offsets outside the element rectangle and
      //     negative numbers are offsets to the inside.
      //   - `viewportOffset`: Like the element offset but appied to the viewport.
      //   - `generateDirection`: Indicate if the `direction` information should
      //     be included in `$inviewInfo` (default false).
      //   - `generateParts`: Indicate if the `parts` information should
      //     be included in `$inviewInfo` (default false).
      //  - `throttle`: Spcify a number of milliseconds by which filter the number
      //    of incoming events.
      var options = {};
      if (attrs.inViewOptions) {
        options = scope.$eval(attrs.inViewOptions);
      }
      if (options.offset) {
        options.offset = normalizeOffset(options.offset);
      }
      if (options.viewportOffset) {
        options.viewportOffset = normalizeOffset(options.viewportOffset);
      }

      // Build reactive chain from an initial event
      var viewportEventSignal = signalSingle({ type: 'initial' })

      // Merged with the window events
      .merge(signalFromEvent(window, 'scroll resize'))

      // Merge with container's events signal
      if (container) {
        viewportEventSignal = viewportEventSignal.merge(container.eventsSignal);
      }

      // Throttle if option specified
      if (options.throttle) {
        viewportEventSignal = viewportEventSignal.throttle(options.throttle);
      }

      // Map to viewport intersection and in-view informations
      var inviewInfoSignal = viewportEventSignal

      // Inview information structure contains:
      //   - `inView`: a boolean value indicating if the element is
      //     visible in the viewport;
      //   - `changed`: a boolean value indicating if the inview status
      //     changed after the last event;
      //   - `event`: the event that initiated the in-view check;
      .map(function(event) {
        var viewportRect;
        if (container) {
          viewportRect = container.getViewportRect();
          // TODO merge with actual window!
        } else {
          viewportRect = getViewportRect();
        }
        viewportRect = offsetRect(viewportRect, options.viewportOffset);
        var elementRect = offsetRect(element[0].getBoundingClientRect(), options.offset);
        var info = {
          inView: intersectRect(elementRect, viewportRect),
          event: event,
          element: element,
          elementRect: elementRect,
          viewportRect: viewportRect
        };
        // Add inview parts
        if (options.generateParts && info.inView) {
          info.parts = {};
          info.parts.top = elementRect.top >= viewportRect.top;
          info.parts.left = elementRect.left >= viewportRect.left;
          info.parts.bottom = elementRect.bottom <= viewportRect.bottom;
          info.parts.right = elementRect.right <= viewportRect.right;
        }
        return info;
      })

      // Add the changed information to the inview structure.
      .scan({}, function (lastInfo, newInfo) {
        // Add inview direction info
        if (options.generateDirection && newInfo.inView && lastInfo.elementRect) {
          newInfo.direction = {
            horizontal: newInfo.elementRect.left - lastInfo.elementRect.left,
            vertical: newInfo.elementRect.top - lastInfo.elementRect.top
          };
        }
        // Calculate changed flag
        newInfo.changed =
          newInfo.inView !== lastInfo.inView ||
          !angular.equals(newInfo.parts, lastInfo.parts) ||
          !angular.equals(newInfo.direction, lastInfo.direction);
        return newInfo;
      })

      // Filters only informations that should be forwarded to the callback
      .filter(function (info) {
        // Don't forward if no relevant infomation changed
        if (!info.changed) {
          return false;
        }
        // Don't forward if not initially in-view
        if (info.event.type === 'initial' && !info.inView) {
          return false;
        }
        return true;
      });

      // Execute in-view callback
      var inViewExpression = $parse(attrs.inView);
      var dispose = inviewInfoSignal.subscribe(function (info) {
        scope.$applyAsync(function () {
          inViewExpression(scope, {
            '$inview': info.inView,
            '$inviewInfo': info
          });
        });
      });

      // Dispose of reactive chain
      scope.$on('$destroy', dispose);
    }
  }
}

function inViewContainerDirective () {
  return {
    restrict: 'A',
    controller: function ($element) {
      this.element = $element;
      this.eventsSignal = signalFromEvent($element, 'scroll');
      this.getViewportRect = function () {
        return $element[0].getBoundingClientRect();
      };
    }
  }
}

// ## Utilities

function getViewportRect () {
  var result = {
    top: 0,
    left: 0,
    width: window.innerWidth,
    right: window.innerWidth,
    height: window.innerHeight,
    bottom: window.innerHeight
  };
  if (result.height) {
    return result;
  }
  var mode = document.compatMode;
  if (mode === 'CSS1Compat') {
    result.width = result.right = document.documentElement.clientWidth;
    result.height = result.bottom = document.documentElement.clientHeight;
  } else {
    result.width = result.right = document.body.clientWidth;
    result.height = result.bottom = document.body.clientHeight;
  }
  return result;
}

function intersectRect (r1, r2) {
  return !(r2.left > r1.right ||
           r2.right < r1.left ||
           r2.top > r1.bottom ||
           r2.bottom < r1.top);
}

function normalizeOffset (offset) {
  if (!angular.isArray(offset)) {
    throw new Error("angular-inview: Offset should be an array");
  }
  if (offset.length == 2) {
    return offset.concat(offset);
  }
  else if (offset.length == 3) {
    return offset.concat([offset[1]]);
  }
  return offset;
}

function offsetRect (rect, offset) {
  if (!offset) {
    return rect;
  }
  var offsetObject = {
    top: isPercent(offset[0]) ? (parseFloat(offset[0]) * rect.height) : offset[0],
    right: isPercent(offset[1]) ? (parseFloat(offset[1]) * rect.width) : offset[1],
    bottom: isPercent(offset[2]) ? (parseFloat(offset[2]) * rect.height) : offset[2],
    left: isPercent(offset[3]) ? (parseFloat(offset[3]) * rect.width) : offset[3]
  };
  var result = angular.copy(rect);
  result.top -= offsetObject.top;
  result.left -= offsetObject.left;
  result.bottom += offsetObject.bottom;
  result.right += offsetObject.right;
  result.height += offsetObject.top + offsetObject.bottom;
  result.width += offsetObject.left + offsetObject.right;
  return result;
}

function isPercent (n) {
  return angular.isString(n) && n.indexOf('%') > 0;
}

// ## QuickSignal FRP
// A quick and dirty implementation of Rx to have a streamlined code in the
// directives.

// ### QuickSignal
//
// - `didSubscribeFunc`: a function receiving a `subscriber` as described below
//
// Usage:
//     var mySignal = new QuickSignal(function(subscriber) { ... })
function QuickSignal (didSubscribeFunc) {
  this.didSubscribeFunc = didSubscribeFunc;
}

// Subscribe to a signal and consume the steam of data.
//
// Returns a function that can be called to stop the signal stream of data and
// perform cleanup.
//
// A `subscriber` is a function that will be called when a new value arrives.
// a `subscriber.$dispose` property can be set to a function to be called uppon
// disposal. When setting the `$dispose` function, the previously set function
// should be chained.
QuickSignal.prototype.subscribe = function (subscriber) {
  this.didSubscribeFunc(subscriber);
  var dispose = function () {
    if (subscriber.$dispose) {
      subscriber.$dispose();
      subscriber.$dispose = null;
    }
  }
  return dispose;
}

QuickSignal.prototype.map = function (f) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    subscriber.$dispose = s.subscribe(function (nextValue) {
      subscriber(f(nextValue));
    });
  });
};

QuickSignal.prototype.filter = function (f) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    subscriber.$dispose = s.subscribe(function (nextValue) {
      if (f(nextValue)) {
        subscriber(nextValue);
      }
    });
  });
};

QuickSignal.prototype.scan = function (initial, scanFunc) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    var last = initial;
    subscriber.$dispose = s.subscribe(function (nextValue) {
      last = scanFunc(last, nextValue);
      subscriber(last);
    });
  });
}

QuickSignal.prototype.merge = function (signal) {
  return signalMerge(this, signal);
};

QuickSignal.prototype.throttle = function (threshhold) {
  var s = this, last, deferTimer;
  return new QuickSignal(function (subscriber) {
    var chainDisposable = s.subscribe(function () {
      var now = +new Date,
          args = arguments;
      if (last && now < last + threshhold) {
        clearTimeout(deferTimer);
        deferTimer = setTimeout(function () {
          last = now;
          subscriber.apply(null, args);
        }, threshhold);
      } else {
        last = now;
        subscriber.apply(null, args);
      }
    });
    subscriber.$dispose = function () {
      clearTimeout(deferTimer);
      if (chainDisposable) chainDisposable();
    };
  });
};

function signalMerge () {
  var signals = arguments;
  return new QuickSignal(function (subscriber) {
    var disposables = [];
    for (var i = signals.length - 1; i >= 0; i--) {
      disposables.push(signals[i].subscribe(function () {
        subscriber.apply(null, arguments);
      }));
    }
    subscriber.$dispose = function () {
      for (var i = disposables.length - 1; i >= 0; i--) {
        if (disposables[i]) disposables[i]();
      }
    }
  });
}

// Returns a signal from DOM events of a target.
function signalFromEvent (target, event) {
  return new QuickSignal(function (subscriber) {
    var handler = function (e) {
      subscriber(e);
    };
    var el = angular.element(target);
    el.on(event, handler);
    subscriber.$dispose = function () {
      el.off(event, handler);
    };
  });
}

function signalSingle (value) {
  return new QuickSignal(function (subscriber) {
    subscriber(value);
  });
}

})();<commit_msg>Use explicit annotation in `in-view-container` directive<commit_after>// # Angular-Inview
// - Author: [Nicola Peduzzi](https://github.com/thenikso)
// - Repository: https://github.com/thenikso/angular-inview
// - Install with: `bower install angular-inview`
// - Version: **2.0-alpha1**
(function() {
'use strict';

// An [angular.js](https://angularjs.org) directive to evaluate an expression if
// a DOM element is or not in the current visible browser viewport.
// Use it in your AngularJS app by including the javascript and requireing it:
//
// `angular.module('myApp', ['angular-inview'])`
angular.module('angular-inview', [])

// ## in-view directive
//
// ### Usage
// ```html
// <any in-view="{expression}" [in-view-options="{object}"]></any>
// ```
.directive('inView', ['$parse', inViewDirective])

// ## in-view-container directive
.directive('inViewContainer', inViewContainerDirective);

// ## Implementation
function inViewDirective ($parse) {
  return {
    // Evaluate the expression passet to the attribute `in-view` when the DOM
    // element is visible in the viewport.
    restrict: 'A',
    require: '?^^inViewContainer',
    link: function inViewDirectiveLink (scope, element, attrs, container) {
      // in-view-options attribute can be specified with an object expression
      // containing:
      //   - `offset`: An array of values to offset the element position.
      //     Offsets are expressed as arrays of 4 numbers [top, right, bottom, left].
      //     Like CSS, you can also specify only 2 numbers [top/bottom, left/right].
      //     Instead of numbers, some array elements can be a string with a percentage.
      //     Positive numbers are offsets outside the element rectangle and
      //     negative numbers are offsets to the inside.
      //   - `viewportOffset`: Like the element offset but appied to the viewport.
      //   - `generateDirection`: Indicate if the `direction` information should
      //     be included in `$inviewInfo` (default false).
      //   - `generateParts`: Indicate if the `parts` information should
      //     be included in `$inviewInfo` (default false).
      //  - `throttle`: Spcify a number of milliseconds by which filter the number
      //    of incoming events.
      var options = {};
      if (attrs.inViewOptions) {
        options = scope.$eval(attrs.inViewOptions);
      }
      if (options.offset) {
        options.offset = normalizeOffset(options.offset);
      }
      if (options.viewportOffset) {
        options.viewportOffset = normalizeOffset(options.viewportOffset);
      }

      // Build reactive chain from an initial event
      var viewportEventSignal = signalSingle({ type: 'initial' })

      // Merged with the window events
      .merge(signalFromEvent(window, 'scroll resize'))

      // Merge with container's events signal
      if (container) {
        viewportEventSignal = viewportEventSignal.merge(container.eventsSignal);
      }

      // Throttle if option specified
      if (options.throttle) {
        viewportEventSignal = viewportEventSignal.throttle(options.throttle);
      }

      // Map to viewport intersection and in-view informations
      var inviewInfoSignal = viewportEventSignal

      // Inview information structure contains:
      //   - `inView`: a boolean value indicating if the element is
      //     visible in the viewport;
      //   - `changed`: a boolean value indicating if the inview status
      //     changed after the last event;
      //   - `event`: the event that initiated the in-view check;
      .map(function(event) {
        var viewportRect;
        if (container) {
          viewportRect = container.getViewportRect();
          // TODO merge with actual window!
        } else {
          viewportRect = getViewportRect();
        }
        viewportRect = offsetRect(viewportRect, options.viewportOffset);
        var elementRect = offsetRect(element[0].getBoundingClientRect(), options.offset);
        var info = {
          inView: intersectRect(elementRect, viewportRect),
          event: event,
          element: element,
          elementRect: elementRect,
          viewportRect: viewportRect
        };
        // Add inview parts
        if (options.generateParts && info.inView) {
          info.parts = {};
          info.parts.top = elementRect.top >= viewportRect.top;
          info.parts.left = elementRect.left >= viewportRect.left;
          info.parts.bottom = elementRect.bottom <= viewportRect.bottom;
          info.parts.right = elementRect.right <= viewportRect.right;
        }
        return info;
      })

      // Add the changed information to the inview structure.
      .scan({}, function (lastInfo, newInfo) {
        // Add inview direction info
        if (options.generateDirection && newInfo.inView && lastInfo.elementRect) {
          newInfo.direction = {
            horizontal: newInfo.elementRect.left - lastInfo.elementRect.left,
            vertical: newInfo.elementRect.top - lastInfo.elementRect.top
          };
        }
        // Calculate changed flag
        newInfo.changed =
          newInfo.inView !== lastInfo.inView ||
          !angular.equals(newInfo.parts, lastInfo.parts) ||
          !angular.equals(newInfo.direction, lastInfo.direction);
        return newInfo;
      })

      // Filters only informations that should be forwarded to the callback
      .filter(function (info) {
        // Don't forward if no relevant infomation changed
        if (!info.changed) {
          return false;
        }
        // Don't forward if not initially in-view
        if (info.event.type === 'initial' && !info.inView) {
          return false;
        }
        return true;
      });

      // Execute in-view callback
      var inViewExpression = $parse(attrs.inView);
      var dispose = inviewInfoSignal.subscribe(function (info) {
        scope.$applyAsync(function () {
          inViewExpression(scope, {
            '$inview': info.inView,
            '$inviewInfo': info
          });
        });
      });

      // Dispose of reactive chain
      scope.$on('$destroy', dispose);
    }
  }
}

function inViewContainerDirective () {
  return {
    restrict: 'A',
    controller: ['$element', function ($element) {
      this.element = $element;
      this.eventsSignal = signalFromEvent($element, 'scroll');
      this.getViewportRect = function () {
        return $element[0].getBoundingClientRect();
      };
    }]
  }
}

// ## Utilities

function getViewportRect () {
  var result = {
    top: 0,
    left: 0,
    width: window.innerWidth,
    right: window.innerWidth,
    height: window.innerHeight,
    bottom: window.innerHeight
  };
  if (result.height) {
    return result;
  }
  var mode = document.compatMode;
  if (mode === 'CSS1Compat') {
    result.width = result.right = document.documentElement.clientWidth;
    result.height = result.bottom = document.documentElement.clientHeight;
  } else {
    result.width = result.right = document.body.clientWidth;
    result.height = result.bottom = document.body.clientHeight;
  }
  return result;
}

function intersectRect (r1, r2) {
  return !(r2.left > r1.right ||
           r2.right < r1.left ||
           r2.top > r1.bottom ||
           r2.bottom < r1.top);
}

function normalizeOffset (offset) {
  if (!angular.isArray(offset)) {
    throw new Error("angular-inview: Offset should be an array");
  }
  if (offset.length == 2) {
    return offset.concat(offset);
  }
  else if (offset.length == 3) {
    return offset.concat([offset[1]]);
  }
  return offset;
}

function offsetRect (rect, offset) {
  if (!offset) {
    return rect;
  }
  var offsetObject = {
    top: isPercent(offset[0]) ? (parseFloat(offset[0]) * rect.height) : offset[0],
    right: isPercent(offset[1]) ? (parseFloat(offset[1]) * rect.width) : offset[1],
    bottom: isPercent(offset[2]) ? (parseFloat(offset[2]) * rect.height) : offset[2],
    left: isPercent(offset[3]) ? (parseFloat(offset[3]) * rect.width) : offset[3]
  };
  var result = angular.copy(rect);
  result.top -= offsetObject.top;
  result.left -= offsetObject.left;
  result.bottom += offsetObject.bottom;
  result.right += offsetObject.right;
  result.height += offsetObject.top + offsetObject.bottom;
  result.width += offsetObject.left + offsetObject.right;
  return result;
}

function isPercent (n) {
  return angular.isString(n) && n.indexOf('%') > 0;
}

// ## QuickSignal FRP
// A quick and dirty implementation of Rx to have a streamlined code in the
// directives.

// ### QuickSignal
//
// - `didSubscribeFunc`: a function receiving a `subscriber` as described below
//
// Usage:
//     var mySignal = new QuickSignal(function(subscriber) { ... })
function QuickSignal (didSubscribeFunc) {
  this.didSubscribeFunc = didSubscribeFunc;
}

// Subscribe to a signal and consume the steam of data.
//
// Returns a function that can be called to stop the signal stream of data and
// perform cleanup.
//
// A `subscriber` is a function that will be called when a new value arrives.
// a `subscriber.$dispose` property can be set to a function to be called uppon
// disposal. When setting the `$dispose` function, the previously set function
// should be chained.
QuickSignal.prototype.subscribe = function (subscriber) {
  this.didSubscribeFunc(subscriber);
  var dispose = function () {
    if (subscriber.$dispose) {
      subscriber.$dispose();
      subscriber.$dispose = null;
    }
  }
  return dispose;
}

QuickSignal.prototype.map = function (f) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    subscriber.$dispose = s.subscribe(function (nextValue) {
      subscriber(f(nextValue));
    });
  });
};

QuickSignal.prototype.filter = function (f) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    subscriber.$dispose = s.subscribe(function (nextValue) {
      if (f(nextValue)) {
        subscriber(nextValue);
      }
    });
  });
};

QuickSignal.prototype.scan = function (initial, scanFunc) {
  var s = this;
  return new QuickSignal(function (subscriber) {
    var last = initial;
    subscriber.$dispose = s.subscribe(function (nextValue) {
      last = scanFunc(last, nextValue);
      subscriber(last);
    });
  });
}

QuickSignal.prototype.merge = function (signal) {
  return signalMerge(this, signal);
};

QuickSignal.prototype.throttle = function (threshhold) {
  var s = this, last, deferTimer;
  return new QuickSignal(function (subscriber) {
    var chainDisposable = s.subscribe(function () {
      var now = +new Date,
          args = arguments;
      if (last && now < last + threshhold) {
        clearTimeout(deferTimer);
        deferTimer = setTimeout(function () {
          last = now;
          subscriber.apply(null, args);
        }, threshhold);
      } else {
        last = now;
        subscriber.apply(null, args);
      }
    });
    subscriber.$dispose = function () {
      clearTimeout(deferTimer);
      if (chainDisposable) chainDisposable();
    };
  });
};

function signalMerge () {
  var signals = arguments;
  return new QuickSignal(function (subscriber) {
    var disposables = [];
    for (var i = signals.length - 1; i >= 0; i--) {
      disposables.push(signals[i].subscribe(function () {
        subscriber.apply(null, arguments);
      }));
    }
    subscriber.$dispose = function () {
      for (var i = disposables.length - 1; i >= 0; i--) {
        if (disposables[i]) disposables[i]();
      }
    }
  });
}

// Returns a signal from DOM events of a target.
function signalFromEvent (target, event) {
  return new QuickSignal(function (subscriber) {
    var handler = function (e) {
      subscriber(e);
    };
    var el = angular.element(target);
    el.on(event, handler);
    subscriber.$dispose = function () {
      el.off(event, handler);
    };
  });
}

function signalSingle (value) {
  return new QuickSignal(function (subscriber) {
    subscriber(value);
  });
}

})();<|endoftext|>


<commit_before>//cia.js  by dandavis [CCBY4]
(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory({});
	} else {
		// Browser globals (root is window)
		root.CIA = factory(root);
  }
}(this, function (pub) {

function CIA(reductions, state, pool) {
	if(typeof reductions  != "object") throw new TypeError("Reduction definitions Object cannot be a non-Object");

    function arr(s){return String(s).trim().split(/\s*,\s*/).filter(Boolean);}
  	function forEach(r,f){var m=r.length, i=0;for(; i<m; i++)f(r[i],i,r);};

	state = state || {};
	pool = pool || [];
	Object.keys(reductions).forEach(function(k){var o=reductions[k]; if(!Array.isArray(o))reductions[k]=[o];});
  	var orig=Object.freeze(Object.assign({}, state));
	var ret={
	  	returnValue: true,
		history: [],
	  	undo: function(n){
		  	state=orig;
		  	var r=this.history.slice(0, -(n||1));
		  	this.history.length=0;
		  	r.forEach(function(e){ this.dispatch(e[0],e[1]); }, this);
		},

		getState: function(){
			return Object.assign({}, state);
		},

		unsubscribe: function(fnHandler){
			return pool = pool.filter(function(fn){return fn !== fnHandler;});
		},

		on: function(strType, fnReducer) {
		  	if(!Array.isArray(fnReducer)) fnReducer = [fnReducer];
		  	forEach( arr(strType), function(strType){
				forEach(fnReducer, function(fnReducer){
					var r=reductions[strType] || (reductions[strType]=[]);
					r.push(fnReducer);
					this.history.push({type:"_ON_", event: strType, action: fnReducer });
				});
			});
			return this;
		},

		off: function(strType, fnReducer) {
			var r=reductions[strType];
			if(!r) return false;
			if(fnReducer==="*"){
			  this.history.push({type:"_OFF_", event: strType, action: fnReducer });
			  return delete reductions[strType];
			}

			var index=r.indexOf(fnReducer);
			if(index===-1) return false;
			r.splice(index, 1);
			this.history.push({type:"_OFF_", event: strType, action: fnReducer });
			return true;
		},
		subscribe: function(fnHandler, matcher){
			pool.push(fnHandler);
		  	fnHandler._matcher=matcher;
			return this.unsubscribe.bind(this, fnHandler);
		},

		dispatch: function(action, data){   // allows reducer return values to be fed to handlers via this:
		  	var that=this;

		  forEach( arr(action), function(action){

			var heap = reductions[action] || [];
			if(!heap.length && action!="_INIT_" ) throw new ReferenceError("Unknown reducer group: "+action);
		  	that.history.push([action, data]);
		  	heap.forEach(function(fn){
			  	state = fn.call(this, state, data) || state;
			}, that);
		  	if(!that.returnValue){
			 	that.returnValue=true;
			  	return that;
			}
			forEach(pool, function(fn){
			  if(fn._matcher){
				if(fn._matcher.call && !fn._matcher.call(that, action)) return;
				if(action.search(fn._matcher)===-1) return;
			  }
			  fn(state);
			});

		  });

		   return this;
		}
	};
	ret.dispatch.call(ret, "_INIT_");
	return ret;
}; // end CIA()

return CIA;

}));
<commit_msg>faster forEach, stop in middle of heap per-event<commit_after>//cia.js  by dandavis [CCBY4]
(function (root, factory) {
	if (typeof define === 'function' && define.amd) {
		// AMD. Register as an anonymous module.
		define([], factory);
	} else if (typeof exports === 'object') {
		// Node. Does not work with strict CommonJS, but
		// only CommonJS-like environments that support module.exports,
		// like Node.
		module.exports = factory({});
	} else {
		// Browser globals (root is window)
		root.CIA = factory(root);
  }
}(this, function (pub) {

function CIA(reductions, state, pool) {
	if(typeof reductions  != "object") throw new TypeError("Reduction definitions Object cannot be a non-Object");

    function arr(s){return String(s).trim().split(/\s*,\s*/).filter(Boolean);}
  	function forEach(r,f){var m=r.length, i=0;for(; i<m; i++)f(r[i],i,r);};

	state = state || {};
	pool = pool || [];
	Object.keys(reductions).forEach(function(k){var o=reductions[k]; if(!Array.isArray(o))reductions[k]=[o];});
  	var orig=Object.freeze(Object.assign({}, state));
	var ret={
	  	returnValue: true,
		history: [],
	  	undo: function(n){
		  	state=orig;
		  	var r=this.history.slice(0, -(n||1));
		  	this.history.length=0;
		  	r.forEach(function(e){ this.dispatch(e[0],e[1]); }, this);
		},

		getState: function(){
			return Object.assign({}, state);
		},

		unsubscribe: function(fnHandler){
			return pool = pool.filter(function(fn){return fn !== fnHandler;});
		},

		on: function(strType, fnReducer) {
		  	if(!Array.isArray(fnReducer)) fnReducer = [fnReducer];
		  	forEach( arr(strType), function(strType){
				forEach(fnReducer, function(fnReducer){
					var r=reductions[strType] || (reductions[strType]=[]);
					r.push(fnReducer);
					this.history.push({type:"_ON_", event: strType, action: fnReducer });
				});
			});
			return this;
		},

		off: function(strType, fnReducer) {
			var r=reductions[strType];
			if(!r) return false;
			if(fnReducer==="*"){
			  this.history.push({type:"_OFF_", event: strType, action: fnReducer });
			  return delete reductions[strType];
			}

			var index=r.indexOf(fnReducer);
			if(index===-1) return false;
			r.splice(index, 1);
			this.history.push({type:"_OFF_", event: strType, action: fnReducer });
			return true;
		},
		subscribe: function(fnHandler, matcher){
			pool.push(fnHandler);
		  	fnHandler._matcher=matcher;
			return this.unsubscribe.bind(this, fnHandler);
		},

		dispatch: function(action, data){   // allows reducer return values to be fed to handlers via this:
		  	var that=this;

		  forEach( arr(action), function(action){

			var heap = reductions[action] || [];
			if(!heap.length && action!="_INIT_" ) throw new ReferenceError("Unknown reducer group: "+action);
		  	that.history.push([action, data]);
		  	forEach(heap, function(fn){
			  	if(that.returnValue) state = fn.call(that, state, data) || state;
			});
		  	if(!that.returnValue){
			 	that.returnValue=true;
			  	return that;
			}
			forEach(pool, function(fn){
			  if(fn._matcher){
				if(fn._matcher.call && !fn._matcher.call(that, action)) return;
				if(action.search(fn._matcher)===-1) return;
			  }
			  fn(state);
			});

		  });

		   return this;
		}
	};
	ret.dispatch.call(ret, "_INIT_");
	return ret;
}; // end CIA()

return CIA;

}));
<|endoftext|>


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

	var unpackHttpRes = function(fn, value) {
		if (angular.isObject(value) && value.data && value.status && value.headers && value.config && value.statusText && angular.isFunction(value.headers)) {
			return fn(value.data, value.status, value.headers, value.config);
		} else {
			return fn(value);
		}
	};

	angular.module('jutaz.quasar', []).config(['$provide', function ($provide) {
		$provide.decorator('$q', ['$delegate', function ($delegate) {
			var q = {
				when: $delegate.when,
				reject: $delegate.reject,
				all: $delegate.all,
				defer: $delegate.defer
			};

			function decoratePromise(promise) {
				promise._then = promise.then;
				promise.extended = true; // Good to have for tests
				promise.then = function(thenFn, errFn, notifyFn) {
					if (angular.isObject(errFn)) {
						thenFn = thenFn.bind(errFn);
					}
					var p = promise._then(thenFn, errFn, notifyFn);
					return decoratePromise(p);
				};
				promise.success = function (fn) {
					return promise.then(unpackHttpRes.bind(undefined, fn));
				};
				promise.error = function (fn) {
					return promise.then(null, unpackHttpRes.bind(undefined, fn));
				};
				promise.spread = function (fn, context) {
					return promise.then(function (data) {
						if (!angular.isArray(data)) {
							return fn.call(context, data);
						} else {
							return q.all(data).then(function (resolved) {
								return fn.apply(context, resolved);
							}); // Resolve promises, if any
						}
					});
				};
				promise.delay = promise.timeout = function (fn, time, context) {
					// In case people have other preference
					if (angular.isNumber(fn) && angular.isFunction(time)) {
						var tmp = fn;
						fn = time;
						time = tmp;
					}
					var deferred = q.defer();
					setTimeout(function () {
						promise.then(fn, context).then(deferred.resolve);
					}, time);
					return decoratePromise(deferred.promise);
				};
				promise.all = function (fn, context) {
					var p = promise.then(function (data) {
						if (angular.isArray(data)) {
							return q.all(data);
						} else {
							return data;
						}
					}).then(fn, context);
					return p;
				};
				return promise;
			}

			$delegate.fcall = function (fn, context) {
				return $delegate.when().then(fn, context);
			};

			$delegate.defer = function() {
				var deferred = q.defer();
				decoratePromise(deferred.promise);
				return deferred;
			};

			['all', 'reject', 'when'].forEach(function (fn) {
				$delegate[fn] = function () {
					return decoratePromise(q[fn].apply(this, arguments));
				};
			});
			return $delegate;
		}]);
	}]);

})();
<commit_msg>Better syntax formatting<commit_after>(function() {
  'use strict';

  var unpackHttpRes = function(fn, value) {
    if (angular.isObject(value) && value.data && value.status && value.headers && value.config && value.statusText && angular.isFunction(value.headers)) {
      return fn(value.data, value.status, value.headers, value.config);
    } else {
      return fn(value);
    }
  };

  angular.module('jutaz.quasar', []).config(['$provide', function($provide) {
    $provide.decorator('$q', ['$delegate', function($delegate) {
      var q = {
        when: $delegate.when,
        reject: $delegate.reject,
        all: $delegate.all,
        defer: $delegate.defer,
      };

      function decoratePromise(promise) {
        promise._then = promise.then;
        promise.extended = true; // Good to have for tests

        promise.then = function(thenFn, errFn, notifyFn) {
          if (angular.isObject(errFn)) {
            thenFn = thenFn.bind(errFn);
          }

          var p = promise._then(thenFn, errFn, notifyFn);
          return decoratePromise(p);
        };

        promise.success = function(fn) {
          return promise.then(unpackHttpRes.bind(undefined, fn));
        };

        promise.error = function(fn) {
          return promise.then(null, unpackHttpRes.bind(undefined, fn));
        };

        promise.spread = function(fn, context) {
          return promise.then(function(data) {
            if (!angular.isArray(data)) {
              return fn.call(context, data);
            } else {
              return q.all(data).then(function(resolved) {
                return fn.apply(context, resolved);
              }); // Resolve promises, if any
            }
          });
        };

        promise.delay = promise.timeout = function(fn, time, context) {
          // In case people have other preference
          if (angular.isNumber(fn) && angular.isFunction(time)) {
            var tmp = fn;
            fn = time;
            time = tmp;
          }

          var deferred = q.defer();
          setTimeout(function() {
            promise.then(fn, context).then(deferred.resolve);
          }, time);

          return decoratePromise(deferred.promise);
        };

        promise.all = function(fn, context) {
          var p = promise.then(function(data) {
            if (angular.isArray(data)) {
              return q.all(data);
            } else {
              return data;
            }
          }).then(fn, context);
          return p;
        };

        return promise;
      }

      $delegate.fcall = function(fn, context) {
        return $delegate.when().then(fn, context);
      };

      $delegate.defer = function() {
        var deferred = q.defer();
        decoratePromise(deferred.promise);
        return deferred;
      };

      ['all', 'reject', 'when'].forEach(function(fn) {
        $delegate[fn] = function() {
          return decoratePromise(q[fn].apply(this, arguments));
        };
      });

      return $delegate;
    },
  ]);
  },
]);
})();
<|endoftext|>