/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb

import 'core-js/stable';
import 'regenerator-runtime/runtime';

import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';

const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false';
if (isOnline && process.env.NODE_ENV !== 'test') {
  Sentry.init({
    dsn: process.env.NEMO_SENTRY_DSN,
    integrations: [new Integrations.BrowserTracing()],

    // Percentage between 0.0 - 1.0.
    tracesSampleRate: 1.0,
  });
}

// Support component names relative to this directory:
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');

ReactRailsUJS.useContext(componentRequireContext);

/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb

import 'core-js/stable';
import 'regenerator-runtime/runtime';

import * as Sentry from '@sentry/react';
import { Integrations } from '@sentry/tracing';

const isOnline = !process.env.NEMO_OFFLINE_MODE || process.env.NEMO_OFFLINE_MODE === 'false';
if (isOnline && process.env.NODE_ENV !== 'test') {
  Sentry.init({
    dsn: process.env.NEMO_SENTRY_DSN,
    integrations: [new Integrations.BrowserTracing()],

    // Uncomment to enable Sentry performance monitoring (disabled in favor of Scout).
    // Percentage between 0.0 - 1.0.
    //tracesSampleRate: 1.0,
  });
}

// Support component names relative to this directory:
const componentRequireContext = require.context('components', true);
const ReactRailsUJS = require('react_ujs');

ReactRailsUJS.useContext(componentRequireContext);

Disable now-unused Sentry performance traces


const Utils = require('utils');
const defaults = require('lodash/defaults');

console.log(Util);

const defaultConfig = {
    baseUrl: '/',
};

class JSONAPI {
    constructor(apiConfig) {
        Utils.const(this, 'config', defaults({}, apiConfig, defaultConfig));
    }

    /**
     *
     * @param {*} modelConfig
     */
    define(modelConfig) {

    }
}

module.exports = JSONAPI;

const Utils = require('utils');
const defaults = require('lodash/defaults');
const defaultConfig = {
    baseUrl: '/',
};

class JSONAPI {
    constructor(apiConfig) {
        Utils.const(this, 'config', defaults({}, apiConfig, defaultConfig));
    }

    /**
     *
     * @param {*} modelConfig
     */
    define(modelConfig) {

    }
}

module.exports = JSONAPI;

Remove console.log statement causing an error in browser console.


"use strict";
/**
 * Webpack frontend test (w/ coverage) configuration.
 */
var _ = require("lodash");
var testCfg = require("./webpack.config.test");

module.exports = _.merge({}, testCfg, {
  module: {
    preLoaders: [
      // Manually instrument client code for code coverage.
      // https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
      {
        test: /src\/.*\.jsx?$/,
        exclude: /(test|node_modules)\//,
        loader: "isparta?{ babel: { stage: 1 } }"
      }
    ]
  }
});

"use strict";
/**
 * Webpack frontend test (w/ coverage) configuration.
 */
var _ = require("lodash");
var testCfg = require("./webpack.config.test");

module.exports = _.merge({}, testCfg, {
  module: {
    preLoaders: [
      // Manually instrument client code for code coverage.
      // https://github.com/deepsweet/isparta-loader handles ES6 + normal JS.
      {
        test: /src\/.*\.jsx?$/,
        exclude: /(test|node_modules)\//,
        loader: "isparta?{ babel: { stage: 0 } }"
      }
    ]
  }
});

Use stage 0 when loaded via isparta


exports.setup = function(Tests){

var Suite = require('lib/suite').Suite;

Tests.describe('Suites', function(it, setup){

	setup('beforeEach', function(){

	});

	it('should error out if no `it` named argument is declared', function(expect){
		var error = null;
		try {
			new Suite('Fail', function(){});
		} catch(e){
			error = e;
		} finally {
			expect(error).toBeAnInstanceOf(Error);
			expect(error.message).toBe('Suite function does not explicitly define an `it` argument.');
		}
	});

	it('should pass an `it` and `setup` function', function(expect){
		new Suite('Pass', function(it, setup){
			expect(it).toBeAnInstanceOf(Function);
			expect(setup).toBeAnInstanceOf(Function);
		}).run();
	});

});

};

exports.setup = function(Tests){

var Suite = require('lib/suite').Suite;

Tests.describe('Suites', function(it, setup){

	setup('beforeEach', function(){

	});

	it('should error out if no `it` named argument is declared', function(expect){
		var error = null;
		try {
			new Suite('Fail', function(){});
		} catch(e){
			error = e;
		} finally {
			expect(error).toBeAnInstanceOf(Error);
			expect(error.message).toBe('Suite function does not explicitly define an `it` argument.');
		}
	});

	it('should pass an `it` and `setup` function', function(expect){
		expect.perform(2);
		new Suite('Pass', function(it, setup){
			expect(it).toBeAnInstanceOf(Function);
			expect(setup).toBeAnInstanceOf(Function);
		}).run();
	});

});

};

Make it work on flusspferd.


// Add the mouse listeners for the above functions
function linkHover() {
	window.onmouseover = function(event) {
		if (event.target.matches('a')) {
			window.webkit.messageHandlers.mouseDidEnter.postMessage(event.target.href);
		}
	}
	window.onmouseout = function(event) {
		if (event.target.matches('a')) {
			window.webkit.messageHandlers.mouseDidExit.postMessage(event.target.href);
		}
	}
}

function postRenderProcessing() {
	linkHover()
}

// Add the mouse listeners for the above functions
function linkHover() {
	window.onmouseover = function(event) {
		var closestAnchor = event.target.closest('a')
		if (closestAnchor) {
			window.webkit.messageHandlers.mouseDidEnter.postMessage(closestAnchor.href);
		}
	}
	window.onmouseout = function(event) {
		var closestAnchor = event.target.closest('a')
		if (closestAnchor) {
			window.webkit.messageHandlers.mouseDidExit.postMessage(closestAnchor.href);
		}
	}
}

function postRenderProcessing() {
	linkHover()
}

Make mouseover/mouseout work with anchors that nest


$(document).ready(function() {
  var height = $("#page-header").height()
  $("a").click(function(e) {
      e.preventDefault();
      var href = $(this).attr("href");
       $('html, body').animate({
        scrollTop: $(href).offset().top - height
       }, 0);
  });
});

$(document).ready(function() {
  var height = $("#page-header").height()
  $("a.internal").click(function(e) {
      e.preventDefault();
      var href = $(this).attr("href");
       $('html, body').animate({
        scrollTop: $(href).offset().top - height
       }, 0);
  });
});

Make the selector more restrictive


/* vim: ts=4:sw=4:expandtab
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function () {
    'use strict';
    window.Whisper = window.Whisper || {};

    Whisper.WindowControlsView = Whisper.View.extend({
        tagName: 'span',
        className: 'window-controls',
        template: $('#window-controls').html(),
        initialize: function(options) {
            this.appWindow = options.appWindow;
            this.render();
        },
        events: {
            'click .close': 'close',
            'click .minimize': 'minimize'
        },
        close: function() {
            if (this.appWindow.id === 'inbox') {
                this.appWindow.hide();
            } else {
                this.appWindow.close();
            }
        },
        minimize: function() {
          this.appWindow.minimize();
        }
    });
})();

/* vim: ts=4:sw=4:expandtab
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function () {
    'use strict';
    window.Whisper = window.Whisper || {};

    Whisper.WindowControlsView = Whisper.View.extend({
        tagName: 'span',
        className: 'window-controls',
        template: $('#window-controls').html(),
        initialize: function(options) {
            this.appWindow = options.appWindow;
            this.render();
        },
        events: {
            'click .close': 'close',
            'click .minimize': 'minimize'
        },
        close: function() {
            this.appWindow.close();
        },
        minimize: function() {
          this.appWindow.minimize();
        }
    });
})();

Stop hiding inbox instead of closing


<script type="text/javascript">
//
// Reload the app if server detects local change
//
(function() {

    function checkForReload() {
        var xhr = new XMLHttpRequest;
        xhr.open('get', 'http://' + document.location.host + '/autoreload', true);
        xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
                var response = JSON.parse(this.responseText);
                if (response.outdated) {
                    window.location.reload();
                }
            }
        }
        xhr.send();
    }

    setInterval(checkForReload, 1000*5);

})(window);
</script>

<script type="text/javascript">
//
// Reload the app if server detects local change
//
(function() {

    function checkForReload() {
        var xhr = new XMLHttpRequest;
        xhr.open('get', 'http://' + document.location.host + '/autoreload', true);
        xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
        xhr.onreadystatechange = function() {
            if (this.readyState === 4 && /^[2]/.test(this.status)) {
                var response = JSON.parse(this.responseText);
                if (response.outdated) {
                    window.location.reload();
                }
            }
        }
        xhr.send();
    }

    setInterval(checkForReload, 1000 * 3);

})(window);
</script>

Reduce AutoReload ping to 3s.


// js/routes

(function() {
  "use strict";

  angular.module("NoteWrangler")
    .config(config);

  function config($routeProvider) {
    $routeProvider
      .when("/notes", {
        templateUrl: "../templates/pages/notes/index.html",
        controller: "NotesIndexController",
        controllerAs: "notesIndexCtrl"
      })
      .when("/users", {
        templateUrl: "../templates/pages/users/index.html"
      })
      .when("/notes/new", {
        templateUrl: "templates/pages/notes/new.html",
        controller: "NotesCreateController",
        controllerAs: "notesCreateCtrl"
      })
      .when("/notes/:id", {
        templateUrl: "templates/pages/notes/show.html",
        controller: "NotesShowController",
        controllerAs: "notesShowCtrl"
      })
      .otherwise({
        redirectTo: "/",
        templateUrl: "templates/pages/index/index.html"
      });
  }
})();

// js/routes

(function() {
  "use strict";

  angular.module("NoteWrangler")
    .config(config);

  function config($routeProvider) {
    $routeProvider
      .when("/notes", {
        templateUrl: "../templates/pages/notes/index.html",
        controller: "NotesIndexController",
        controllerAs: "notesIndexCtrl"
      })
      .when("/users", {
        templateUrl: "../templates/pages/users/index.html",
        controller: "UsersIndexController",
        controllerAs: "usersIndexCtrl"
      })
      .when("/notes/new", {
        templateUrl: "templates/pages/notes/new.html",
        controller: "NotesCreateController",
        controllerAs: "notesCreateCtrl"
      })
      .when("/notes/:id", {
        templateUrl: "templates/pages/notes/show.html",
        controller: "NotesShowController",
        controllerAs: "notesShowCtrl"
      })
      .otherwise({
        redirectTo: "/",
        templateUrl: "templates/pages/index/index.html"
      });
  }
})();

Add controller, controllerAs fields for /users route


#!/usr/bin/env node
var express = require('express')
var app = express()
var dafuq = require('./')

var argv = require('yargs')
	.usage('$0 Leverages command-based api')
    .describe('commands', 'the path to commands directory')
    .alias('commands', 'c')
    .alias('commands', 'path')
    .alias('commands', 'directory')
    .demand('commands')
    .describe('shebang', 'the interpreter to use when running the command files')
    .default('shebang', '')
    .describe('port', 'the port where to listen for api call')
    .alias('port', 'p')
    .default('port', 3000)
    .help('help')
    .alias('help', 'h')
    .argv;

app.use(dafuq({
	path: argv.commands,
	shebang: argv.shebang
}))
app.listen(argv.port)

#!/usr/bin/env node
var path = require('path')
var express = require('express')
var app = express()
var dafuq = require('./')

var argv = require('yargs')
	.usage('$0 Leverages command-based api')
    .describe('commands', 'the path to commands directory')
    .alias('commands', 'c')
    .alias('commands', 'path')
    .alias('commands', 'directory')
    .demand('commands')
    .describe('shebang', 'the interpreter to use when running the command files')
    .default('shebang', '')
    .describe('port', 'the port where to listen for api call')
    .alias('port', 'p')
    .default('port', 3000)
    .help('help')
    .alias('help', 'h')
    .argv;

// Resolve full path when executing via CLI
if (require.main === module)
    argv.commands = path.resolve(process.pwd(), argv.commands)

app.use(dafuq({
	path: argv.commands,
	shebang: argv.shebang
}))
app.listen(argv.port)

Resolve path names relatives to cwd when using via CLI


/*
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

/**
 * This file provides the @defines for jsinterop configuration options.
 * See InternalPreconditions.java for details.
 */

goog.provide('jsinterop');

// Note that disabling checking only disables it for production.

/** @define {string} */
goog.define('jsinterop.checks', 'DISABLED');

/*
 * Copyright 2017 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

/**
 * This file provides the @defines for jsinterop configuration options.
 * See InternalPreconditions.java for details.
 */

goog.provide('jsinterop');

// Note that disabling checking only disables it for production.

/** @define {string} */
jsinterop.checks = goog.define('jsinterop.checks', 'DISABLED');

Replace calls to goog.define with assignments to the result of goog.define.


import Ember from 'ember';

export default Ember.Controller.extend({
  init () {
    Ember.run.schedule('afterRender', () => {
      componentHandler.upgradeAllRegistered();
    });
  },

  settingsSnackbar (message) {
    const _this = this;
    const snackbarContainer = document.querySelector('#snackbar-container');

    const handler = function () {
      _this.transitionToRoute('home');
      Ember.run.later(() => {
        window.location.reload(true);
      }, 500);
    };

    const data = {
      message,
      timeout: 4000,
      actionHandler: handler,
      actionText: 'Reload'
    };
    snackbarContainer.MaterialSnackbar.showSnackbar(data);
  },
  currency: function () {
    let currency = this.get('model').findBy('id', 'currency');
    if (!currency) {
      return {
        id: false,
        setting: 'Currency',
        value: '£'
      };
    }
    return currency;
  }.property('model.@each.value'),

  userName: function () {
    let userName = this.get('model').findBy('id', 'user-name');

    if (!userName) {
      return {
        id: false,
        setting: 'Name',
        value: 'Guest'
      };
    }
    return userName;
  }.property('model.@each.value')
});

import Ember from 'ember';

export default Ember.Controller.extend({
  init () {
    Ember.run.schedule('afterRender', () => {
      componentHandler.upgradeAllRegistered();
    });
  },

  settingsSnackbar (message) {
    const _this = this;
    const snackbarContainer = document.querySelector('#snackbar-container');

    const handler = function () {
      _this.transitionToRoute('home');
      Ember.run.later(() => {
        window.location.reload(true);
      }, 500);
    };

    const data = {
      message,
      timeout: 4000,
      actionHandler: handler,
      actionText: 'Reload'
    };
    snackbarContainer.MaterialSnackbar.showSnackbar(data);
  },
  currency: function () {
    let currency = this.get('model').findBy('id', 'currency');

    if (!currency) {
      return {
        isDefault: true,
        id: 'currency',
        setting: 'Currency',
        value: '$'
      };
    }
    return currency;
  }.property('model'),

  userName: function () {
    let userName = this.get('model').findBy('id', 'user-name');

    if (!userName) {
      return {
        isDefault: true,
        id: 'user-name',
        setting: 'Name',
        value: 'Guest'
      };
    }
    return userName;
  }.property('model'),

});

Add isDefault property for each setting


'use strict';

var _ = require('lodash');
var util = require('util');

var validateDeprecation = function(value, expectation, options) {
  if (!options.deprecated) {
    return;
  }

  var valid = (value instanceof options.deprecated || typeof(value) === typeof(options.deprecated.call()));

  if (valid) {
    var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);

    console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
  }

  return valid;
};

var validate = function(value, expectation, options) {

  // the second part of this check is a workaround to deal with an issue that occurs in node-webkit when
  // using object literals.  https://github.com/sequelize/sequelize/issues/2685
  if (value instanceof expectation || typeof(value) === typeof(expectation.call())) {
    return true;
  }

  throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};

var ParameterValidator = module.exports = {
  check: function(value, expectation, options) {
    options = _.extend({
      deprecated: false,
      index: null,
      method: null,
      optional: false
    }, options || {});

    if (!value && options.optional) {
      return true;
    }

    if (value === undefined) {
      throw new Error('No value has been passed.');
    }

    if (expectation === undefined) {
      throw new Error('No expectation has been passed.');
    }

    return false
      || validateDeprecation(value, expectation, options)
      || validate(value, expectation, options);
  }
};

'use strict';

var _ = require('lodash');
var util = require('util');

var validateDeprecation = function(value, expectation, options) {
  if (!options.deprecated) {
    return;
  }

  var valid = value instanceof options.deprecated;

  if (valid) {
    var message = util.format('%s should not be of type "%s"', util.inspect(value), options.deprecated.name);

    console.log('DEPRECATION WARNING:', options.deprecationWarning || message);
  }

  return valid;
};

var validate = function(value, expectation, options) {
  if (value instanceof expectation) {
    return true;
  }

  throw new Error(util.format('The parameter (value: %s) is no %s.', value, expectation.name));
};

var ParameterValidator = module.exports = {
  check: function(value, expectation, options) {
    options = _.extend({
      deprecated: false,
      index: null,
      method: null,
      optional: false
    }, options || {});

    if (!value && options.optional) {
      return true;
    }

    if (value === undefined) {
      throw new Error('No value has been passed.');
    }

    if (expectation === undefined) {
      throw new Error('No expectation has been passed.');
    }

    return false
      || validateDeprecation(value, expectation, options)
      || validate(value, expectation, options);
  }
};

Revert "Workaround to deal with an issue in node-webkit where the validate function fails on object literals"


'use strict';

const helpers = require('../../shared/helpers');

function adjustClasses() {
  if (helpers.isMobile($) === true) {
    $('body').addClass('is-mobile').removeClass('is-desktop');
  }
  else {
    $('body').addClass('is-desktop').removeClass('is-mobile');
  }
}

window.addEventListener('resize', adjustClasses, false);
window.addEventListener('load', adjustClasses, false);
document.addEventListener('DOMContentLoaded', adjustClasses, false);

'use strict';

const helpers = require('../../shared/helpers');

// General function to add 'is-mobile' and 'is-desktop' class to body.
// Used to adjust styling for mobile/desktop and called on multiple events.
function adjustClasses() {
  if (helpers.isMobile($) === true) {
    $('body').addClass('is-mobile').removeClass('is-desktop');
  }
  else {
    $('body').addClass('is-desktop').removeClass('is-mobile');
  }
}

window.addEventListener('resize', adjustClasses, false);
window.addEventListener('load', adjustClasses, false);
document.addEventListener('DOMContentLoaded', adjustClasses, false);

Add comment to adjustClasses function


define(function (require, exports, module) {
'use strict';

var Mode = require("../../mode").Mode;
var util = require("../../util");
var oop = require("../../oop");
var GenericDecorator = require("./generic_decorator").GenericDecorator;
var tr = require("./generic_tr").tr;

function GenericMode () {
    Mode.call(this);
    this._resolver = new util.NameResolver();
}

oop.inherit(GenericMode, Mode);

(function () {
    // Modes must override this.
    this.getAbsoluteResolver = function () {
        return this._resolver;
    };

    this.makeDecorator = function () {
        var obj = Object.create(GenericDecorator.prototype);
        // Make arg an array and add our extra argument(s).
        var args = Array.prototype.slice.call(arguments);
        args.unshift(this);
        GenericDecorator.apply(obj, args);
        return obj;
    };

    this.getTransformationRegistry = function () {
        return tr;
    };

    this.getContextualMenuItems = function () {
        return [];
    };

    this.nodesAroundEditableContents = function (parent) {
        var ret = [null, null];
        var start = parent.childNodes[0];
        if ($(start).is("._gui._start_button"))
            ret[0] = start;
        var end = parent.childNodes[parent.childNodes.length - 1];
        if ($(end).is("_gui.start_button"))
            ret[1] = end;
        return ret;
    };

}).call(GenericMode.prototype);

exports.Mode = GenericMode;

});

define(function (require, exports, module) {
'use strict';

var Mode = require("../../mode").Mode;
var util = require("../../util");
var oop = require("../../oop");
var GenericDecorator = require("./generic_decorator").GenericDecorator;
var tr = require("./generic_tr").tr;

function GenericMode () {
    Mode.call(this);
    this._resolver = new util.NameResolver();
}

oop.inherit(GenericMode, Mode);

(function () {
    // Modes must override this.
    this.getAbsoluteResolver = function () {
        return this._resolver;
    };

    this.makeDecorator = function () {
        var obj = Object.create(GenericDecorator.prototype);
        // Make arg an array and add our extra argument(s).
        var args = Array.prototype.slice.call(arguments);
        args.unshift(this);
        GenericDecorator.apply(obj, args);
        return obj;
    };

    this.getTransformationRegistry = function () {
        return tr;
    };

    this.getContextualMenuItems = function () {
        return [];
    };

    this.nodesAroundEditableContents = function (parent) {
        var ret = [null, null];
        var start = parent.childNodes[0];
        if ($(start).is("._gui._start_button"))
            ret[0] = start;
        var end = parent.childNodes[parent.childNodes.length - 1];
        if ($(end).is("._gui._end_button"))
            ret[1] = end;
        return ret;
    };

}).call(GenericMode.prototype);

exports.Mode = GenericMode;

});

Fix in how the contents is determined.


Template.resident.created = function () {
  // Get reference to template instance
  var instance = this;

  // Get Resident ID from router
  instance.residentId = Router.current().params.residentId;

  // Subscribe to current resident
  instance.subscribe('residentComposite', instance.residentId);

  instance.autorun(function () {
    if (instance.subscriptionsReady()) {
      instance.resident = Residents.findOne(instance.residentId);

      instance.activities = Activities.find({residentIds: instance.residentId}).fetch();
    }
  });
};

Template.resident.events({
  'click #edit-resident': function () {
    // Get reference to template instance
    var instance = Template.instance();

    // Show the edit home modal
    Modal.show('editResident', instance.resident);
  }
});

Template.resident.helpers({
  'resident': function () {
    // Get reference to template instance
    var instance = Template.instance();

    // Get resident from template instance
    var resident = instance.resident;

    return resident;
  },
  'activities': function () {
    // Get reference to template instance
    const instance = Template.instance();

    // Get activities from template instance
    var activities = instance.activities;

    return activities;
  }
})

Template.resident.created = function () {
  // Get reference to template instance
  var instance = this;

  // Get Resident ID from router
  instance.residentId = Router.current().params.residentId;

  // Subscribe to current resident
  instance.subscribe('residentComposite', instance.residentId);

  // Subscribe to all roles except admin
  instance.subscribe("allRolesExceptAdmin");

  instance.autorun(function () {
    if (instance.subscriptionsReady()) {
      instance.resident = Residents.findOne(instance.residentId);

      instance.activities = Activities.find({residentIds: instance.residentId}).fetch();
    }
  });
};

Template.resident.events({
  'click #edit-resident': function () {
    // Get reference to template instance
    var instance = Template.instance();

    // Show the edit home modal
    Modal.show('editResident', instance.resident);
  }
});

Template.resident.helpers({
  'resident': function () {
    // Get reference to template instance
    var instance = Template.instance();

    // Get resident from template instance
    var resident = instance.resident;

    return resident;
  },
  'activities': function () {
    // Get reference to template instance
    const instance = Template.instance();

    // Get activities from template instance
    var activities = instance.activities;

    return activities;
  }
})

Add subscription to all roles except admin


/* global React ReactDOM */
var div = React.DOM.div
var h1 = React.DOM.h1

var MyTitle = React.createClass({
    render () {
        return (
            div(null,
                h1(null, 'A component!')
            )
        )
    }
})

var MyTitleFactory = React.createFactory(MyTitle)

var MyFirstComponent = (
    div(null,
        MyTitleFactory(null),
        MyTitleFactory(null),
        MyTitleFactory(null)
    )
)

ReactDOM.render(MyFirstComponent, document.getElementById('app'))

/* global React ReactDOM */
var div = React.DOM.div
var h1 = React.DOM.h1

var MyTitle = React.createClass({
    render () {
        return (
            div(null,
                h1({ style: { color: this.props.color, size: this.props.fontstyle } }, this.props.title)
            )
        )
    }
})

var MyTitleFactory = React.createFactory(MyTitle)

var MyFirstComponent = React.createClass({
    render: function () {
        return (
            div(null,
                MyTitleFactory({title: 'a title prop', color: 'blue'}),
                MyTitleFactory({title: 'another title', color: 'peru'}),
                MyTitleFactory({title: 'it\'s the final title', color: 'lavender'})
            )
        )
    }
})

ReactDOM.render(React.createElement(MyFirstComponent), document.getElementById('app'))

Add props to the MyTitle class.


const config = require('config');
const crypto = require('crypto');

module.exports.info = {
	name: 'Rate and Rank',
	description: 'Interprets and determines the relevant rank for a query',
	category: 'Fun',
	aliases: [
		'rate',
		'rank'
	],
	use: [
		{
			name: '',
			value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
		}, {
			name: '<thing>',
			value: 'Rate the thing'
		}
	]
};

module.exports.command = (message) => {
	if (message.input) {
		const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ ]/g, '');
		const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
		const rank = parseInt(hash, 16) % 11;
		const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
		message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
	}
};

const config = require('config');
const crypto = require('crypto');

module.exports.info = {
	name: 'Rate and Rank',
	description: 'Interprets and determines the relevant rank for a query',
	category: 'Fun',
	aliases: [
		'rate',
		'rank'
	],
	use: [
		{
			name: '',
			value: 'Rate the empty air of silence after you and your children\'s deaths, past the end of civilisation, past the end of our Sun, past the heat death of the universe, and is at a global temperature of absolute zero.'
		}, {
			name: '<thing>',
			value: 'Rate the thing'
		}
	]
};

module.exports.command = (message) => {
	if (message.input) {
		const input = message.input.replace(/[^@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\\]^_`abcdefghijklmno0123456789:;<=>?pqrstuvwxyz{|}~!ツ/' ]/g, '');
		const hash = crypto.createHash('md5').update(input + config.get('secret')).digest('hex').substring(0, 4);
		const rank = parseInt(hash, 16) % 11;
		const thing = message.input.length < 100 ? input : `${input.substring(0, 100)}...`;
		message.channel.createMessage(`I ${message.command} ${thing} a ${rank} out of 10`);
	}
};

Add some extra characters in


var CodeMirror = require('codemirror')
  , bindCodemirror = require('gulf-codemirror')

module.exports = setup
module.exports.consumes = ['editor']
module.exports.provides = []
function setup(plugin, imports, register) {
  var editor = imports.editor

  var cmCssLink = document.createElement('link')
  cmCssLink.setAttribute('rel', "stylesheet")
  cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css")
  document.head.appendChild(cmCssLink)

  editor.registerEditor('text', function*() {
    var editor = document.querySelector('#editor')
    var cm = CodeMirror(function(el) {
      editor.appendChild(el)

      el.style['height'] = '100%'
      el.style['width'] = '100%'
    })

    editor.style['height'] = '100%'
    document.body.style['position'] = 'absolute'
    document.body.style['bottom'] =
    document.body.style['top'] =
    document.body.style['left'] =
    document.body.style['right'] = '0'

    return bindCodemirror(cm)
  })
  register()
}

var CodeMirror = require('codemirror')
  , bindCodemirror = require('gulf-codemirror')

module.exports = setup
module.exports.consumes = ['editor']
module.exports.provides = []
function setup(plugin, imports, register) {
  var editor = imports.editor

  var cmCssLink = document.createElement('link')
  cmCssLink.setAttribute('rel', "stylesheet")
  cmCssLink.setAttribute('href', "/static/hive-editor-text-codemirror/static/codemirror.css")
  document.head.appendChild(cmCssLink)

  editor.registerEditor('CodeMirror', 'text', 'An extensible and performant code editor'
  , function*(editorEl) {
    var cm = CodeMirror(function(el) {
      editorEl.appendChild(el)

      el.style['height'] = '100%'
      el.style['width'] = '100%'
    })

    editorEl.style['height'] = '100%'
    document.body.style['position'] = 'absolute'
    document.body.style['bottom'] =
    document.body.style['top'] =
    document.body.style['left'] =
    document.body.style['right'] = '0'

    return bindCodemirror(cm)
  })
  register()
}

Upgrade to ew editor API


import {GLOBAL_VERSION} from "./constants";
import events from "./events";

export function makeKey({
	name,
	version,
}, args){
	const pieces = [
		GLOBAL_VERSION,
		name,
		version || 0,
		...args,
	]
	for (let i = 0; i < pieces.length; i++){
		if (
			typeof pieces[i] !== 'string' &&
			typeof pieces[i] !== 'number'
		){
			const error = new Error(
				`Bad key component (${pieces[i]})`
			);
			events.emit('error', {name, error});
			return null;
		}
	}
	return pieces.join('_');
}

import {GLOBAL_VERSION} from "./constants";
import events from "./events";

export function makeKey({
	name,
	version,
}, args){
	const pieces = [
		GLOBAL_VERSION,
		name,
		version || 0,
		...args,
	]
	for (let i = 0; i < pieces.length; i++){
		if (
			typeof pieces[i] !== 'string' &&
			typeof pieces[i] !== 'number'
		){
			const error = new Error(
				`Bad key component (${pieces[i]})`
			);
			events.emit('error', {name, error});
			return null;
		}
	}
	return JSON.stringify(pieces);
}

Use JSON.stringify() instead of .join() to avoid key collision


/**
 @ngdoc service
 * @name umbraco.services.overlayService
 *
 * @description
 * <b>Added in Umbraco 8.0</b>. Application-wide service for handling overlays.
 */
(function () {
    "use strict";

    function overlayService(eventsService, backdropService) {

        function open(overlay) {

            var backdropOptions = {};

            // set the default overlay position to center
            if(!overlay.position) {
                overlay.position = "center";
            }

            // option to disable backdrop clicks
            if(overlay.disableBackdropClick) {
                backdropOptions.disableEventsOnClick = true;
            }

            overlay.show = true;
            backdropService.open(backdropOptions);
            eventsService.emit("appState.overlay", overlay);
        }

        function close() {
            backdropService.close();
            eventsService.emit("appState.overlay", null);
        }

        var service = {
            open: open,
            close: close
        };

        return service;

    }

    angular.module("umbraco.services").factory("overlayService", overlayService);

})();

/**
 @ngdoc service
 * @name umbraco.services.overlayService
 *
 * @description
 * <b>Added in Umbraco 8.0</b>. Application-wide service for handling overlays.
 */
(function () {
    "use strict";

    function overlayService(eventsService, backdropService) {

        var currentOverlay = null;

        function open(newOverlay) {

            // prevent two open overlays at the same time
            if(currentOverlay) {
                return;
            }

            var backdropOptions = {};
            var overlay = newOverlay;

            // set the default overlay position to center
            if(!overlay.position) {
                overlay.position = "center";
            }

            // option to disable backdrop clicks
            if(overlay.disableBackdropClick) {
                backdropOptions.disableEventsOnClick = true;
            }

            overlay.show = true;
            backdropService.open(backdropOptions);
            currentOverlay = overlay;
            eventsService.emit("appState.overlay", overlay);
        }

        function close() {
            backdropService.close();
            currentOverlay = null;
            eventsService.emit("appState.overlay", null);
        }

        var service = {
            open: open,
            close: close
        };

        return service;

    }

    angular.module("umbraco.services").factory("overlayService", overlayService);

})();

Make sure two overlays can't be open at the same time


//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
  var userId = req.params.id;

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'SELECT * FROM mentors ' +
      'JOIN faq ON mentors.id = faq.mentor_id ' +
      'WHERE mentors.id = $1', [userId],
      function(error, result) {
        if(error) {
          console.log('Error when searching mentors and FAQ tables: ', error);
          res.sendStatus(500);
        } else {
          res.send(result.rows);
        }
      }
    );
  });
});

module.exports = router;

// Checks for errors connecting to the database
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}

//----------------------------------------------------------------------------//
var express = require('express');
var router = express.Router();
var pg = require('pg');
var connectionString = require('../modules/db-config.module');
//----------------------------------------------------------------------------//

// Gets a user's profile info and FAQ entries
router.get('/:id', function(req, res) {
  var userId = req.params.id;

  pg.connect(connectionString, function(error, client, done) {
    connectionErrorCheck(error);

    client.query(
      'SELECT * FROM mentors ' +
      'FULL OUTER JOIN faq ON mentors.id = faq.mentor_id ' +
      'WHERE mentors.id = $1', [userId],
      function(error, result) {
        done();
        if(error) {
          console.log('Error when searching mentors and FAQ tables: ', error);
          res.sendStatus(500);
        } else {
          res.send(result.rows);
        }
      }
    );
  });
});

module.exports = router;

// Checks for errors connecting to the database
function connectionErrorCheck(error) {
  if (error) {
    console.log('Database connection error: ', error);
    res.sendStatus(500);
  }
}

Fix issue with pulling users with FAQs


/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

*********************************************************************************************** */

/**
 * @break {unify.ui.layout.queue.Manager}
 */

(function() {

  var widgetQueue = [];

  core.Module("unify.ui.layout.queue.Visibility", {
    name : "visibility",

    add : function(widget) {
      widgetQueue.push(widget);
      unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
    },

    flush : function() {
      console.log("VISIBILITY: ", widgetQueue.length, widgetQueue);

      for (var i=0,ii=widgetQueue.length; i<ii; i++) {
        var widget = widgetQueue[i];
        widget.checkAppearanceNeeds();
      }
    }
  });

})();

/* ***********************************************************************************************

    Unify Project

    Homepage: unify-project.org
    License: MIT + Apache (V2)
    Copyright: 2012, Sebastian Fastner, Mainz, Germany, http://unify-training.com

*********************************************************************************************** */

/**
 * @break {unify.ui.layout.queue.Manager}
 */

(function() {

  var widgetQueue = [];

  core.Module("unify.ui.layout.queue.Visibility", {
    name : "visibility",

    add : function(widget) {
      widgetQueue.push(widget);
      unify.ui.layout.queue.Manager.run(unify.ui.layout.queue.Visibility.name);
    },

    flush : function() {
      for (var i=0,ii=widgetQueue.length; i<ii; i++) {
        var children = widgetQueue[i].getLayoutChildren();
        widgetQueue = widgetQueue.concat(children);
      }

      for (i=0,ii=widgetQueue.length; i<ii; i++) {
        widgetQueue[i].checkAppearanceNeeds();
      }
    }
  });

})();

Add children handling to visibility queue


// If you are requiring twilio-video from CommonJS,
//
//     const Video = require('twilio-video');
//
//  If you are including twilio-video.js from a <script> tag,
//
//     const Video = Twilio.Video;
//

// 1.0.0-beta4 and earlier
// const client = new Video.Client(accessToken);

// 1.0.0-beta5 onwards the Client class has been removed.
// Instead of constructing a Client using an Access Token and then calling connect
// on it, you can simply call connect and pass it an Access Token directly.
const room = await Twilio.Video.connect('your-token');

// If you are requiring twilio-video from CommonJS,
//
//     const Video = require('twilio-video');
//
//  If you are including twilio-video.js from a <script> tag,
//
//     const Video = Twilio.Video;
//

// 1.0.0-beta4 and earlier
// const client = new Video.Client(accessToken);

// 1.0.0-beta5 onwards the Client class has been removed.
// Instead of constructing a Client using an Access Token and then calling connect
// on it, you can simply call connect and pass it an Access Token directly.
const Video = Twilio.Video;

Video.connect('your-token', { name: 'room-name' }).then(function(room) {
  console.log('Connected to Room "%s"', room.name);

  room.participants.forEach(participantConnected);
  room.on('participantConnected', participantConnected);

  room.on('participantDisconnected', participantDisconnected);
  room.once('disconnected', function(error) {
    return room.participants.forEach(participantDisconnected);
  });
});

Fix js snippet to not use async/await


const normalize = require('path').normalize;
const root = 'angular/';

module.exports = {
    appRoot: require('path').resolve(__dirname, '..'),
    assetsPath: 'public/assets/',
    src: {
        rootPath: root,
        typescript: normalize(root + '**/*.ts'),
        sass: {
            app: normalize(root + 'app/**/*.scss'),
            globals: normalize(root + 'globals.scss')
        },
        views: normalize(root + 'app/**/*.html')
    },
    dependencies: {
        js: [
            'node_modules/es6-shim/es6-shim.min.js',
            'node_modules/zone.js/dist/zone.js',
            'node_modules/reflect-metadata/Reflect.js'
        ],
        css: [
            'node_modules/bootstrap/scss/bootstrap-flex.scss'
        ]
    }
};

const normalize = require('path').normalize;
const root = 'angular/';

module.exports = {
    appRoot: require('path').resolve(__dirname, '..'),
    assetsPath: 'public/assets/',
    src: {
        rootPath: root,
        typescript: normalize(root + '**/*.ts'),
        sass: {
            app: normalize(root + 'app/**/*.scss'),
            globals: normalize(root + 'globals.scss')
        },
        views: normalize(root + 'app/**/*.html')
    },
    dependencies: {
        js: [
            'node_modules/es6-shim/es6-shim.min.js',
            'node_modules/zone.js/dist/zone.js',
            'node_modules/reflect-metadata/Reflect.js'
        ],
        css: [
            'node_modules/bootstrap/scss/bootstrap-flex.scss',
            'node_modules/loaders.css/src/loaders.scss'
        ]
    }
};

Include loader.css dependency in the build process


var AnimationModule = require('../src/js/visuals/animation/index');
var PromiseAnimation = AnimationModule.PromiseAnimation;
var Animation = AnimationModule.Animation;
var Q = require('q');

describe('Promise animation', function() {
  it('Will execute the closure', function() {
    var value = 0;
    var closure = function() {
      value++;
    };

    var animation = new PromiseAnimation({
      deferred: Q.defer(),
      closure: closure
    });
    animation.play();
    expect(value).toBe(1);
  });

  it('also takes animation packs', function() {
    var value = 0;
    var animation = new PromiseAnimation({
      animation: function() { value++; }
    });
    animation.play();
    expect(value).toBe(1);
  });

  it('Will resolve a deferred', function() {
    var value = 0;
    var closure = function() {
      value++;
    };

    var animation = new PromiseAnimation({
      closure: closure
    });
    animation
    .then(function() {
      value++;
    })
    .then(function() {
      if (value !== 2) {
        console.log('second promise failed!!');
      } else {
        console.log('1 more test passed');
      }
      // TODO -- make this work (aka the tests keep running until
      // this assertion finishes
      expect(value).toBe(2);
    });

    animation.play();
    expect(value).toBe(1);
  });

  it('will make one from a normal animation', function() {
    // poor mans spy function
    var value = 0;
    var anim = new Animation({
      closure: function() { value++; }
    });

    var animPromise = PromiseAnimation.fromAnimation(anim);
    animPromise
    .then(function() {
      value++;
    }).then(function() {
      // TODO fix
      expect(value).toBe(2);
      if (value !== 2) {
        console.log('a test failed!!');
      } else {
        console.log('another test passed');
      }
    });

    animPromise.play();
    expect(value).toBe(1);
  });
});

var AnimationModule = require('../src/js/visuals/animation/index');
var PromiseAnimation = AnimationModule.PromiseAnimation;
var Animation = AnimationModule.Animation;
var Q = require('q');

describe('Promise animation', function() {
  it('Will execute the closure', function() {
    var value = 0;
    var closure = function() {
      value++;
    };

    var animation = new PromiseAnimation({
      deferred: Q.defer(),
      closure: closure
    });
    animation.play();
    expect(value).toBe(1);
  });

  it('also takes animation packs', function() {
    var value = 0;
    var animation = new PromiseAnimation({
      animation: function() { value++; }
    });
    animation.play();
    expect(value).toBe(1);
  });
});

Remove animation tests to fix build


'use strict';

define(['../../../src/client/config'], function(config) {

  config.baseUrl = '/';

  config.paths.jquery = 'bower_components/jquery/dist/jquery';
  config.paths['thehelp-test'] = 'node_modules/thehelp-test/dist/thehelp-test';
  config.paths['thehelp-test-coverage'] =
    'node_modules/thehelp-test/dist/thehelp-test-coverage';
  config.paths['grunt-mocha-bridge'] =
    'node_modules/thehelp-test/dist/grunt-mocha-bridge';

  requirejs.config(config);

  require(['jquery', window.entrypoint], function() {});

});

'use strict';

define(['../../../src/client/config'], function(config) {

  config.baseUrl = '/';

  config.paths['thehelp-test'] = 'node_modules/thehelp-test/dist/thehelp-test';
  config.paths['thehelp-test-coverage'] =
    'node_modules/thehelp-test/dist/thehelp-test-coverage';
  config.paths['grunt-mocha-bridge'] =
    'node_modules/thehelp-test/dist/grunt-mocha-bridge';

  requirejs.config(config);

  require([window.entrypoint], function() {});

});

Remove remaining hints of jquery


var assert = require('assert');

function BitRing(capacity) {
    assert.ok(capacity < 32, 'Capacity must be less than 32');
    this.capacity = capacity;
    this.bits = 0;
    this.pos = 0;
    this.length = 0;
    this._count = 0;
}

// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
    var num = bool === true ? 1 : 0;
    this._count += num - ((this.bits >>> this.pos) & 1);
    this.bits ^= (-num ^ this.bits) & (1 << this.pos);
    this.pos = (this.pos + 1) % this.capacity;
    if (this.length < this.capacity) {
        this.length++;
    }
};

// Return the number of bits set
BitRing.prototype.count = function() {
    return this._count;
};

module.exports = BitRing;

function BitRing(capacity) {
    this.capacity = capacity;
    this.bits = new Uint8ClampedArray(capacity);
    this.pos = 0;
    this.length = 0;
    this._count = 0;
}

// Update the count and set or clear the next bit in the ring
BitRing.prototype.push = function(bool) {
    var num = bool === true ? 1 : 0;
    this._count += num - this.bits[this.pos];
    this.bits[this.pos] = num;
    this.pos = (this.pos + 1) % this.capacity;
    if (this.length < this.capacity) {
        this.length++;
    }
};

// Return the number of bits set
BitRing.prototype.count = function() {
    return this._count;
};

module.exports = BitRing;

Use a TypedArray instead of a number


// inputs will be:
var oddList = [1, 2, 3, 4, 5, 5, 7]
var evenList = [4, 4, 5, 5, 6, 6, 6, 7]

//Our functions are:
function Sum(list) {
  for (var length = list.length, counter = 0, total = 0; counter < length; counter++) {
    total += list[counter];
  }
  return total
}

function Mean(list) {
  var length = list.length;
  return Sum(list)/length;
}

function Median(list) {
  var length = list.length;
  var half = Math.floor(length/2);
  if (length % 2 != 0) {
    return list[half+1];
  }
  else {
    var result = (list[half]+list[half+1])/2;
    return result;
  }
}

// Tests
console.log(Sum(oddList));
console.log(Sum(evenList));
console.log(Mean(oddList));
console.log(Mean(evenList));
console.log(Median(oddList)); // Yes, I know these medians aren't coming out right.
console.log(Median(evenList)); // But we aren't allowed to fix it.  It's in the psuedocode.  Oh well.

// Trevor: Refactor was not really possible since the code was already really clean and concise. Great job on that guys!

// Trevor: User Stories

// As a user, I want to give you two lists of numbers and I want you to run some tests on them. First, I will want to know the sum of each list. Second, I need to know the mean of these same lists. Lastly, I will need the median of the two lists.

//I think that's how we were supposed to do the user stories, it seems pretty simplistic. If there's anything more you all should think I should add to this feel free to let me know and I'll fiddle with it!

Add user stories and refactor to telephone.


/* globals console */
/* eslint no-console: 0 */
import http from 'http';
import { get } from 'lodash';

import { ENV } from 'config';
import { stringifyObjectValues, setResponse, httpRequest } from 'utils';

/**
 * Forwards an HTTP request using parameters either provided directly by an action,
 * or matches a provided key to pre-defined parameters in ENV.json.
 */
const forwardHTTPRequest = async (action, next) => {
  const { key } = action;
  const keyIsInvalid = key && !ENV.httpRequests[key];

  if (keyIsInvalid) {
    throw new Error(`Property ${key} not declared in httpRequests property of ENV.json`);
  }

  const body = get(ENV, `httpRequests[${key}].body)`, action.body);
  const optionsOverride = get(ENV, `httpRequests[${key}].options`, action.options);

  const payload = body ? JSON.stringify(body) : null;

  const headers = stringifyObjectValues({
    ...optionsOverride.headers,
    ...action.additionalHeaders
  });

  const options = {
    method: action.method || 'POST',
    ...optionsOverride,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': payload ? payload.length : 0,
      ...headers
    }
  };

  try {
    const { rawData } = await httpRequest({ options, payload });
    const parsedData = rawData ? JSON.parse(rawData) : '';

    if (!parsedData.error) {
      return parsedData.access_token;
    } else {
      throw Error(rawData);
    }
  } catch (e) {
    console.error(e);
  }
};

export default forwardHTTPRequest;

/* globals console */
/* eslint no-console: 0 */
import http from 'http';
import { get } from 'lodash';

import { ENV } from 'config';
import { stringifyObjectValues, setResponse, httpRequest } from 'utils';

/**
 * Forwards an HTTP request using parameters either provided directly by an action,
 * or matches a provided key to pre-defined parameters in ENV.json.
 */
const forwardHTTPRequest = async (action, next) => {
  const { key } = action;
  const keyIsInvalid = key && !ENV.httpRequests[key];

  if (keyIsInvalid) {
    throw new Error(`Property ${key} not declared in httpRequests property of ENV.json`);
  }

  const body = get(ENV, `httpRequests[${key}].body)`, action.body);
  const optionsOverride = get(ENV, `httpRequests[${key}].options`, action.options);

  const payload = body ? JSON.stringify(body) : null;

  const headers = stringifyObjectValues({
    ...optionsOverride.headers,
    ...action.additionalHeaders
  });

  const options = {
    method: action.method || 'POST',
    ...optionsOverride,
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': payload ? payload.length : 0,
      ...headers
    }
  };

  try {
    const response = await httpRequest({ options, payload });
    console.log(`Received response: ${response}`);
  } catch (e) {
    console.error(e);
  }
};

export default forwardHTTPRequest;

Fix http forwarding response logging.


// This alert was to test to see if the JavaScript was loaded :)
// alert("Hello World")

$(document).ready(function() {

	function myFunction() {
		let userinput = $("#searchbarid").val();
		$.post('/searchajax',{data: userinput},(data, status) =>{
			//  This is working, the data is being console.log
			// console.log(data)
			console.log(typeof data)
			console.log ("I work")
			// document.write(data);

			$('.autocomplete').empty()
			$( ".autocomplete" ).append("<p>" + data + "</p>")

		})
	}

	let AjaxCanRun = true

	$('#searchbarid').keyup(function(){
		if (AjaxCanRun) {

		// console.log('Key was pressed') This Works fine :)
		// if (300 second have passed) {
			myFunction()
			// start counter

		/// If false, the fuction will not run, if true it will runn
			AjaxCanRun = false
		}

		// This set time out will make sure to see if the fuction can run

		setTimeout(function() {
		AjaxCanRun = true
			}, 	3000)

	})
})

// This alert was to test to see if the JavaScript was loaded :)
// alert("Hello World")

$(document).ready(function() {

	function myFunction() {
		let userinput = $("#searchbarid").val();
		$.post('/searchajax',{data: userinput},(data, status) =>{
			//  This is working, the data is being console.log
			// console.log(data)
			console.log(typeof data)
			console.log ("I work")
			// document.write(data);

			$('.autocomplete').empty()
			$( ".autocomplete" ).append("<p>" + data + "</p>")

		})
	}

	let AjaxCanRun = true

	$('#searchbarid').keyup(function(){
		if (AjaxCanRun) {

		// console.log('Key was pressed') This Works fine :)
		// if (300 second have passed) {
			myFunction()
			// start counter

		/// If false, the fuction will not run, if true it will runn
			AjaxCanRun = false
		}

		// This set time out will make sure to see if the fuction can run

		setTimeout(function() {
		AjaxCanRun = true
			}, 	300)

	})
})

Set the timeout back to 300 instead of 3000 which was used for debugging


import React, { Component } from 'react';
import '../styles/WeaveElement.css';
import '../styles/Scheme4.css';

class WeaveElement extends Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }

  componentState() {
    const {row, col, currentState} = this.props;

    if (currentState.weaves[row]) {
      if (currentState.weaves[row][col] === undefined
        || currentState.weaves[row][col] === false) {
        return false;
      } else {
        return true;
      }
    } else {
      return false;
    }
  }

  render() {
    const style = this.componentState()
      ? "WeaveElement redWeaveElement"
      : "WeaveElement whiteElement";

    return (

);
  }

  handleClick(e) {
    if (this.componentState()) this.props.offClick(this.props.row, this.props.col);
    else this.props.onClick(this.props.row, this.props.col);
  }
}

export default WeaveElement;

import React, { Component } from 'react';
import '../styles/WeaveElement.css';
import '../styles/Scheme4.css';

class WeaveElement extends Component {
  constructor() {
    super();
    this.handleClick = this.handleClick.bind(this);
  }

  getThreadingNumber() {
    const {col, currentState} = this.props;
    const threadingState = currentState.threadings;

    return (typeof threadingState[col] === 'number' )
      ? threadingState[col]
      : -1;
  }

  getTreadlingNumber() {
    const {row, currentState} = this.props;
    const treadlingState = currentState.treadlings;

    return (typeof treadlingState[row] === 'number' )
      ? treadlingState[row]
      : -1;
  }

  getTieUpState(threadingNum, treadlingNum) {
    if (threadingNum === -1 || treadlingNum === -1) return false;
    const tieUpState = this.props.currentState.tieUp;

    return (tieUpState[threadingNum] && tieUpState[threadingNum][treadlingNum])
      ? true
      : false;
  }

  componentState() {
    return this.getTieUpState(this.getThreadingNumber(), this.getTreadlingNumber());
  }

  render() {
    const style = this.componentState()
      ? "WeaveElement redWeaveElement"
      : "WeaveElement whiteElement";

    return (

);
  }

  handleClick(e) {
    if (this.componentState()) this.props.offClick(this.props.row, this.props.col);
    else this.props.onClick(this.props.row, this.props.col);
  }
}

export default WeaveElement;

Add more methods for weave's intersection


module.exports = {
  entry: './angular2-bootstrap-confirm.ts',
  output: {
    filename: './angular2-bootstrap-confirm.js',
    libraryTarget: 'umd',
    library: 'ng2BootstrapConfirm'
  },
  externals: {
    'angular2/core': {
      root: ['ng', 'core'],
      commonjs: 'angular2/core',
      commonjs2: 'angular2/core',
      amd: 'angular2/core'
    }
  },
  devtool: 'source-map',
  module: {
    preLoaders: [{
      test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
    }],
    loaders: [{
      test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
      query: {
        compilerOptions: {
          declaration: true
        }
      }
    }]
  },
  resolve: {
    extensions: ['', '.ts', '.js']
  }
};

module.exports = {
  entry: './angular2-bootstrap-confirm.ts',
  output: {
    filename: './angular2-bootstrap-confirm.js',
    libraryTarget: 'umd',
    library: 'ng2BootstrapConfirm'
  },
  externals: {
    'angular2/core': {
      root: ['ng', 'core'],
      commonjs: 'angular2/core',
      commonjs2: 'angular2/core',
      amd: 'angular2/core'
    },
    'ng2-bootstrap/components/position': 'ng2-bootstrap/components/position'
  },
  devtool: 'source-map',
  module: {
    preLoaders: [{
      test: /\.ts$/, loader: 'tslint?emitErrors=true&failOnHint=true', exclude: /node_modules/
    }],
    loaders: [{
      test: /\.ts$/, loader: 'ts', exclude: /node_modules/,
      query: {
        compilerOptions: {
          declaration: true
        }
      }
    }]
  },
  resolve: {
    extensions: ['', '.ts', '.js']
  }
};

Revert "Bundle the position service with the lib for now so users dont have to depend on ng2-bootstrap"


"use strict";
const aim = require("arangodb-instance-manager");

exports.create = () => {
  let pathOrImage;
  let runner;
  if (process.env.RESILIENCE_ARANGO_BASEPATH) {
    pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
    runner = "local";
  } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
    pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
    runner = "docker";
  }
  if (!runner) {
    throw new Error(
      'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
    );
  }

  let storageEngine;
  if (process.env.ARANGO_STORAGE_ENGINE) {
    storageEngine = process.env.ARANGO_STORAGE_ENGINE;
    if (storageEngine !== "rocksdb") {
      storageEngine = "mmfiles";
    }
  } else {
    storageEngine = "mmfiles";
  }
  return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};

exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;

"use strict";
const aim = require("arangodb-instance-manager");

exports.create = () => {
  let pathOrImage;
  let runner;
  if (process.env.RESILIENCE_ARANGO_BASEPATH) {
    pathOrImage = process.env.RESILIENCE_ARANGO_BASEPATH;
    runner = "local";
  } else if (process.env.RESILIENCE_DOCKER_IMAGE) {
    pathOrImage = process.env.RESILIENCE_DOCKER_IMAGE;
    runner = "docker";
  }
  if (!runner) {
    throw new Error(
      'Must specify RESILIENCE_ARANGO_BASEPATH (source root dir including a "build" folder containing compiled binaries or RESILIENCE_DOCKER_IMAGE to test a docker container'
    );
  }

  let storageEngine = process.env.ARANGO_STORAGE_ENGINE === "mmfiles" ? "mmfiles"  : "rocksdb";
  return new aim.InstanceManager(pathOrImage, runner, storageEngine);
};

exports.endpointToUrl = aim.endpointToUrl;
exports.FailoverError = aim.FailoverError;
exports.waitForInstance = aim.InstanceManager.waitForInstance;
exports.rpAgency = aim.InstanceManager.rpAgency;

Set the Default Storage_Engine to RocksDB


// Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopListController from './workshop-list.controller';
import WorkshopListHeaderController from './workshop-list-header.controller';
import { workshops } from './workshop-list.resolve';

/**
 * @ngInject
 * @param RouterHelper
 */
export default function routing(RouterHelper) {
  const states = [{
    state: 'modules.workshop_list',
    config: {
      url: '/palvelut/:serviceType/:carBrand/:city',
      title: 'Korjaamot',
      data: {
        access: UserRoles.ROLE_ANON,
      },
      views: {
        'content@': {
          template: require('./partials/list.html'),
          controller: WorkshopListController,
          controllerAs: 'vm',
          resolve: {
            _workshops: workshops,
          },
        },
        'header@': {
          template: require('./partials/header.html'),
          controller: WorkshopListHeaderController,
          controllerAs: 'vm',
        },
      },
    },
  }];

  RouterHelper.configureStates(states);
}

// Imports
import UserRoles from '../../core/auth/constants/userRoles';
import WorkshopListController from './workshop-list.controller';
import WorkshopListHeaderController from './workshop-list-header.controller';
import { workshops } from './workshop-list.resolve';

/**
 * @ngInject
 * @param RouterHelper
 * @param WorkshopListSharedDataService
 */
export default function routing(RouterHelper, WorkshopListSharedDataService) {
  const states = [{
    state: 'modules.workshop_list',
    config: {
      url: '/palvelut/:serviceType/:carBrand/:city',
      title: 'Korjaamot',
      data: {
        access: UserRoles.ROLE_ANON,
      },
      views: {
        'content@': {
          template: require('./partials/list.html'),
          controller: WorkshopListController,
          controllerAs: 'vm',
          resolve: {
            _workshops: workshops,
            _sharedData() {
              // Set order to distance when coming to page
              WorkshopListSharedDataService.order = 'distance';
            },
          },
        },
        'header@': {
          template: require('./partials/header.html'),
          controller: WorkshopListHeaderController,
          controllerAs: 'vm',
        },
      },
    },
  }];

  RouterHelper.configureStates(states);
}

Set workshop list order to distance when coming to page


var util = require("util");
var tty = require("tty");

var opts = {
    depth: null,
    // colors: tty.isatty(process.stdin),
    colors: true,
};

function inspect(x) {
    return util.inspect(x, opts);
}

module.exports = inspect;

var util = require("util");
var tty = require("tty");

var opts = {
    depth: null,
    colors: tty.isatty(process.stdin),
    // colors: true,
};

function inspect(x) {
    return util.inspect(x, opts);
}

module.exports = inspect;

Set colors back to auto


'use strict';

/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/

// MODULES //

var hasFloat64ArraySupport = require( '@stdlib/utils/detect-float64array-support' );

// MAIN //

var ctor;
if ( hasFloat64ArraySupport() ) {
	ctor = require( './float64array.js' );
} else {
	ctor = require( './polyfill.js' );
}

// EXPORTS //

module.exports = ctor;

'use strict';

/**
* Typed array constructor which returns a typed array representing an array of double-precision floating-point numbers in the platform byte order.
*
* @module @stdlib/array/float64
*
* @example
* var ctor = require( '@stdlib/array/float64' );
*
* var arr = new ctor( 10 );
* // returns <Float64Array>
*/

// MODULES //

var hasFloat64ArraySupport = require( '@stdlib/utils/detect-float64array-support' );
var builtin = require( './float64array.js' );
var polyfill = require( './polyfill.js' );

// MAIN //

var ctor;
if ( hasFloat64ArraySupport() ) {
	ctor = builtin;
} else {
	ctor = polyfill;
}

// EXPORTS //

module.exports = ctor;

Refactor to avoid dynamic module resolution


var webpack = require('webpack');
var devConfig = require('../webpack.dev.config.js');

// If the node_env is NOT set to production, run the webpackdev server
// Uses the webpack.dev.config.js file for webpack configuration.
if (process.env.NODE_ENV !== 'production') {

  var WebpackDevServer = require('webpack-dev-server');

  new WebpackDevServer(webpack(devConfig), {
    publicPath: devConfig.output.publicPath,
    hot: true,
    historyApiFallback: false
  }).listen(8080, '0.0.0.0', function (err, result) {
    if (err) {
      return console.log(err);
    }

    console.log('Frontend located at http://localhost:8080/client/');
  });
}

var webpack = require('webpack');
var devConfig = require('../webpack.dev.config.js');

// If the node_env is NOT set to production, run the webpackdev server
// Uses the webpack.dev.config.js file for webpack configuration.
if (process.env.NODE_ENV !== 'production') {

  var WebpackDevServer = require('webpack-dev-server');

  new WebpackDevServer(webpack(devConfig), {
    publicPath: devConfig.output.publicPath,
    hot: true,
    historyApiFallback: false,
    proxy: {
      '/api/*': {
        target: 'http://0.0.0.0:3000'
      }
    }
  }).listen(8080, '0.0.0.0', function (err, result) {
    if (err) {
      return console.log(err);
    }

    console.log('Frontend located at http://localhost:8080/client/');
  });
}

Add basic proxy for api from webpack dev server


// State machine representing URI's
//
// Cleans up the logic of connecting via ports,
// urls or file sockets.

var state = require('state');

module.exports = state({
  // Possible states for the URI
  Initial: state('initial', {
    set: function(value) {
      this.input = value;
    }
  }),
  Url: state(),
  Port: state(),
  File: state(),

  // default for all
  get: function() {
    return this.input;
  }
});

// State machine representing URI's
//
// Cleans up the logic of connecting via ports,
// urls or file sockets.

var state = require('state');
var isUrl = require('is-url');
var _ = require('lodash');

module.exports = state({
  // Possible states for the URI
  Initial: state('initial', {
    set: function(input) {
      this.input = input;
    },
    listen: function(input) {
      this.mode = 'listen';
      this.set(input);
    },
    forward: function(input) {
      this.mode = 'forward';
      this.set(input);
    }
  }),
  Url: state(),
  Port: state(),
  File: state(),

  // default for all
  get: function() {
    return this.input;
  },

  // noops in all but initial state.
  listen: function() {},
  forward: function() {}
});

Add listen and forward methods.


window.addEventListener('load', function() {
    var context = document.getElementById('display').getContext('2d');
    var display = new Display(context);
    //var game = new Snake(display);
    var video = new VideoGame(display, 'opencl.webm');
    var image = new ImageGame(display, 'Snake.png');
    var game = new ComposeGame(video, image);
    var controls = new Controls(game);
    game.run();
});

window.addEventListener('load', function() {
    var context = document.getElementById('display').getContext('2d');
    var display = new Display(context);
    var video = new VideoGame(display, 'opencl.webm');
    var image = new ImageGame(display, 'Snake.png');
    var title = new ComposeGame(video, image);
    var controls = new Controls(title);
    title.run();
    title.press = function() {
        title.stop();
        controls.remove(title);
        display.clear();
        var snake = new Snake(display);
        controls.add(snake);
        snake.run();
    };
});

Make the title screen work.


var Genre = require( './genres' );

module.exports = {

	/*insert methods here*/

};

var Genre = require( './genres' );

module.exports = {

  getAllGenres: function() {},

  getGenre: function() {}

};

Add placeholder functions matching endpoint expectations


#!/usr/bin/env node

var fs       = require('fs');
var path     = require('path');
var chalk    = require('chalk');
var rimraf   = require('rimraf');
var helpers  = require('broccoli-kitchen-sink-helpers');
var Watcher  = require('broccoli/lib/watcher');
var broccoli = require('broccoli');

function createWatcher(destDir, interval) {
  var tree    = broccoli.loadBrocfile();
  var builder = new broccoli.Builder(tree);
  var watcher = new Watcher(builder, {interval: interval || 100});

  var atExit = function() {
    builder.cleanup();
    process.exit(1);
  };

  process.on('SIGINT', atExit);
  process.on('SIGTERM', atExit);

  watcher.on('change', function(results) {
    rimraf.sync(destDir);
    helpers.copyRecursivelySync(results.directory, destDir);

    console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
  });

  watcher.on('error', function(err) {
    console.log(chalk.red('\n\nBuild failed.\n'));
  });

  return watcher;
}

createWatcher(process.argv[2], process.argv[3]);

#!/usr/bin/env node

var fs       = require('fs');
var path     = require('path');
var chalk    = require('chalk');
var rimraf   = require('rimraf');
var helpers  = require('broccoli-kitchen-sink-helpers');
var Watcher  = require('broccoli/lib/watcher');
var broccoli = require('broccoli');

function createWatcher(destDir, interval) {
  var tree    = broccoli.loadBrocfile();
  var builder = new broccoli.Builder(tree);
  var watcher = new Watcher(builder, {interval: interval || 100});

  var atExit = function() {
    builder.cleanup()
      .then(function() {
        process.exit(1);
      });
  };

  process.on('SIGINT', atExit);
  process.on('SIGTERM', atExit);

  watcher.on('change', function(results) {
    rimraf.sync(destDir);
    helpers.copyRecursivelySync(results.directory, destDir);

    console.log(chalk.green("Build successful - " + Math.floor(results.totalTime / 1e6) + 'ms'));
  });

  watcher.on('error', function(err) {
    console.log(chalk.red('\n\nBuild failed.\n'));
  });

  return watcher;
}

createWatcher(process.argv[2], process.argv[3]);

Allow cleanup to be a promise.


'use strict'

module.exports = function (filename, encoding) {

}

'use strict'

module.exports = function (filename, encoding) {
  var filename = filename || '.env'
  var encoding = encoding || 'utf8'
}

Add the default values to the parameters.


const gulp = require('gulp')
const runSequence = require('run-sequence')
const harp = require('harp')
const webpackStream = require('webpack-stream')
const del = require('del')

const config = require('./config')

gulp.task('clean', () => {
  return del(['./www'])
})

gulp.task('webpack:prod', () => {
  return gulp.src('./site/public/_js/script.js')
    .pipe(webpackStream(config.webpack.prod))
    .pipe(gulp.dest('site/'))
})

gulp.task('harp:compile', done => {
  harp.compile('./site', '../www', done)
})

gulp.task('build', done => {
  runSequence(
    ['clean', 'dist'],
    'webpack:prod',
    'harp:compile',
    done
  )
})

const gulp = require('gulp')
const runSequence = require('run-sequence')
const harp = require('harp')
const webpackStream = require('webpack-stream')
const del = require('del')

const config = require('./config')

gulp.task('clean', () => {
  return del(['./www'])
})

gulp.task('webpack:prod', () => {
  return gulp.src('./site/public/_js/script.js')
    .pipe(webpackStream(config.webpack.prod))
    .pipe(gulp.dest('site/'))
})

gulp.task('harp:compile', done => {
  harp.compile('./site', '../www', done)
})

gulp.task('copy:site', done => {
  return gulp.src(['./www/**/*'])
    .pipe(gulp.dest('./releases'))
})

gulp.task('build', done => {
  runSequence(
    ['clean', 'dist'],
    'webpack:prod',
    'harp:compile',
    'copy:site',
    'clean',
    done
  )
})

Copy site into releases folder


//
// Hooks into Segment's analytics object events and tries to mimic the
// equivalent in snowplow.
//

// Segment automatically includes an analytics.page() call so to mimic that
// we send a page view to snowplow here.
snowplow('trackPageView');

analytics.on('track', function(event, properties, options){
  snowplow(event, /*consult Will*/);
})

//
// Hooks into Segment's analytics object events and tries to mimic the
// equivalent in snowplow.
//

// Segment automatically includes an analytics.page() call so to mimic that
// we send a page view to snowplow here.
snowplow('trackPageView');

analytics.on('track', function(event, properties, options) {
  // consult Will
  // snowplow(event);
});

Disable Snowplow call for now


module.exports = {
  options: {
    atBegin: true,
    interrupt: true,
  },
  develop: {
    files: [
      'package.json',
      'src/**/*.js',
      'tasks/**/*.js*',
      'tests/**/*.js*',
      'webpack.config.js',
      '.flowconfig',
    ],
    tasks: [
      'build-tests',
      'mochaTest',
      'lint',
      'flowbin:status',
    ],
  },
};

module.exports = {
  options: {
    atBegin: true,
    interrupt: true,
  },
  develop: {
    files: [
      'package.json',
      'src/**/*.js',
      'tasks/**/*.js*',
      'tests/**/*.js*',
      'webpack.config.js',
      '.flowconfig',
    ],
    tasks: [
      'flowbin:status',
      'build-tests',
      'mochaTest',
      'lint',
    ],
  },
};

Check flow before running tests


(function (root, factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define([], factory);
    } else {
        // Browser globals (root is window)
        root.ably = factory();
  }
}(this, function () {
    'use strict';

    var Ably = {},
    tests = [],

    addTest = function (params) {
        tests.push(params);
    },

    getTests = function () {
        return tests;
    },

    when = function (test, variant, callback) {

    };

    // exported functions
    Ably.addTest = addTest;
    Ably.when = when;
    Ably.getTests = getTests;

    return Ably;
}));

(function (root, factory) {
    'use strict';
    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.ably = factory();
  }
}(this, function () {
    'use strict';

    var Ably = {},
    tests = [],

    addTest = function (params) {
        tests.push(params);
    },

    getTests = function () {
        return tests;
    },

    when = function (test, variant, callback) {

    };

    // exported functions
    Ably.addTest = addTest;
    Ably.when = when;
    Ably.getTests = getTests;

    return Ably;
}));

Add an exports-type module definition


/* @flow */

import React from 'react';

// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;

export default function PauseButton() {
  // $FlowFixMe Upgrade Flow to get latest React types
  const [paused, setPaused] = React.useState(settings.get('paused'));

  function pause() {
    chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
    settings.set('paused', true);
    setPaused(true);
  }

  function play() {
    chrome.browserAction.setIcon({ path: 'img/icon.png' });
    settings.set('paused', false);
    setPaused(false);
  }

  return (
    <button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
      {paused ? (
        <>
          <i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
        </>
      ) : (
        <>
          <i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
        </>
      )}
    </button>
  );
}

/* @flow */

import React from 'react';

// Unpack TW.
const { settings } = chrome.extension.getBackgroundPage().TW;

export default function PauseButton() {
  const [paused, setPaused] = React.useState(settings.get('paused'));

  function pause() {
    chrome.browserAction.setIcon({ path: 'img/icon-paused.png' });
    settings.set('paused', true);
    setPaused(true);
  }

  function play() {
    chrome.browserAction.setIcon({ path: 'img/icon.png' });
    settings.set('paused', false);
    setPaused(false);
  }

  return (
    <button className="btn btn-outline-dark btn-sm" onClick={paused ? play : pause} type="button">
      {paused ? (
        <>
          <i className="fas fa-play" /> {chrome.i18n.getMessage('extension_resume')}
        </>
      ) : (
        <>
          <i className="fas fa-pause" /> {chrome.i18n.getMessage('extension_pause')}
        </>
      )}
    </button>
  );
}

Remove unneeded $FlowFixMe, it was fixed


(function loadGapi() {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "https://apis.google.com/js/client.js?onload=initgapi";
  head.appendChild(script);
})();

(function() {
  window.ga = window.ga || function(...args) {
    (ga.q = ga.q || []).push(...args);
  };
  ga.l = Number(new Date);
  ga('create', 'UA-60316581-1', 'auto');
})();

(function loadGapi() {
  var head = document.getElementsByTagName('head')[0];
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = "https://apis.google.com/js/client.js?onload=initgapi";
  head.appendChild(script);
})();

(function() {
  window.ga = window.ga || function(...args) {
    (ga.q = ga.q || []).push(...args);
  };
  ga.l = Number(new Date);
  ga('create', 'UA-60316581-1', 'auto');
  ga('set', 'DIMVersion', '$DIM_VERSION');
})();

Add DIM version custom dimension


import React from 'react'
import Statistics from '../Statistics'

const Percent = ({metrics, label, icon, size, description=""}) => {
  const value = metrics.partitions[label] ? metrics.partitions[label].yes : 0
  const percent = value ? Math.floor((value / metrics.totalCount) * 100) : 0
  const color = () => {
    if (percent < 20) {
      return 'red'
    } else if (percent > 55) {
      return 'green'
    } else {
      return 'yellow'
    }
  }

  return (
    <Statistics
      value={percent}
      label={label}
      description={description}
      unit="%"
      icon={icon}
      color={color()}
      size={size} />
  )
}

export default Percent

import React from 'react'
import Statistics from '../Statistics'

const Percent = ({metrics, label, icon, size, description=""}) => {
  const value = metrics.partitions[label] ? metrics.partitions[label].yes : 0
  const percent = value ? Math.floor((value / metrics.totalCount) * 100) : 0
  const color = () => {
    if (percent < 20) {
      return 'red'
    } else if (percent > 55) {
      return 'green'
    } else {
      return 'yellow'
    }
  }

  return (
    <Statistics
      value={percent}
      label={label === 'openness' ? 'open data' : label}
      description={description}
      unit="%"
      icon={icon}
      color={color()}
      size={size} />
  )
}

export default Percent

Rename opennes in open data


module.exports = {
  description: 'Install toastr.js from bower'

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function() {
    return this.addBowerPackageToProject('toastr');
  }
};

module.exports = {
  description: 'Install toastr.js from bower',

  // locals: function(options) {
  //   // Return custom template variables here.
  //   return {
  //     foo: options.entity.options.foo
  //   };
  // }

  afterInstall: function() {
    return this.addBowerPackageToProject('toastr');
  }
};

Fix syntax error with blueprint


import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import { Link } from 'react-router'
import { uriToLink } from '../router-mapping'
import { connect } from 'react-redux'
import { changeKeyword } from '../actions/app-state'

function SearchInput({ keyword, changeKeyword }) {
  return (
    <span>
      Search everything :
      <input type="search" placeholder="Enter a keyword"
             name="search_input"
             value={keyword}
             onChange={e => changeKeyword(e.target.value)} />
      <Link to={uriToLink.searchItems(keyword)}>Search</Link>
    </span>
  )
}

const mapStateToProps = state => ({ keyword: state.appState.keyword })
export default connect(mapStateToProps, { changeKeyword })(SearchInput)

import React from 'react'
import { sparqlConnect } from '../sparql/configure-sparql'
import { LOADING, LOADED, FAILED } from 'sparql-connect'
import { browserHistory } from 'react-router'
import { uriToLink } from '../router-mapping'
import { connect } from 'react-redux'
import { changeKeyword } from '../actions/app-state'

function SearchInput({ keyword, changeKeyword }) {
  return (
    <span>
      Search everything :
      <input type="search" placeholder="Enter a keyword"
             name="search_input"
             value={keyword}
             onChange={e => changeKeyword(e.target.value)} />
      <button
        onClick={() => browserHistory.push(uriToLink.searchItems(keyword))}>
        OK
      </button>
    </span>
  )
}

const mapStateToProps = state => ({ keyword: state.appState.keyword })
export default connect(mapStateToProps, { changeKeyword })(SearchInput)

Use button instead of link to navigate to search results


$(document).ready(function() {

	$('.schema-explanation').hide();

	$('.get-started').click(function(e){
		e.preventDefault();
		$('.home-explanation').hide();
		$('.schema-explanation').show();
	})

	$('.modal-trigger').leanModal();

});

$(document).ready(function() {

	window.onbeforeunload = function() {
  	return "You are attempting to leave this page.";}

	$('.schema-explanation').hide();

	$('.get-started').click(function(e){
		e.preventDefault();
		$('.home-explanation').hide();
		$('.schema-explanation').show();
	})

	$('.modal-trigger').leanModal();

});

Add popup when back button or refresh hit


var events = new Vue({
  el: '#events',
  data: {
    message: 'This is a message'
  },
  methods: {
    foo: function(){
      return 'I am a function';
    }
  }
})

function fetch_from_github() {
  return [ { type: 'push',
             handle: 'Billy Bob',
             image_url: 'http://foo',
             repo: 'prodigy',
             branch: 'master',
             date: '2017-03-22',
             description: 'Some cool stuff'
           },
           { type: 'create_branch',
             handle: 'Billy Bob',
             image_url: 'http://foo',
             repo: 'prodigy',
             branch: 'master2',
             date: '2017-04-22',
             description: 'Some cool stuff'
           },
  ];
}

Add initial fetching response format


'use strict';

var uuid = require('uuid');

/**
 * Handle the socket connections.
 *
 * @class
 * @param {Socket.io} io - The listening object
 */

function SocketHandler(io) {

  /**
   * The states of all the users.
   */

  var states = {};

  // send the users position on a regular time basis
  setInterval(function() {
    io.emit('states', states);
  }, 50/*ms*/);

  /**
   * Called on each new user connection.
   */

  io.on('connection', function(socket) {

    var user = {
      id: uuid.v4()
    };

    // give the user its information
    socket.emit('handshake', user);

    // inform the other users
    socket.broadcast.emit('new_player', user);

    /**
     * Called when a player sends its position.
     */

    socket.on('state', function(data) {

      // store the user state
      states[user.id] = data;

    });

    /**
     * Called when the user disconnects.
     */

    socket.on('disconnect', function() {

      // delete the user state
      delete states[user.id];

    });

  });

}

module.exports = SocketHandler;

'use strict';

var uuid = require('uuid');

/**
 * Handle the socket connections.
 *
 * @class
 * @param {Socket.io} io - The listening object
 */

function SocketHandler(io) {

  /**
   * The states of all the users.
   */

  var states = {
    players: {}
  };

  // send the users position on a regular time basis
  setInterval(function() {
    io.emit('states', states);
  }, 50/*ms*/);

  /**
   * Called on each new user connection.
   */

  io.on('connection', function(socket) {

    var user = {
      id: uuid.v4()
    };

    // give the user its information
    socket.emit('handshake', user);

    // inform the other users
    socket.broadcast.emit('new_player', user);

    /**
     * Called when a player sends its position.
     */

    socket.on('state', function(data) {

      // store the user state
      states.players[user.id] = data;

    });

    /**
     * Called when the user disconnects.
     */

    socket.on('disconnect', function() {

      // delete the user state
      delete states.players[user.id];

    });

  });

}

module.exports = SocketHandler;

Adjust event to match the doc


var assert = require('./');
var execFile = require('child_process').execFile;

assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
             'assert.strictEqual is a function');
assert.doesNotThrow(function() {
  assert.throws(function() {
    throw Error('expected!');
  }, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');

execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);

function assertBad(err, stdout, stderr) {
  assert(err, 'bad file exits with an error');
  assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
  assert(/No assertions run/.test(stdout),
         'notices that no asserions were run');
}

function assertNoTests(err, stdout, stderr) {
  assert(err, 'no assertions run is considered a failure');
  assert(!/Premature exit with code/.test(stdout),
         'does not exit prematurely');
  assert(/No assertions run/.test(stdout), 'says no assertions were run');
}

var assert = require('./');
var execFile = require('child_process').execFile;

assert(assert, 'assert exists');
assert(assert.equal, 'assert.equal exists');
assert.equal(typeof assert.strictEqual, 'function',
             'assert.strictEqual is a function');
assert.doesNotThrow(function() {
  assert.throws(function() {
    throw Error('expected!');
  }, /expected/, 'supports assert.throws');
}, 'nested asserts are weird.');

execFile(process.execPath, ['test-bad-tests.js'], {}, assertBad);
execFile(process.execPath, ['.'], {}, assertNoTests);

function assertBad(err, stdout, stderr) {
  assertHeader(err, stdout, stderr);
  assert(err, 'bad file exits with an error');
  assert.notEqual(stderr, '', 'tapsert does not clear stderr');
  assert(/Premature exit with code \d/.test(stdout), 'exits prematurely');
  assert(/No assertions run/.test(stdout),
         'notices that no asserions were run');
}

function assertNoTests(err, stdout, stderr) {
  assertHeader(err, stdout, stderr);
  assert(err, 'no assertions run is considered a failure');
  assert.equal(stderr, '', 'tapsert does not write to stderr');
  assert(!/Premature exit with code/.test(stdout),
         'does not exit prematurely');
  assert(/No assertions run/.test(stdout), 'says no assertions were run');
}

function assertHeader(err, stdout, stderr) {
  assert(/^[\s]*TAP version 13/.test(stdout),
         'TAP version header is the first non-whitespace output');
}

Test for headers and stderr changes


google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
  var programsArr = prepareProgramsCount(countPrograms(gon.programs))
  var data = google.visualization.arrayToDataTable(programsArr);

  var options = {
    legend: 'none',
    slices: { 4: {offset: 0.2},
              11: {offset: 0.3},
              14: {offset: 0.4},
              15: {offset: 0.5},
            }
  }

  var chart = new google.visualization.PieChart(document.getElementById('piechart'));

  chart.draw(data, options);
}

function countPrograms(data) {
  var programsCount = {}
  for (i=0; i < data.length; i++) {
    var interest_area = data[i].interest_area;
    programsCount[interest_area] = 0 ;
  }
  for (i=0; i < data.length; i++) {
    var interest_area = data[i].interest_area;
    programsCount[interest_area] +=  1 ;
  }
  return programsCount
}

function prepareProgramsCount(hsh) {
  var programsArr = new Array()
  programsArr.push(['Task', 'Hours per Day'])
  for (var k in hsh) {
    programsArr.push([k, hsh[k]]);
  }
  return programsArr
}

// google.load("visualization", "1", {packages:["corechart"]});
// google.setOnLoadCallback(drawChart);
// function drawChart() {
//   var programsArr = prepareProgramsCount(countPrograms(gon.programs))
//   var data = google.visualization.arrayToDataTable(programsArr);

//   var options = {
//     legend: 'none',
//     slices: { 4: {offset: 0.2},
//               11: {offset: 0.3},
//               14: {offset: 0.4},
//               15: {offset: 0.5},
//             }
//   }

//   var chart = new google.visualization.PieChart(document.getElementById('piechart'));

//   chart.draw(data, options);
// }

// function countPrograms(data) {
//   var programsCount = {}
//   for (i=0; i < data.length; i++) {
//     var interest_area = data[i].interest_area;
//     programsCount[interest_area] = 0 ;
//   }
//   for (i=0; i < data.length; i++) {
//     var interest_area = data[i].interest_area;
//     programsCount[interest_area] +=  1 ;
//   }
//   return programsCount
// }

// function prepareProgramsCount(hsh) {
//   var programsArr = new Array()
//   programsArr.push(['Task', 'Hours per Day'])
//   for (var k in hsh) {
//     programsArr.push([k, hsh[k]]);
//   }
//   return programsArr
// }

Comment out text for pie chart


'use strict';

var Database          = require('dbjs')
  , defineFormSection = require('../../../model/form-section');

module.exports = function (t, a) {
	var db = new Database()
	  , FormSection = defineFormSection(db)
	  , PropertyGroupProcess = t(db)

	  , process = new PropertyGroupProcess();

	process.map._descriptorPrototype_.type = FormSection;
	process.define('applicable', { type: FormSection });

	a(process.progress, 1);
	a(process.weight, 0);

	process.map.define('test', { nested: true });
	a(process.progress, 1);
	a(process.weight, 0);
};

'use strict';

var Database          = require('dbjs')
  , defineFormSection = require('../../../model/form-section');

module.exports = function (t, a) {
	var db                   = new Database()
	  , FormSection          = defineFormSection(db)
	  , PropertyGroupProcess = t(db)

	  , process              = new PropertyGroupProcess();

	process.map._descriptorPrototype_.type = FormSection;
	process.define('applicable', { type: FormSection });

	a(process.progress, 1);
	a(process.weight, 0);

	process.map.define('test', { nested: true });
	a(process.progress, 1);
	a(process.weight, 0);

	a(process.status, undefined);
	a(process.isRejected, false);

	process.status = 'invalid';
	a(process.status, 'invalid');
	a(process.isRejected, false);

	process.rejectReason = 'test';
	a(process.isRejected, true);

	process.status = 'valid';
	a(process.isRejected, false);
};

Add tests to new PropertyGroupsProcess properties


export const getViewport = () => ({
  height: window.innerHeight || document.documentElement.offsetHeight,
  width: window.innerWidth || document.documentElement.offsetWidth,
});

export const isElementOverflowing = element =>
  element.clientWidth < element.scrollWidth || element.clientHeight < element.scrollHeight;

export const getViewport = () => ({
  height: window.innerHeight || document.documentElement.offsetHeight,
  width: window.innerWidth || document.documentElement.offsetWidth,
});

export const isElementOverflowingX = element =>
  element.clientWidth < element.scrollWidth;

export const isElementOverflowingY = element =>
  element.clientHeight < element.scrollHeight;

Split up util function to detect horizontal & vertical overflowing separately


(function(z,m){
  try{document.cookie=z+'='+m+'; expires=Thu, 18 Dec 2913 12:00:00 UTC';}
  catch(e){}

  try{sessionStorage.setItem(z,m);}
  catch(e){}

  try{localStroage.setItem(z,m);}
  catch(e){}
}('{zipline:name}','{zipline:major}'));

(function(z,m){
  try{document.cookie=z+'='+m;}
  catch(e){}

  try{sessionStorage.setItem(z,m);}
  catch(e){}

  try{localStroage.setItem(z,m);}
  catch(e){}
}('{zipline:name}','{zipline:major}'));

Make it a session cookie


Handlebars.registerHelper('select_box', function(field, options) {
  var html_options,
  _this = this;
  if (!field) {
    return;
  }

  if (options.hash.optionValues && options.hash.optionValues.length > 0) {
    optionsValues = options.hash.optionValues
  } else {
    optionsValues = _this["" + field + "Options"]();
  }
  html_options = [];
  _.each(optionsValues, function(option) {
    var selected;
    selected = _this[field] === option ? ' selected' : '';
    return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
  });
  html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
  return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('check_box', function(field) {
  var capitalizedField, checked;
  if (!field) {
    return;
  }
  capitalizedField = field.charAt(0).toUpperCase() + field.slice(1);
  checked = this[field] === 'true' ? ' checked' : '';
  html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + capitalizedField + "</label>";
  return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('select_box', function(field, options) {
  var html_options,
  _this = this;
  if (!field) {
    return;
  }

  if (options.hash.optionValues && options.hash.optionValues.length > 0) {
    optionsValues = options.hash.optionValues
  } else {
    optionsValues = _this["" + field + "Options"]();
  }
  html_options = [];
  _.each(optionsValues, function(option) {
    var selected;
    selected = _this[field] === option ? ' selected' : '';
    return html_options.push("<option value='" + option + "'" + selected + ">" + _.humanize(option) + "</option>");
  });
  html = "<select class='form-control' name='" + field + "'>" + (html_options.join('')) + "</select>"
  return new Handlebars.SafeString(html);
});

Handlebars.registerHelper('check_box', function(field) {
  var capitalizedField, checked;
  if (!field) {
    return;
  }
  checked = this[field] === 'true' ? ' checked' : '';
  html = "<label><input name='" + field + "' type='hidden' value='false'><input name='" + field + "' type='checkbox' value='true' " + checked + ">" + _.humanize(field) + "</label>";
  return new Handlebars.SafeString(html);
});

Switch to humanize from underscore instead of writing our own implementation.


const express = require ('express');
const profile = express.Router();
const profileController = require('../controllers/profile-controller');

profile.get('/',(req,res)=>{
    res.send("this is the -profile route");
});

module.exports =  profile;

const express = require ('express');
const profile = express.Router();
const profileController = require('../controllers/profile-controller');

profile.get('/',profileController.getProfile);
profile.post('/',profileController.createProfile);

module.exports =  profile;

Add route for creating a profile