/* Set up the environment before loading the rest of the files into Zotero */
var $rdf = {
  Util: {
    ArrayIndexOf: function (arr, item, i) {
      //supported in all browsers except IE<9
      return arr.indexOf(item, i);
    },
    RDFArrayRemove: function (a, x) { //removes all statements equal to x from a
      for(var i = 0; i < a.length; i++) {
        //TODO: This used to be the following, which didnt always work..why
        //if(a[i] == x)
        if(a[i].subject.sameTerm(x.subject)
          && a[i].predicate.sameTerm(x.predicate)
          && a[i].object.sameTerm(x.object)
          && a[i].why.sameTerm(x.why)) {
          a.splice(i, 1);
          return;
        }
      }
      throw "RDFArrayRemove: Array did not contain " + x;
    },
  },
  log: {
  	debug: Zotero.debug,
  	warn: Zotero.debug
	}
};

if(Zotero.RDF) {
	Zotero.RDF.AJAW = $rdf;
} else {
	Zotero.RDF = {AJAW:$rdf};
}

var tabulator = {log: $rdf.log};
var alert = $rdf.log.warn;

/* Set up the environment before loading the rest of the files into Zotero */
var $rdf = {
	Util: {
		ArrayIndexOf: function (arr, item, i) {
			//supported in all browsers except IE<9
			return arr.indexOf(item, i);
		},
		RDFArrayRemove: function (a, x) { //removes all statements equal to x from a
			for (var i = 0; i < a.length; i++) {
				//TODO: This used to be the following, which didnt always work..why
				//if(a[i] == x)
				if (a[i].subject.sameTerm(x.subject) && a[i].predicate.sameTerm(x.predicate) && a[i].object.sameTerm(x.object) && a[i].why.sameTerm(x.why)) {
					a.splice(i, 1);
					return;
				}
			}
			throw "RDFArrayRemove: Array did not contain " + x;
		}
	},
	log: {
		debug: Zotero.debug,
		warn: Zotero.debug
	}
};

if(Zotero.RDF) {
	Zotero.RDF.AJAW = $rdf;
} else {
	Zotero.RDF = {AJAW:$rdf};
}

var tabulator = {log: $rdf.log};
var alert = $rdf.log.warn;

Fix indentation and IE parse error


"use strict";

const TsReader = require("../reader");
const TsDescriptorBase = require("./base");

class TsDescriptorEmergencyInformation extends TsDescriptorBase {
    constructor(buffer) {
        super(buffer);
    }

    decode() {
        const reader = new TsReader(this._buffer);
        const objDescriptor = {};

        objDescriptor.descriptor_tag = reader.uimsbf(8);
        objDescriptor.descriptor_length = reader.uimsbf(8);

        objDescriptor.services = [];

        for (const l = 2 + objDescriptor.descriptor_length; reader.position >> 3 < l; ) {
            const service = {};

            service.service_id = reader.uimsbf(16);
            service.start_end_flag = reader.bslbf(1);
            service.signal_level = reader.bslbf(1);
            reader.next(6);    // reserved_future_use
            service.area_code_length = reader.uimsbf(8);
            service.area_codes = [];

            for (const length = (reader.position >> 3) + objDescriptor.area_code_length; reader.position >> 3 < length; ) {
                const area_code = {};

                area_code.area_code = reader.bslbf(12);
                reader.next(4);    // reserved_future_use

                service.area_codes.push(area_code);
            }

            objDescriptor.services.push(service);
        }

        return objDescriptor;
    }
}

module.exports = TsDescriptorEmergencyInformation;

"use strict";

const TsReader = require("../reader");
const TsDescriptorBase = require("./base");

class TsDescriptorEmergencyInformation extends TsDescriptorBase {
    constructor(buffer) {
        super(buffer);
    }

    decode() {
        const reader = new TsReader(this._buffer);
        const objDescriptor = {};

        objDescriptor.descriptor_tag = reader.uimsbf(8);
        objDescriptor.descriptor_length = reader.uimsbf(8);

        objDescriptor.services = [];

        for (const l = 2 + objDescriptor.descriptor_length; reader.position >> 3 < l; ) {
            const service = {};

            service.service_id = reader.uimsbf(16);
            service.start_end_flag = reader.bslbf(1);
            service.signal_level = reader.bslbf(1);
            reader.next(6);    // reserved_future_use
            service.area_code_length = reader.uimsbf(8);
            service.area_codes = [];

            for (const length = (reader.position >> 3) + service.area_code_length; reader.position >> 3 < length; ) {
                const area_code = {};

                area_code.area_code = reader.bslbf(12);
                reader.next(4);    // reserved_future_use

                service.area_codes.push(area_code);
            }

            objDescriptor.services.push(service);
        }

        return objDescriptor;
    }
}

module.exports = TsDescriptorEmergencyInformation;

Fix a bug of TsDescriptorEmergencyInformation


import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
import { siteName } from '../../../config';

export default class LoginContainer extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
  }

  state = { siteLogo: null }

  componentWillMount() { document.body.classList.add('body--grey'); }

  componentDidMount() {
    get('/admin/api/site').then(({ data }) => {
      this.setState({ siteLogo: data.siteLogo });
    });
  }

  componentWillUnmount() { document.body.classList.remove('body--grey'); }

  render() {
    const { siteLogo } = this.state;
    const { children } = this.props;

    return (

        {siteLogo ? <img style={{ maxWidth: '420px', maxHeight: '200px', margin: '1em auto' }} src={`/public/assets/${siteLogo.filename}`} alt={siteName} /> : <FlintLogo width={140} height={80} />}
        {children}
        <Link to="/admin/fp" className="login__forgot">Forgot your password?</Link>
        {siteLogo && <FlintLogo poweredBy width={100} height={25} />}

    );
  }
}

import React, { Component, PropTypes } from 'react';
import { Link } from 'react-router';
import { get } from 'axios';
import FlintLogo from 'components/FlintLogo';
import './LoginContainer.scss';
import { siteName } from '../../../config';

export default class LoginContainer extends Component {
  static propTypes = {
    children: PropTypes.object.isRequired,
  }

  state = { siteLogo: null, isFetching: true }

  componentWillMount() { document.body.classList.add('body--grey'); }

  componentDidMount() {
    get('/admin/api/site').then(({ data }) => {
      this.setState({ siteLogo: data.siteLogo, isFetching: false });
    });
  }

  componentWillUnmount() { document.body.classList.remove('body--grey'); }

  render() {
    const { siteLogo, isFetching } = this.state;
    const { children } = this.props;

    if (isFetching) return null;

    return (

        {siteLogo ? <img style={{ maxWidth: '420px', maxHeight: '200px', margin: '1em auto' }} src={`/public/assets/${siteLogo.filename}`} alt={siteName} /> : <FlintLogo width={140} height={80} />}
        {children}
        <Link to="/admin/fp" className="login__forgot">Forgot your password?</Link>
        {siteLogo && <FlintLogo poweredBy width={100} height={25} />}

    );
  }
}

Add loading check for Login container


'use strict';

var kanjiApp = angular.module('kanjiApp', []);

kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
  $scope.saved = ["blah"];
  $scope.findKanji = search.findKanji;
  $scope.findWords = search.findWords;
  $scope.getKanjiMeaning = kanjiDictionary.getMeaning;
  $scope.wordSearchResults = ["happy"];
  $scope.kanjiSearchResults = ["日"];
  $scope.updateSearchResults = function(query) {
    search.findKanji($scope.query).then(function(results) {
        console.log("Inside kanji callback");
        $scope.kanjiSearchResults = results;
        console.log($scope.kanjiSearchResults);
    });

    search.findWords($scope.query).then(function(results) {
        console.log("Inside words callback");
        $scope.wordSearchResults = results;
        console.log($scope.wordSearchResults);
    });
  };

  $scope.searchDisabled = true;
  search.onReady(function() {
      console.log("Enabling search");
      $scope.searchDisabled = false;
  });
}]);

'use strict';

var kanjiApp = angular.module('kanjiApp', []);

kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
  $scope.saved = [];
  $scope.findKanji = search.findKanji;
  $scope.findWords = search.findWords;
  $scope.getKanjiMeaning = kanjiDictionary.getMeaning;
  $scope.wordSearchResults = [];
  $scope.kanjiSearchResults = [];
  $scope.updateSearchResults = function(query) {
    search.findKanji($scope.query).then(function(results) {
        console.log("Inside kanji callback");
        $scope.kanjiSearchResults = results;
        console.log($scope.kanjiSearchResults);
    });

    search.findWords($scope.query).then(function(results) {
        console.log("Inside words callback");
        $scope.wordSearchResults = results;
        console.log($scope.wordSearchResults);
    });
  };

  $scope.searchDisabled = true;
  search.onReady(function() {
      console.log("Enabling search");
      $scope.searchDisabled = false;
  });
}]);

Remove placeholders in the controller arrays


import React from "react";
import { connect } from "react-redux";

import ChessBoardSquare from "components/chess-board-square";

class ChessBoard extends React.Component {
  getBoard() {
    const { store } = this.props;
    return store.getState().board;
  }

  renderFiles(rankId) {
    const rank = this.getBoard()[rankId];

    return Object.keys(rank).map((fileId) => {
      return (
        <ChessBoardSquare
          file={fileId}
          key={fileId}
          rank={rankId}
          square={rank[fileId]}
        />
      );
    });
  }

  renderRanks() {
    const board = this.getBoard();

    return Object.keys(board).reverse().map((rankId) => {
      return (

          {this.renderFiles(rankId)}

      );
    });
  }

  render() {
    return
{this.renderRanks()}
;
  }
}

function mapStateToProps(state) {
  return { selectedSquare: state.selectedSquare }
}

export default connect(mapStateToProps)(ChessBoard);

import React from "react";
import { connect } from "react-redux";

import ChessBoardSquare from "components/chess-board-square";

class ChessBoard extends React.Component {
  getBoard() {
    const { store } = this.props;
    return store.getState().board;
  }

  renderFiles(rankId) {
    const { store } = this.props;
    const rank = this.getBoard()[rankId];

    return Object.keys(rank).map((fileId) => {
      return (
        <ChessBoardSquare
          file={fileId}
          key={fileId}
          rank={rankId}
          piece={rank[fileId]}
          store={store}
        />
      );
    });
  }

  renderRanks() {
    const board = this.getBoard();

    return Object.keys(board).reverse().map((rankId) => {
      return (

          {this.renderFiles(rankId)}

      );
    });
  }

  render() {
    return
{this.renderRanks()}
;
  }
}

function mapStateToProps(state) {
  return { selectedSquare: state.selectedSquare }
}

export default connect(mapStateToProps)(ChessBoard);

Fix problem caused by Rob


import DS from "ember-data";

var attr = DS.attr;

var Problem = DS.Model.extend({
  title: attr(),
  description: attr(),

  contest: DS.belongsTo('contest')
});

export default Problem;

import DS from "ember-data";

var attr = DS.attr;

var Problem = DS.Model.extend({
  createdAt   : attr();
  updatedAt   : attr();
  author      : attr(),
  title       : attr(),
  description : attr(),
  inputs      : attr(),
  outputs     : attr(),

  contest: DS.belongsTo('contest')
});

export default Problem;

Add some extra fields to Problem model :smile:


import Ember from 'ember';

export default Ember.Route.extend({
    model(params) {
        return this.store.findRecord('experiment', params.experiment_id).then((experiment) => {
            // When page loads, creates new session, but doesn't save to store
            var session = this.store.createRecord(experiment.get('sessionCollectionId'), {
                experimentId: experiment.id,
                profileId: 'tester0.prof1', // TODO fetch from service
                profileVersion: '',
                softwareVersion: ''
            });
            experiment.getCurrentVersion().then(function(versionId) {
                session.set('experimentVersion', versionId);
            });  // TODO: May be an edge case where experimentVersion isn't set/ resolved before this hash returns
            return Ember.RSVP.hash({
                experiment: experiment,
                session: session
            });
        });
    },

    actions: {
        willTransition: function(transition) {
            // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
            if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
                transition.abort();
                return false;
            } else {
                // Bubble this action to parent routes
                return true;
            }
        }
    }
});

import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    model(params) {
        var parentParams = this.paramsFor('experiments.info');

        return this.store.findRecord('experiment', parentParams.experiment_id).then((experiment) => {
            // When page loads, creates new session, but doesn't save to store
            var session = this.store.createRecord(experiment.get('sessionCollectionId'), {
                experimentId: experiment.id,
                profileId: 'tester0.prof1', // TODO fetch from service
                profileVersion: '',
                softwareVersion: ''
            });
            experiment.getCurrentVersion().then(function(versionId) {
                session.set('experimentVersion', versionId);
            });  // TODO: May be an edge case where experimentVersion isn't set/ resolved before this hash returns
            return Ember.RSVP.hash({
                experiment: experiment,
                session: session
            });
        });
    },

    actions: {
        willTransition: function(transition) {
            // FIXME: This won't prevent back button or manual URL change. See https://guides.emberjs.com/v2.3.0/routing/preventing-and-retrying-transitions/#toc_preventing-transitions-via-code-willtransition-code
            if (this.controller.isDirty() && !confirm('Are you sure you want to exit the experiment?')) {
                transition.abort();
                return false;
            } else {
                // Bubble this action to parent routes
                return true;
            }
        }
    }
});

Fix params in nested route


function showVideo() {
  // Show player
  var block = document.getElementById("player");
  if (block) {
    block.style.visibility = "visible";
  }
}

function hideVideo() {
  var vid = document.getElementsByTagName('video')[0];
  if (vid) {
    vid.addEventListener("canplaythrough", showVideo, true);
  }

  // Safari needs help
  window.setTimeout(showVideo, 500);
}

(function () {
  // Add 'js' class to head element if Javascript is enabled
  document.documentElement.className += " js";
}());

"use strict";

function showControls() {
  var vid = document.getElementsByTagName('video')[0];
  if (vid) {
    vid.setAttribute("controls", "true")
  }
}

function showVideo() {
  // Show player
  var block = document.getElementById("player");
  if (block) {
    block.style.visibility = "visible";
  }

  // Chrome needs a delay
  window.setTimeout(showControls, 500)
  window.setTimeout(showControls, 1000)
  window.setTimeout(showControls, 2000)
  window.setTimeout(showControls, 5000)
}

function hideVideo() {
  var vid = document.getElementsByTagName("video")[0];
  if (vid) {
    vid.addEventListener("canplay", showVideo);

    // Hide controls
    // vid.removeAttribute("controls")
  }

  // Safari needs help
  window.setTimeout(showVideo, 500);
}

// Add 'js' class to head element if Javascript is enabled
(function () {
  document.documentElement.className += " js";
}());

Fix for Chrome video controls


'use strict';

angular.module('integrationApp')
  .directive('faScrollView', function (famous) {
    return {
      template: '

',
      restrict: 'E',
      transclude: true,
      link: function postLink(scope, element, attrs) {
      },
      compile: function(tElem, tAttrs, transclude){
        return  {
          pre: function(scope, element, attrs){

            var ScrollView = famous["famous/views/scrollview"];
            var ViewSequence = famous['famous/core/viewsequence'];
            var Surface = famous['famous/core/surface'];

            var surfaces = new ViewSequence();

            for(var i = 0; i < 50; i++) {
                surfaces.push(new Surface({content: 'Item ' + i, size:[100, 20]}));
            }

            console.log("surfaces", surfaces)

            scope.view = new ScrollView({
              itemSpacing: 1
            });

            scope.view.sequenceFrom(surfaces);

            window.Engine.pipe(scope.view);

            scope.$on('registerChild', function(evt, data){
              if(evt.targetScope.$id != scope.$id){
                console.log("scroll view registered", data);
                evt.stopPropagation();
              };
            });
            scope.modifier = {};
          },
          post: function(scope, element, attrs){
            transclude(scope, function(clone) {
              element.find('div').append(clone);
            });
            scope.$emit('registerChild', {view: scope.view, mod: scope.modifier});
          }
        };
      },
      scope: {}
    };
  });

'use strict';

angular.module('integrationApp')
  .directive('faScrollView', function (famous) {
    return {
      template: '

',
      restrict: 'E',
      transclude: true,
      link: function postLink(scope, element, attrs) {
      },
      compile: function(tElem, tAttrs, transclude){
        return  {
          pre: function(scope, element, attrs){

            var ScrollView = famous["famous/views/scrollview"];
            var ViewSequence = famous['famous/core/viewsequence'];
            var Surface = famous['famous/core/surface'];

            var surfaces = new ViewSequence();

            for(var i = 0; i < 50; i++) {
                surfaces.push(new Surface({content: 'Item ' + i, size:[100, 20]}));
            }

            var _children = [];

            console.log("surfaces", surfaces)

            scope.view = new ScrollView({
              itemSpacing: 1
            });

            window.Engine.pipe(scope.view);

            scope.$on('registerChild', function(evt, data){
              if(evt.targetScope.$id != scope.$id){
                console.log("scroll view registered", data);
                _children.push(data.view);
                scope.view.sequenceFrom(_children);
                evt.stopPropagation();
              };
            });
            scope.modifier = {};
          },
          post: function(scope, element, attrs){
            transclude(scope, function(clone) {
              element.find('div').append(clone);
            });
            scope.$emit('registerChild', {view: scope.view, mod: scope.modifier});
          }
        };
      },
      scope: {}
    };
  });

Use real children for scrollview


'use strict';

myApp.factory('Message', ['$resource', function ($resource) {
    return $resource('http://localhost:8080/api/timeline');
}]);

myApp.controller('TimeLineController', function ($scope, $timeout, Message, $cookies, $location) {
    $scope.currentTimeline = 0;

<<<<<<< HEAD
    $scope.update = function () {
        $scope.messages = Message.query();
        $scope.currentTimeline = $scope.currentTimeline + 1;
        $timeout($scope.update, 10000);
    };

    $scope.update();

    $scope.disconnect = function () {
        $cookies.token = null;
        $location.path("/auth");
    };
});

myApp.controller('AuthController', function ($http, $scope, $cookies, $base64, $location) {
    $scope.auth = function (email, password) {
        $cookies.token = $base64.encode(email + ":" + password);
        $http.defaults.headers.common['Authorization'] = "Basic " + $cookies.token;
        $location.path("/timeline");
    };
});
=======
        $scope.update = function() {
            $http.get('timeline' + $scope.currentTimeline % 2 + '.json').success(function (data) {
                $scope.messages = data;
                $scope.currentTimeline = $scope.currentTimeline + 1;
                $timeout($scope.update, 10000);
            });
        };
        $scope.update();
    }]);
>>>>>>> Webdesign part

'use strict';

myApp.factory('Message', ['$resource', function ($resource) {
    return $resource('http://localhost:8080/api/timeline');
}]);

myApp.controller('TimeLineController', function ($scope, $timeout, Message, $cookies, $location) {
    $scope.currentTimeline = 0;

    $scope.update = function () {
        $scope.messages = Message.query();
        $scope.currentTimeline = $scope.currentTimeline + 1;
        $timeout($scope.update, 10000);
    };

    $scope.update();

    $scope.disconnect = function () {
        $cookies.token = null;
        $location.path("/auth");
    };
});

myApp.controller('AuthController', function ($http, $scope, $cookies, $base64, $location) {
    $scope.auth = function (email, password) {
        $cookies.token = $base64.encode(email + ":" + password);
        $http.defaults.headers.common['Authorization'] = "Basic " + $cookies.token;
        $location.path("/timeline");
    };
});

FIX : merge little mistake


$(document).ready(function() {

  $("form.contact").on("submit", function(e) {
    var $fadeElement = $(".fade-on-submit");
    if (!$fadeElement) return;

    e.preventDefault();
    fadeOutAndRevealBeneath($fadeElement);
  });

  var imageId = 1;
  $("img.replaceable").on("click", function() {
    var image = $(this);

    imageId++;
    if (imageId > 3) imageId = 1;

    image.attr("src", "assets/timeline_images/" + imageId + ".jpg");
  });

  $(".switch-on-click").on("click", function() {
    fadeOutAndRevealBeneath($(this), 200, function() {
      $("#searchField").focus();
    });
  });

  function fadeOutAndRevealBeneath(element, speed, completionFunction) {
    if (!speed) speed = 400;

    var hidden = $(".hidden");
    element.fadeOut(speed, function() {
      hidden.fadeIn(speed, function() {
        hidden.removeClass("hidden");
        completionFunction();
      });
    });
  }
});

$(document).ready(function() {

  $("form.contact").on("submit", function(e) {
    var $fadeElement = $(".fade-on-submit");
    if (!$fadeElement) return;

    e.preventDefault();
    fadeOutAndRevealBeneath($fadeElement);
  });

  var imageId = 1;
  $("img.replaceable").on("click", function() {
    var image = $(this);

    imageId++;
    if (imageId > 3) imageId = 1;

    image.attr("src", "assets/timeline_images/" + imageId + ".jpg");
  });

  $(".switch-on-click").on("click", function() {
    fadeOutAndRevealBeneath($(this), 200, function() {
      $("#searchField").focus();
    });
  });

  function fadeOutAndRevealBeneath(element, speed, completionFunction) {
    if (!speed) speed = 400;

    var hidden = element.siblings(".hidden");
    element.fadeOut(speed, function() {
      hidden.fadeIn(speed, function() {
        hidden.removeClass("hidden");
        completionFunction();
      });
    });
  }
});

Fix a bug, where fading in .hidden on contact page would also fade in searchField, since there was a class collision.


define(['underscore', 'jquery'], function(_, $) {
  return function(app) {
    app.components.before('initialize', function() {
      "use strict";
      if (this.require && this.require.paths) {
        var dfd = $.Deferred();
        var requireConfig = this.require;
        var localRequire = require.config(_.extend(requireConfig, {
          context: 'context-' + this.ref,
          baseUrl: this.options.require.packages[0].location
        }));
        localRequire(_.keys(this.require.paths), function(deps) {
          dfd.resolve();
        }, function (err) {
          dfd.reject(err);
        });
        this.require = localRequire;
        return dfd.promise();
      }
    });
  };
});

define(['underscore', 'jquery'], function(_, $) {
  return function(app) {
    app.components.before('initialize', function() {
      "use strict";
      if (this.require && this.require.paths) {
        var dfd = $.Deferred();
        var requireConfig = this.require;
        var localRequire = require.config(_.extend(requireConfig, {
          // context: 'context-' + this.ref,
          baseUrl: this.options.require.packages[0].location
        }));
        localRequire(_.keys(this.require.paths), function(deps) {
          dfd.resolve();
        }, function (err) {
          dfd.reject(err);
        });
        this.require = localRequire;
        return dfd.promise();
      }
    });
  };
});

Remove Contexts for now so we don't step in to dependency hell


function failure() {
	const root = document.documentElement

	root.classList.remove('sr')

	return {
		clean() {},
		destroy() {},
		reveal() {},
		sync() {},
		get noop() {
			return true
		}
	}
}

function success() {
	const html = document.documentElement
	const body = document.body

	html.classList.add('sr')

	if (body) {
		body.style.height = '100%'
	} else {
		document.addEventListener('DOMContentLoaded', () => {
			body.style.height = '100%'
		})
	}
}

export default { success, failure }

function failure() {
	const root = document.documentElement

	root.classList.remove('sr')

	return {
		clean() {},
		destroy() {},
		reveal() {},
		sync() {},
		get noop() {
			return true
		}
	}
}

function success() {
	const html = document.documentElement
	const body = document.body

	html.classList.add('sr')

	if (body) {
		body.style.height = '100%'
	} else {
		document.addEventListener('DOMContentLoaded', () => {
			document.body.style.height = '100%'
		})
	}
}

export default { success, failure }

Fix attempted property assignment on null


define(function() {

  // Export
  return function(Prism) {

    Prism.languages.java = Prism.languages.extend('clike', {
    	'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g,
    	'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+[e]?[\d]*[df]\b|\W\d*\.?\d+\b/gi,
    	'operator': {
    		pattern: /([^\.]|^)([-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|%|\^|(<){2}|($gt;){2,3}|:|~)/g,
    		lookbehind: true
    	}
    });

  };

});

define(function() {
  return function(Prism) {
    Prism.languages.java = Prism.languages.extend('clike', {
      'keyword': /\b(abstract|continue|for|new|switch|assert|default|goto|package|synchronized|boolean|do|if|private|this|break|double|implements|protected|throw|byte|else|import|public|throws|case|enum|instanceof|return|transient|catch|extends|int|short|try|char|final|interface|static|void|class|finally|long|strictfp|volatile|const|float|native|super|while)\b/g,
      'number': /\b0b[01]+\b|\b0x[\da-f]*\.?[\da-fp\-]+\b|\b\d*\.?\d+[e]?[\d]*[df]\b|\W\d*\.?\d+\b/gi,
      'operator': {
        pattern: /([^\.]|^)([-+]{1,2}|!|=?<|=?>|={1,2}|(&){1,2}|\|?\||\?|\*|\/|%|\^|(<){2}|($gt;){2,3}|:|~)/g,
        lookbehind: true
      }
    });
  };
});

Fix indentation of the Java grammar


module.exports = {
  description: 'Add bower dependencies for bootstrap and bootswatch to the project',

  normalizeEntityName: function() {
    // allows us to run ember -g ember-cli-bootswatch and not blow up
    // because ember cli normally expects the format
    // ember generate <entitiyName> <blueprint>
  },

  afterInstall: function(options) {
    var addon = this;

    // Ability to add multiple bower packages introduced in ember-cli 0.1.2
    if (addon.addBowerPackagesToProject) {
      return addon.addBowerPackagesToProject([
        {name: 'bootstrap', target: '^3.3.5'},
        {name: 'bootswatch', target: '^3.3.5'}
      ]);
    } else { // Else need to add them individually
      return addon.addBowerPackageToProject('bootstrap', '^3.3.5').then(function(){
        return addon.addBowerPackageToProject('bootswatch', '^3.3.5');
      });
    }

  } // :afterInstall

};

/*jshint node:true*/

module.exports = {
  description: '',

  afterInstall: function(options) {
    return this.addBowerPackagesToProject([
      {name: 'bootstrap', target: '^3.3.6'},
      {name: 'bootswatch', target: '^3.3.6'}
    ]);
  } // :afterInstall

}; // module.exports

Update bower deps and slimed down the blueprint


$(function() {
	if(sessionStorage.getItem("openMenu") === null){
		sessionStorage.setItem("openMenu", "yes" );
	}
	if(sessionStorage.getItem("openMenu") == "yes"){
			$(".mainmenu").show();
	}
	$("#menu-toggle").click(function() {
		$(".mainmenu").slideToggle();
			if(sessionStorage.getItem("openMenu") == "yes"){
					sessionStorage.setItem("openMenu", "no" );
				} else {
						sessionStorage.setItem("openMenu", "yes" );
				}
	});
});

$(function() {
	if(sessionStorage.getItem("openMenu") === null){
		sessionStorage.setItem("openMenu", "yes" );
	}
	if(sessionStorage.getItem("openMenu") == "yes"){
			$(".mainmenu").slideDown();
	}
	$("#menu-toggle").click(function() {
		$(".mainmenu").slideToggle();
			if(sessionStorage.getItem("openMenu") == "yes"){
					sessionStorage.setItem("openMenu", "no" );
				} else {
						sessionStorage.setItem("openMenu", "yes" );
				}
	});
});

Revert "keine slidedown animation mehr"


/* eslint-disable */
/* DEPRECATED DO NOT USE */
import React from 'react';
import cx from 'classnames';
import styles from './index.css';

export const FlexRow = ({
  children,
  className,
  justifyContent,
  alignItems,
  flexWrap,
  style,
  ...rest
}) => (
  <div
    className={cx(styles.row, className)}
    style={{
      justifyContent,
      alignItems,
      flexWrap,
      ...style
    }}
    {...rest}
  >
    {children}
  </div>
);

export const FlexColumn = ({
  children,
  className,
  justifyContent,
  alignItems,
  flexWrap,
  style,
  ...rest
}) => (
  <div
    className={cx(styles.column, className)}
    style={{
      justifyContent,
      alignItems,
      flexWrap,
      ...style
    }}
    {...rest}
  >
    {children}
  </div>
);

export const FlexItem = ({
  children,
  className,
  flex,
  container = false, // Add display: flex;
  ...rest
}) => (
  <div
    className={className}
    style={{
      flex,
      display: container ? 'flex' : 'block'
    }}
    {...rest}
  >
    {children}
  </div>
);

//@flow

import React from 'react';
import cx from 'classnames';
import styles from './index.css';

type Props = {
  children?: any,
  className?: string,
  justifyContent?: string,
  alignItems?: string,
  flexWrap?: string,
  style?: any,
  container?: boolean,
  flex?: any
};

export const FlexRow = ({
  children,
  className,
  justifyContent,
  alignItems,
  flexWrap,
  style,
  ...rest
}: Props) => (
  <div
    className={cx(styles.row, className)}
    style={{
      justifyContent,
      alignItems,
      flexWrap,
      ...style
    }}
    {...rest}
  >
    {children}
  </div>
);

export const FlexColumn = ({
  children,
  className,
  justifyContent,
  alignItems,
  flexWrap,
  style,
  ...rest
}: Props) => (
  <div
    className={cx(styles.column, className)}
    style={{
      justifyContent,
      alignItems,
      flexWrap,
      ...style
    }}
    {...rest}
  >
    {children}
  </div>
);

export const FlexItem = ({
  children,
  className,
  flex,
  container = false, // Add display: flex;
  ...rest
}: Props) => (
  <div
    className={className}
    style={{
      flex,
      display: container ? 'flex' : 'block'
    }}
    {...rest}
  >
    {children}
  </div>
);

Remove eslint disable, and add flow


const {resolve} = require('path')

function getEntryOutputPathFromStats (stats, assetName) {
  if (!assetName) {
    assetName = Object.keys(stats.compilation.assets)[0]
  }

  if (assetName) {
    return resolve(stats.compilation.compiler.options.output.path, assetName)
  }
}

module.exports = getEntryOutputPathFromStats

const {join} = require('path')

function getEntryOutputPathFromStats (stats, options = {}) {
  if (typeof options === 'string') {
    options = {entryName: options}
  }

  let {
    entryName,
    outputPath
  } = options

  let entryFiles
  let entryOutputPath

  if (stats.compilation) {
    const {entrypoints} = stats.compilation
    const entry = entryName ? entrypoints[entryName] : entrypoints.main || entrypoints.index

    if (!outputPath) {
      outputPath = stats.compilation.outputOptions.path
    }

    if (entry) {
      entryChunk = entry.chunks.find((chunk) => chunk.name === entry.name)

      if (entryChunk) {
        entryFiles = entryChunk.files
      }
    }
  }

  if (!entryFiles && stats.chunks && stats.entrypoints) {
    const {
      chunks,
      entrypoints
    } = stats

    if (!entryName) {
      entryName = entrypoints.main ? 'main' : entrypoints.index ? 'index' : undefined
    }

    const entry = entrypoints[entryName]

    if (entry) {
      entryFiles = entry.chunks
        .map((chunkId) => chunks.find((chunk) => chunk.id === chunkId))
        .filter((chunk) => chunk && chunk.names && ~chunk.names.indexOf(entryName))
        .reduce((acc, chunk) => acc.concat(chunk.files || []), [])
    }
  }

  if (!entryFiles && stats.assetsByChunkName && stats.chunks) {
    const {assetsByChunkName} = stats

    entryFiles = entryName ? assetsByChunkName[entryName] : assetsByChunkName.main || assetsByChunkName.index
  }

  if (!entryFiles && stats.assets) {
    const {assets} = stats

    entryFiles = []
      .concat(entryName || ['main', 'index'])
      .map((chunkName) => assets.filter((asset) => ~asset.chunkNames.indexOf(chunkName)))
      .reduce((acc, value) => value.map((asset) => asset.name), [])
  }

  if (entryFiles) {
    entryOutputPath = entryFiles.find((file) => file.endsWith('.js'))
  }

  if (entryOutputPath && outputPath) {
    entryOutputPath = join(outputPath, entryOutputPath)
  }

  return entryOutputPath
}

module.exports = getEntryOutputPathFromStats

Enhance entry output path resolution from stats and json stats


const fs = require('fs')
const path = require('path')
const cli = require('commander')
const apiCall = require('./apiCall')
const config = require('../apiConfig')

cli.parse(process.argv)

// Get current certifications from the API
apiCall('certifications')
  .then(res => {
    res.body.filter(c => c.status === 'certified')
      .forEach(c => {
        config.certs[c.project_id.toString()] = c.project.name
      })
    // Save the config file.
    fs.writeFileSync(
      path.resolve('./apiConfig.json'), JSON.stringify(config, null, 2))
  })

const fs = require('fs')
const path = require('path')
const cli = require('commander')
const apiCall = require('./apiCall')
const config = require('../apiConfig')

cli.parse(process.argv)

config.certs = []
// Get current certifications from the API
apiCall('certifications')
.then(res => {
  res.body.filter(c => c.status === 'certified')
    .forEach(c => {
      config.certs.push({
        id: c.project_id.toString(),
        name: c.project.name,
        price: c.project.price
      })
    })
  // Save the config file.
  fs.writeFileSync(
    path.resolve('./apiConfig.json'), JSON.stringify(config, null, 2))
})

Change config.certs to include an object for each certification with name, id and price


'use strict';

var evalInScope = require('./helpers/eval-in-scope');

/*eslint-disable*/

function evalBEST(source, builder, extras) {
    evalInScope(source, { component: builder }, extras);
}

function evalSources(sources, proc, extras, cb) {
    var sourcesLength = sources.length;
    var sourcesLoaded = 0;
    if (sourcesLength === sourcesLoaded) {
        return cb();
    }
    for (var i = 0; i < sourcesLength; i++) {
        evalDependency(sources[i], proc, extras, function() {
            if (++sourcesLoaded === sourcesLength) {
                cb();
            }
        });
    }
}

function evalEntrypoint(source, proc, extras, final) {
    evalBEST(source, function(name, definition) {
        return proc(name, definition, final);
    }, extras);
}

function evalDependency(source, proc, extras, final) {
    evalBEST(source, function(name, definition) {
        return proc(name, definition, final);
    }, extras);
}

/*eslint-enable*/

module.exports = {
    evalDependency: evalDependency,
    evalEntrypoint: evalEntrypoint,
    evalSources: evalSources
};

'use strict';

var evalInScope = require('./helpers/eval-in-scope');

/*eslint-disable*/

function evalBEST(source, builder, extras) {
    evalInScope(source, { component: builder }, extras);
}

function evalSources(sources, proc, extras, cb) {
    var sourcesLength = sources.length;
    var sourcesLoaded = 0;
    if (sourcesLength === sourcesLoaded) {
        if (cb) {
            return cb();
        }
    }
    for (var i = 0; i < sourcesLength; i++) {
        evalDependency(sources[i], proc, extras, function() {
            if (++sourcesLoaded === sourcesLength) {
                if (cb) {
                    return cb();
                }
            }
        });
    }
}

function evalEntrypoint(source, proc, extras, final) {
    evalBEST(source, function(name, definition) {
        return proc(name, definition, final);
    }, extras);
}

function evalDependency(source, proc, extras, final) {
    evalBEST(source, function(name, definition) {
        return proc(name, definition, final);
    }, extras);
}

/*eslint-enable*/

module.exports = {
    evalDependency: evalDependency,
    evalEntrypoint: evalEntrypoint,
    evalSources: evalSources
};

Check for presence of callback


import 'app/client/components/helpers/jsdom-support.js';

import { assert } from 'chai';
import sinon from 'sinon';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import stubRouterContext from 'app/client/components/helpers/stub-router-context';
import TodosAdd from './todos-add';

describe('Component: TodosAdd', () => {
  it('should be defined', () => {
    assert.ok(TodosAdd);
    assert.isFunction(TodosAdd);
  });

  it("should render 'TodosAdd' component", () => {
    const component = TestUtils.renderIntoDocument(<TodosAdd />);

    assert.ok(component);
  });

  it('should define state.todo', () => {
    const component = TestUtils.renderIntoDocument(<TodosAdd />);

    assert.equal(component.state.todo, '');
  });

  it("should call the addTodo action when click on the 'Add Todo' button", () => {
    const callback = sinon.spy();
    const component = TestUtils.renderIntoDocument(<TodosAdd addTodo={callback} />);
    const input = ReactDOM.findDOMNode(TestUtils.findRenderedDOMComponentWithTag(component, 'input'));
    const button = ReactDOM.findDOMNode(TestUtils.findRenderedDOMComponentWithTag(component, 'button'));

    input.value = 'do chore';
    TestUtils.Simulate.change(input);
    assert.equal(component.state.todo, 'do chore');

    TestUtils.Simulate.click(button);
    assert(callback.called);
    assert(callback.calledWith('do chore'));
    assert.equal(component.state.todo, '');
  });
});

import 'app/client/components/helpers/jsdom-support.js';

import { assert } from 'chai';
import sinon from 'sinon';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import TodosAdd from './todos-add';

describe('Component: TodosAdd', () => {
  it('should be defined', () => {
    assert.ok(TodosAdd);
    assert.isFunction(TodosAdd);
  });

  it("should render 'TodosAdd' component", () => {
    const component = TestUtils.renderIntoDocument(<TodosAdd />);

    assert.ok(component);
  });

  it('should define state.todo', () => {
    const component = TestUtils.renderIntoDocument(<TodosAdd />);

    assert.equal(component.state.todo, '');
  });

  it("should call the addTodo action when click on the 'Add Todo' button", () => {
    const callback = sinon.spy();
    const component = TestUtils.renderIntoDocument(<TodosAdd addTodo={callback} />);
    const input = ReactDOM.findDOMNode(TestUtils.findRenderedDOMComponentWithTag(component, 'input'));
    const button = ReactDOM.findDOMNode(TestUtils.findRenderedDOMComponentWithTag(component, 'button'));

    input.value = 'do chore';
    TestUtils.Simulate.change(input);
    assert.equal(component.state.todo, 'do chore');

    TestUtils.Simulate.click(button);
    assert(callback.called);
    assert(callback.calledWith('do chore'));
    assert.equal(component.state.todo, '');
  });
});

Remove stub router context from TodosAdd


var _ = require('underscore');

/*
 * Approx timings for how often we should notify
 * 360 (~5mins)      : every 58mins
 * 4500 (~hourly)    : every 58mins
 * 90000 (~day)      : every 58mins
 * 648000 (~week)    : every day
 * 2764800 (~month)  : every other day
 * 8467200 (~quater) : every week
 */
var frequencyMap = {
  360: 3480,
  4500: 3480,
  90000: 3480,
  648000: 86400,
  2764800: 172800,
  8467200: 604800
};

module.exports = function (maxAge) {
  var sortedAge = _.map(frequencyMap, function (val, key) {
    return [key, Math.abs(key - maxAge)];
  });

  var reduce = _.reduce(sortedAge, function (memo, val) {
    return (memo[1] < val[1]) ? memo : val;
  })[0];

  return frequencyMap[reduce];
};

var _ = require('underscore');

/*
 * Approx timings for how often we should notify
 * 360 (~5mins)       : every 58mins
 * 4500 (~hourly)     : every 58mins
 * 90000 (~day)       : every 58mins
 * 648000 (~week)     : every day
 * 2764800 (~month)   : every other day
 * 8467200 (~quarter) : every week
 */
var frequencyMap = {
  360: 3480,
  4500: 3480,
  90000: 3480,
  648000: 86400,
  2764800: 172800,
  8467200: 604800
};

module.exports = function (maxAge) {
  var sortedAge = _.map(frequencyMap, function (val, key) {
    return [key, Math.abs(key - maxAge)];
  });

  var reduce = _.reduce(sortedAge, function (memo, val) {
    return (memo[1] < val[1]) ? memo : val;
  })[0];

  return frequencyMap[reduce];
};

Fix spelling of 'quarter' in comment


var remark = require('remark');
var visit = require('unist-util-visit');
var remove = require('unist-util-remove');

var processor = remark().use(function () {
  return function(ast, file) {
    visit(ast, 'code', function (node) {
      console.log(node.value);
      remove(ast, node);
    });
  };
});
var doc = processor.process('hello\nfoo\n\n    bar\n\nbaz *qux*');
console.log('---');
console.log(doc);

var remark = require('remark');
var visit = require('unist-util-visit');
var remove = require('unist-util-remove');

function spliterator(code_out) {
  // Our Remark "plugin".
  return function () {
    return function(ast, file) {
      visit(ast, 'code', function (node) {
        code_out.push(node.value);
        remove(ast, node);
      });
    };
  };
}

// Construct the plugin. We'll accumulate the code into `code_chunks` while
// stripping it out of the AST.
var code_chunks = [];
var plugin = spliterator(code_chunks);

// Process the document.
var processor = remark().use(plugin);
var doc = processor.process('hello\nfoo\n\n    bar\n\nbaz *qux*');

console.log(code_chunks);
console.log(doc);

Clean up structure a little


/* eslint-disable no-var */
var evs = require('eventsource-polyfill/dist/eventsource')
module.exports = window.EventSource || evs.EventSource

Fix incorrect usage of polyfill when bundled


/**
 * Puppy Play Date
 * https://github.com/Tooconfident/Puppy_PlayDate
 * @flow
 */

import React, { Component } from 'react';
import {
 AppRegistry,
 Navigator,
 AsyncStorage,
} from 'react-native';

import MapScene from './MapScene';
import MainScene from './MainScene';
import WelcomePage from './WelcomePage';

const styles = require('./style.js')

class PuppyPlayDateApp extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentDidMount() {
        // AsyncStorage.clear()
        AsyncStorage.getItem("userID").then((value) => {
          console.log('current.val '+ value);
            this.setState({"userID": value});
        }).done();
    }
  renderScene(route, navigator){
    console.log("renderScene was called: passProps: " + route.passProps);
    return(
      <route.component navigator={navigator} {...route.passProps}/>
    );
  }
  render() {

    if (this.state.userID != undefined){
      return (<MainScene/>);
    } else {
      return (
        <Navigator
        sceneStyle={styles.container}
        ref={(navigator) => { this.navigator = navigator; }}
        renderScene={this.renderScene}
        tintColor='#D6573D'
        barTintColor='#FFFFFD'
        titleTextColor='#D6573D'
        navigationBarHidden={true}
        initialRoute={{
          title: 'Main',
          component: WelcomePage,
        }}
      >
      );

        <WelcomePage/>
        </Navigator>
      );
    }

  }

}
AppRegistry.registerComponent('PuppyPlayDate', () => PuppyPlayDateApp);

/**
 * Puppy Play Date
 * https://github.com/Tooconfident/Puppy_PlayDate
 * @flow
 */

import React, { Component } from 'react';
import {
 AppRegistry,
 NavigatorIOS,
 StyleSheet,
} from 'react-native';

import Login from './Login';
import MainScene from './MainScene';
import MapScene from './MapScene';
import WelcomePage from './WelcomePage';

let styles = StyleSheet.create({
  wrapper: {
    flex: 1
  }
});
class PuppyPlayDateApp extends Component {
  // constructor(props) {
  //   super(props);
  //   this.state = {};
  // }
  //
  // componentDidMount() {
  //   AsyncStorage.clear()
  //   AsyncStorage.getItem("userID").then((value) => {
  //     console.log('current.val '+ value);
  //       this.setState({"userID": value});
  //   }).done();
  // }
  //
  // renderScene(route, navigator){
  //   console.log("renderScene was called: passProps: " + route.passProps);
  //   return(
  //     <route.component navigator={navigator} {...route.passProps}/>
  //   );
  // }
  //
  //
  render() {
    return (
      <NavigatorIOS
        style={styles.wrapper}
        initialRoute= {{
          title: 'Login Page',
          component: Login,
        }}/>
      );
  }
}
AppRegistry.registerComponent('PuppyPlayDate', () => PuppyPlayDateApp);

Replace Navigator with NavigatorIOS; import Login component; comment out unnecessary functions


var gulp = require('gulp');
var less = require('gulp-less');
var bower = require('gulp-bower');
var minifyCSS = require('gulp-minify-css');

var paths = {
  css: 'src/styles/**/*.less',
  fonts: 'bower_components/font-awesome/fonts/**/*'
};

gulp.task('bower', function() {
  bower();
});

gulp.task('css', ['bower'], function() {
  return gulp.src(paths.css)
    .pipe(less())
    .pipe(minifyCSS())
    .pipe(gulp.dest('public/css'));
});

gulp.task('fonts', ['bower'], function() {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('public/fonts'));
});

gulp.task('watch', function() {
  gulp.watch(paths.css, ['css']);
});

gulp.task('default', ['css', 'fonts']);

var gulp = require('gulp');
var less = require('gulp-less');
var bower = require('gulp-bower');
var minifyCSS = require('gulp-minify-css');

var paths = {
  css: 'src/styles/**/*.less',
  fonts: 'bower_components/font-awesome/fonts/**/*'
};

gulp.task('bower', function() {
  return bower();
});

gulp.task('css', ['bower'], function() {
  return gulp.src(paths.css)
    .pipe(less())
    .pipe(minifyCSS())
    .pipe(gulp.dest('public/css'));
});

gulp.task('fonts', ['bower'], function() {
  return gulp.src(paths.fonts)
    .pipe(gulp.dest('public/fonts'));
});

gulp.task('watch', function() {
  gulp.watch(paths.css, ['css']);
});

gulp.task('default', ['css', 'fonts']);

Return the bower result so that it waits correctly.


var gulp = require('gulp');
var oghliner = require('oghliner');
var fse = require('fs-extra');

gulp.task('default', function() {
  fse.removeSync('dist');
  fse.mkdirSync('dist');
  fse.copySync('js', 'dist/js');
  fse.copySync('tictactoe.html', 'dist/tictactoe.html');
});

gulp.task('offline', function(callback) {
  oghliner.offline({
    rootDir: 'dist',
    fileGlobs: [
      'tictactoe.html',
      'js/**/*.js',
    ],
  }, callback);
});

gulp.task('deploy', function(callback) {
  oghliner.deploy({
    rootDir: 'dist',
  }, callback);
});

var gulp = require('gulp');
var oghliner = require('oghliner');
var fse = require('fs-extra');

gulp.task('default', function() {
  fse.removeSync('dist');
  fse.mkdirSync('dist');
  fse.copySync('js', 'dist/js');
  fse.copySync('tictactoe.html', 'dist/tictactoe.html');
});

gulp.task('clean', function() {
  fse.removeSync('dist');
});

gulp.task('offline', function(callback) {
  oghliner.offline({
    rootDir: 'dist',
    fileGlobs: [
      'tictactoe.html',
      'js/**/*.js',
    ],
  }, callback);
});

gulp.task('deploy', function(callback) {
  oghliner.deploy({
    rootDir: 'dist',
  }, callback);
});

Add a gulp task to clean the build


'use strict'

const db = require('APP/db');
const Product = db.model('products');
const Review = db.model('review');
const router = require('express').Router();

router.get('/', (req, res, next) => {
  Product.findAll({})
    .then(products => res.json(products))
    .catch(next)
})

router.get('/:id', (req, res, next) => {
  Product.findOne({
    where: {
      id: req.params.id
    }
  })
    .then(product => res.json(product))
    .catch(next)
})

router.get('/:id/reviews', (req, res, next) => {
    Review.findAll({
      where: {
        product_id: req.params.id
      }
    })
    .then(reviews => {
      res.json(reviews);
    })
})

module.exports = router;

'use strict'

const db = require('APP/db');
const Product = db.model('products');
const Review = db.model('review');
const router = require('express').Router();

router.get('/', (req, res, next) => {
  Product.findAll({})
    .then(products => res.json(products))
    .catch(next)
})

router.get('/:id', (req, res, next) => {
  Product.findOne({
    where: {
      id: req.params.id
    },
    include: [{model: Review}]
  })
    .then(product => res.json(product))
    .catch(next)
})

// router.get('/:id/reviews', (req, res, next) => {
//     Review.findAll({
//       where: {
//         product_id: req.params.id
//       }
//     })
//     .then(reviews => {
//       res.json(reviews);
//     })
// })

module.exports = router;

Add eager loading of reviews for single product.


window.onload = function main() {
  var timezones = document.querySelectorAll('.timezone');

  var getCalendarOffset = function getCalendarOffset(timezone) {
    var localTime = moment.tz(moment().format('YYYY-MM-DD, HH:mm:ss'), 'America/Los_Angeles');

    return moment.tz(timezone).calendar(localTime, {
      sameDay: '[Today]',
      nextDay: '[Tomorrow]',
      nextWeek: 'dddd',
      lastDay: '[Yesterday]',
      lastWeek: '[Last] dddd',
      sameElse: 'YYYY-MM-DD'
    });
  }

  var updateTimes = function updateTimes() {
    for (var timezone of timezones) {
      timezone.getElementsByClassName('timezone__time')[0].textContent = moment.tz(timezone.dataset.timezone).format('HH:mm:ss z');
      timezone.getElementsByClassName('timezone__offset')[0].textContent = getCalendarOffset(timezone.dataset.timezone);
    }
  }

  setInterval(updateTimes, 500);
};

window.onload = function main() {
  var timezones = document.querySelectorAll('.timezone');

  var getCalendarOffset = function getCalendarOffset(timezone) {
    var localTime = moment.tz(moment().format('YYYY-MM-DD, HH:mm:ss'), 'America/Los_Angeles');

    return moment.tz(timezone).calendar(localTime, {
      sameDay: '[Today]',
      nextDay: '[Tomorrow]',
      nextWeek: 'dddd',
      lastDay: '[Yesterday]',
      lastWeek: '[Last] dddd',
      sameElse: 'YYYY-MM-DD'
    });
  }

  var updateTimes = function updateTimes() {
    for (var i = 0, length = timezones.length; i < length; i++) {
      var timezone = timezones[i];

      timezone.getElementsByClassName('timezone__time')[0].textContent = moment.tz(timezone.dataset.timezone).format('HH:mm:ss z');
      timezone.getElementsByClassName('timezone__offset')[0].textContent = getCalendarOffset(timezone.dataset.timezone);
    }
  }

  setInterval(updateTimes, 500);
};

Revise for loop for timezones to work with Chrome


const Connection = require('./connection');

class ConnectionPool {
  constructor() {
    this.hosts = [];
    this.nextHostID = 1; // not an index for array

    this.addHost = this.addHost.bind(this);
    this.getDisplayList = this.getDisplayList.bind(this);
    this.onConnectRequest = this.onConnectRequest.bind(this);
  }

  newConnection(ws) {
    return new Connection(ws, {
      addHost: this.addHost,
      getDisplayList: this.getDisplayList,
      onConnectRequest: this.onConnectRequest,
    })
  }

  removeHost(con) {
    this.hosts.splice(this.hosts.indexOf(con), 1);
  }

  // ========================== Callbacks ==========================

  addHost(con) {
    this.hosts.push(con);
    return this.nextHostID++;
  }

  getDisplayList() {
    return this.hosts.map(h => ({
      hostID: h.hostID,
      hostName: h.hostName,
    }));
  }

  onConnectRequest(req) {
    return this.hosts.find(h => (
      req.hostID === h.hostID || req.hostName === h.hostName
    )) || null;
  }
}

module.exports = ConnectionPool;

const Connection = require('./connection');

class ConnectionPool {
  constructor() {
    this.hosts = [];
    this.nextHostID = 1; // not an index for array

    this.addHost = this.addHost.bind(this);
    this.getDisplayList = this.getDisplayList.bind(this);
    this.onConnectRequest = this.onConnectRequest.bind(this);
  }

  newConnection(ws) {
    const con = new Connection(ws, {
      addHost: this.addHost,
      getDisplayList: this.getDisplayList,
      onConnectRequest: this.onConnectRequest,
      onClose: () => this.removeHost(con),
    });
  }

  removeHost(con) {
    const index = this.hosts.indexOf(con);
    if(index >= 0) {
      this.hosts.splice(index, 1);
    }
  }

  // ========================== Callbacks ==========================

  addHost(con) {
    this.hosts.push(con);
    return this.nextHostID++;
  }

  getDisplayList() {
    return this.hosts.map(h => ({
      hostID: h.hostID,
      hostName: h.hostName,
    }));
  }

  onConnectRequest(req) {
    return this.hosts.find(h => (
      req.hostID === h.hostID || req.hostName === h.hostName
    )) || null;
  }
}

module.exports = ConnectionPool;

Make removal of host a bit safer


/**
 * Entry point for defining Gulp tasks.
 */

// Pull in the tasks from the gulp-tasks directory.
require('require-dir')('./gulp-tasks');

// serve
// acceptance test
// acceptance test with coverage
// lint
// watch - refresh browser on css or js change, restart server and refresh browser on server logic or template change.
// "prestart": "npm stop",
// "start": "node ./bin/www",
// "stop": "pkill specs || true",
// "pretest": "PORT=1337 npm start & sleep 1",
// "test": "PORT=1337 node_modules/.bin/cucumber-js --require features-support",
// "posttest": "npm stop",
// "pretest-with-coverage": "npm run pretest",
// "test-with-coverage": "PORT=1337 node_modules/.bin/istanbul cover node_modules/.bin/cucumber-js --report teamcity --report lcov -- --require features-support -f progress",
// "posttest-with-coverage": "npm run posttest",
// "upload-coverage-data": "node_modules/.bin/codeclimate-test-reporter < coverage/lcov.info",
// "lint": "node_modules/.bin/eslint ./"

Move and modify list of required Gulp tasks.


'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');

var config = {
  namespace: 'braintree',
  src: {
    js: {
      all: './src/**/*.js',
      main: './index.js',
      output: 'card-validator.js',
      min: 'card-validator.min.js'
    }
  },
  dist: 'dist'
};

gulp.task('js', function () {
  return browserify({standalone: 'cardValidator'})
    .add(config.src.js.main)
    .bundle()
    .pipe(source(config.src.js.output))
    .pipe(streamify(size()))
    .pipe(gulp.dest(config.dist))
    .pipe(streamify(uglify()))
    .pipe(streamify(size()))
    .pipe(rename(config.src.js.min))
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', function (done) {
  del([config.dist], done);
});

gulp.task('build', ['clean', 'js']);

'use strict';

var gulp = require('gulp');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var size = require('gulp-size');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var del = require('del');

var config = {
  src: {
    js: {
      all: './src/**/*.js',
      main: './index.js',
      output: 'card-validator.js',
      min: 'card-validator.min.js'
    }
  },
  dist: 'dist'
};

gulp.task('js', function () {
  return browserify({standalone: 'cardValidator'})
    .add(config.src.js.main)
    .bundle()
    .pipe(source(config.src.js.output))
    .pipe(streamify(size()))
    .pipe(gulp.dest(config.dist))
    .pipe(streamify(uglify()))
    .pipe(streamify(size()))
    .pipe(rename(config.src.js.min))
    .pipe(gulp.dest(config.dist));
});

gulp.task('clean', function (done) {
  del([config.dist], done);
});

gulp.task('build', ['clean', 'js']);

Remove unused `namespace` key from Gulp configuration


var gulp = require('gulp');
var sass = require('gulp-sass');
var autoprefixer = require('gulp-autoprefixer');
var uglify = require('gulp-uglify');
var pump = require('pump');
var cleanCSS = require('gulp-clean-css');
var imagemin = require('gulp-imagemin');

gulp.task('sass', function() {
    return gulp.src('src/sass/*.scss')
        .pipe(sass())
        .pipe(autoprefixer({ browsers: ['last 3 versions'] }))
        .pipe(cleanCSS())
        .pipe(gulp.dest('build/css'));
});

gulp.task('uglify-js', function() {
    pump([
        gulp.src('src/js/*.js'),
        uglify(),
        gulp.dest('build/js')
    ]);
});

gulp.task('html', function() {
	return gulp.src('src/index.html').pipe(gulp.dest('build'));
});

gulp.task('default', function() {
	gulp.watch('src/sass/*.scss', ['sass']);
	gulp.watch('src/js/*.js', ['uglify-js']);
	gulp.watch('src/index.html', ['html']);
	gulp.src('src/img/*')
        .pipe(imagemin())
        .pipe(gulp.dest('build/img'));
});

Add tasks to compile and minify *.scss files, compress images, and minify *.js files.


module.exports = {

  stack: function (browser, selector, index) {
    index = index || '';
    return function () {
      var linePath;
      return browser
        .$(selector + ' svg .line' + index)
          .should.eventually.exist
          .getAttribute('d').then(function (d) {
            linePath = d.split('M')[1];
          })
        .$(selector + ' svg .stack' + index)
          .should.eventually.exist
          .getAttribute('d').then(function (d) {
            // the line follows the top of the stack, so the line path should be a
            // substring of the stack path
            d.should.contain(linePath);
          });
    };
  }

};

var _ = require('underscore');

module.exports = {

  stack: function (browser, selector, index) {
    var lineInGroup = _.isNumber(index) ? '.group' + index : '';
    return function () {
      var linePath;
      return browser
        .$(selector + ' svg .line' + lineInGroup)
          .should.eventually.exist
          .getAttribute('d').then(function (d) {
            linePath = d.split('M')[1];
          })
        .$(selector + ' svg .stack' + lineInGroup)
          .should.eventually.exist
          .getAttribute('d').then(function (d) {
            // the line follows the top of the stack, so the line path should be a
            // substring of the stack path
            d.should.contain(linePath);
          });
    };
  }

};

Fix groupIndex for stacked graphs.


const conf = require('./gulp.conf');

module.exports = function () {
  return {
    server: {
      baseDir: [
        conf.paths.tmp,
        conf.paths.src
      ]
    },
    open: false
  };
};

const conf = require('./gulp.conf');

module.exports = function () {
  return {
    server: {
      baseDir: [
        conf.paths.tmp,
        conf.paths.src
      ]
    },
    open: false,
    port: 3002
  };
};

Set gulp serve prot to 3002


(function(w) {

  "use strict";
  var angular = w.angular;
  var _ = w._;

  var deps = [];

  function PluckFilter() {
    return _.memoize(function(input, field) {
      if(Array.isArray(input)) {
        return input.map(function(item) {
          return item[field];
        });
      } else if(input) {
        return input[field];
      }
    });
  }

  PluckFilter.$inject = deps;

  angular.module('Thoth')
      .filter('pluck', PluckFilter);

}(window));

(function(w) {

  "use strict";
  var angular = w.angular;
  var _ = w._;
  var btoa = w.btoa;

  var deps = [];

  var slice = Array.prototype.slice;

  function hash() {
    var args = slice.call(arguments);
    return btoa(args.join(':'));
  };

  function PluckFilter() {
    return _.memoize(function(input, field) {
      if(Array.isArray(input)) {
        return input.map(function(item) {
          return item[field];
        });
      } else if(input) {
        return input[field];
      }
    }, hash);
  }

  PluckFilter.$inject = deps;

  angular.module('Thoth')
      .filter('pluck', PluckFilter);

}(window));

Fix memoize bug, use custom hash method


// run `npm install` to install deps first, then `node ./` to execute

var fs = require('fs')
  , colors = require('colors')
  , path = require('path')
  , cheerio = require('cheerio')

  , page = fs.readFileSync(path.join(__dirname, 'es6', 'index.html')).toString()
  , $ = cheerio.load(page)

  , test = function test (expression) {
      return expression
    }

$('#body tbody tr').each(function () {
  var desc = (function (el) {
        while (el && !el.data)
          el = el.children[0]
        return (el && el.data) || 'ERROR!'
      }(this.find('td>span>a')[1] || this.find('td>span')[0].children[1]))
    , scripts = this.find('script')
    , result = false
    , i = 0, scr

  // can be multiple scripts
  for (; scripts[i] && scripts[i].children && scripts[i].children.length; i++) {
    scr = scripts[i].children[0].data.trim()
    result = eval(scr)
  }

  console.log(((result ? '\u2714' : '\u2718') + '\t' + desc + '\t')[result ? 'green' : 'red'])
})

// run `npm install` to install deps first, then `node ./` to execute

var fs = require('fs')
  , colors = require('colors')
  , path = require('path')
  , cheerio = require('cheerio')

  , page = fs.readFileSync(path.join(__dirname, 'es6', 'index.html')).toString()
  , $ = cheerio.load(page)

$('#body tbody tr').each(function () {
  var desc = (function (el) {
        while (el && !el.data)
          el = el.children[0]
        return (el && el.data) || 'ERROR!'
      }(this.find('td>span>a')[1] || this.find('td>span')[0].children[1]))
    , scripts = this.find('script')
    , result = false
    , i = 0, scr

    , test = function test (expression) {
        result = result || expression
      }

  // can be multiple scripts
  for (; scripts[i] && scripts[i].children && scripts[i].children.length; i++) {
    scr = scripts[i].children[0].data.trim()
    eval(scr)
  }

  console.log(((result ? '\u2714' : '\u2718') + '\t' + desc + '\t')[result ? 'green' : 'red'])
})

Fix for test with multiple scripts


import Em from 'ember';

var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;

/**
 * Fires custom events on the implementor when arrow keys are pressed.
 * @module mixins
 * @constructor
 * @class ArrowKeysMixin
 * @extends Ember.Mixin
 */
var ArrowKeysMixin = Em.Mixin.create({
	keyDown: function (e) {
		switch (e.which) {
			case KEY_LEFT:
				this.send('keyLeft');
				e.preventDefault();
				break;
			case KEY_UP:
				this.send('keyUp');
				e.preventDefault();
				break;
			case KEY_RIGHT:
				this.send('keyRight');
				e.preventDefault();
				break;
			case KEY_DOWN:
				this.send('keyDown');
				e.preventDefault();
				break;
		}
	}
});

export default ArrowKeysMixin;

import Em from 'ember';

var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;

/**
 * Fires custom events on the implementor when arrow keys are pressed.
 * @module mixins
 * @constructor
 * @class ArrowKeysMixin
 * @extends Ember.Mixin
 */
var ArrowKeysMixin = Em.Mixin.create({
	keyDown: function (e) {
		switch (e.which) {
			case KEY_LEFT:
				this.send('keyLeft', e);
				e.preventDefault();
				break;
			case KEY_UP:
				this.send('keyUp', e);
				e.preventDefault();
				break;
			case KEY_RIGHT:
				this.send('keyRight', e);
				e.preventDefault();
				break;
			case KEY_DOWN:
				this.send('keyDown', e);
				e.preventDefault();
				break;
		}
	}
});

export default ArrowKeysMixin;

Send event object with arrow key press events


require('_animate');
require('_copyright');
require('_faq');
require('_nav-scroll');
require('_nav-transparent');
require('_nav');
require('_scroll');
require('_top-home');
require('_top');

require('./_animate');
require('./_copyright');
require('./_faq');
require('./_nav-scroll');
require('./_nav-transparent');
require('./_nav');
require('./_scroll');
require('./_top-home');
require('./_top');

Correct paths for require statements.


var finish_utc;
$(document).ready(function(){
  var finish_utc_args = JSON.parse($('#countdown-finish-time').html());
  finish_utc = new Date(Date.UTC(finish_utc_args[0],
                                 finish_utc_args[1],
                                 finish_utc_args[2],
                                 finish_utc_args[3],
                                 finish_utc_args[4],
                                 finish_utc_args[5]));
  update_countdown();
});

function update_countdown() {
  var current_utc = new Date().getTime();
  var time_diff = finish_utc - current_utc;
  var seconds = Math.floor(time_diff / 1000);
  var minutes = Math.floor(seconds / 60);
  var hours = Math.floor(minutes / 60);
  var days = Math.floor(hours / 24);
  var content;

  hours %= 24;
  minutes %= 60;
  seconds %= 60;

  if (time_diff < 0) {
      $('.countdown').remove();
  }

  $('.countdown-days').text(days);
  $('.countdown-hours').text(hours);
  $('.countdown-minutes').text(minutes);
  $('.countdown-seconds').text(seconds);
  setTimeout('update_countdown()', 1000);
}

var finish_utc;
$(document).ready(function(){
	if ($('#countdown-finish-time').length != 0) {
	  var finish_utc_args = JSON.parse($('#countdown-finish-time').html());
	  finish_utc = new Date(Date.UTC(finish_utc_args[0],
	                                 finish_utc_args[1],
	                                 finish_utc_args[2],
	                                 finish_utc_args[3],
	                                 finish_utc_args[4],
	                                 finish_utc_args[5]));
	  update_countdown();
	}
});

function update_countdown() {
  var current_utc = new Date().getTime();
  var time_diff = finish_utc - current_utc;
  var seconds = Math.floor(time_diff / 1000);
  var minutes = Math.floor(seconds / 60);
  var hours = Math.floor(minutes / 60);
  var days = Math.floor(hours / 24);
  var content;

  hours %= 24;
  minutes %= 60;
  seconds %= 60;

  if (time_diff < 0) {
      $('.countdown').remove();
  }

  $('.countdown-days').text(days);
  $('.countdown-hours').text(hours);
  $('.countdown-minutes').text(minutes);
  $('.countdown-seconds').text(seconds);
  setTimeout('update_countdown()', 1000);
}

Fix JS crashing when no countdown on page


var gulp    = require('gulp'),
    coffee  = require('gulp-coffee'),
    gutil   = require('gulp-util');

gulp.task('default', function(){
  gulp.src('src/*.coffee')
      .pipe(coffee({sourceMap: false}))
      .on('error', gutil.log)
      .pipe(gulp.dest('dist'));
})

gulp.watch(['src/*.coffee'], ['default'])

var gulp    = require('gulp'),
    coffee  = require('gulp-coffee'),
    gutil   = require('gulp-util');

gulp.task('default', function(){
  gulp.src('src/*.coffee')
      .pipe(coffee({sourceMap: false})).on('error', gutil.log)
      .pipe(gulp.dest('dist'));
})

gulp.watch(['src/*.coffee'], ['default'])

Make error handling on the same line


var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var concat = require('gulp-concat');
var sass = require('gulp-sass');

var cssPath = [
    './vendor/webuploader_fex/dist/webuploader.css',
    './assets/css/**/*'
];

var jsPath = [
    './vendor/jquery/dist/jquery.js',
    './vendor/webuploader_fex/dist/webuploader.js',
    './assets/js/**/*'
];

gulp.task('css', function () {
    gulp.src(cssPath)
        .pipe(sass())
        .pipe(concat('all.css'))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('js', function () {
    gulp.src(jsPath)
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./public/js'));
});

gulp.task('watch', function () {
    gulp.watch('assets/css/**/*', ['css']);
    gulp.watch('assets/js/**/*', ['js']);
});

gulp.task('build', function () {
    gulp.start(['css', 'js']);
});

gulp.task('nodemon', function () {
    nodemon({
        script: './bin/www',
        ext: 'sass js',
        env: {
            'NODE_ENV': 'development'
        }
    });
});

gulp.task('default', function () {
    gulp.start('watch');
    gulp.start('nodemon');
});

var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
var concat = require('gulp-concat');
var sass = require('gulp-sass');

var cssPath = [
    './vendor/webuploader_fex/dist/webuploader.css',
    './assets/css/**/*'
];

var jsPath = [
    './vendor/jquery/dist/jquery.js',
    './vendor/webuploader_fex/dist/webuploader.js',
    './assets/js/**/*'
];

gulp.task('css', function () {
    gulp.src(cssPath)
        .pipe(sass())
        .pipe(concat('all.css'))
        .pipe(gulp.dest('./public/css'));
});

gulp.task('js', function () {
    gulp.src(jsPath)
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./public/js'));
});

gulp.task('watch', function () {
    gulp.watch('assets/css/**/*', ['css']);
    gulp.watch('assets/js/**/*', ['js']);
});

gulp.task('build', function () {
    gulp.start(['css', 'js']);
});

gulp.task('nodemon', function () {
    nodemon({
        script: './bin/www',
        ext: 'sass js',
        env: {
            'NODE_ENV': 'development'
        },
        watch: ['app.js', './routes', './bin']
    });
});

gulp.task('default', function () {
    gulp.start('watch');
    gulp.start('nodemon');
});

Add watch files in nodemon task


var gulp   = require('gulp'),
    gutil  = require('gulp-util'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    karma  = require('gulp-karma'),
    notify = require('gulp-notify');

gulp.task('default', function() {
  gulp.run('scripts', 'test');
});

gulp.task('watch', function() {
  gulp.watch('./src/*.js', function(event) {
    gulp.run('scripts');
  });
  gulp.run('test-watch');
});

gulp.task('scripts', function() {
  gulp.src([
      './src/angular-moment.js',
      './src/angular-moment.service.js',
      './src/angular-moment.directive.js'
    ])
    .pipe(concat("angular-moment.js"))
    .pipe(gulp.dest('./dist/'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      outSourceMaps: true,
      preserveComments: 'some'
    }))
    .pipe(gulp.dest('./dist'))
    .pipe(notify({ message: 'Scripts task complete' }));
});

// Karma testing
gulp.task('test', function() {
  // Be sure to return the stream
  return gulp.src('./defined-in-karma.conf.js')
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'run'
    }));
});

gulp.task('test-watch', function() {
  // Be sure to return the stream
  return gulp.src('./defined-in-karma.conf.js')
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'watch'
    }));
});

var gulp   = require('gulp'),
    gutil  = require('gulp-util'),
    concat = require('gulp-concat'),
    uglify = require('gulp-uglify'),
    rename = require('gulp-rename'),
    karma  = require('gulp-karma'),
    notify = require('gulp-notify');

var jsFiles = [
  './src/angular-moment.js',
  './src/angular-moment.service.js',
  './src/angular-moment.directive.js'
];

// Task to run during development
gulp.task('develop', function() {
  karmaAction = 'watch';
  gulp.watch(jsFiles, ['js']);
  karmaTest('watch');
});

// Task to build to dist folder
gulp.task('build', ['js'], function() {
  karmaTest('run');
});

// Subtasks
////////////

gulp.task('js', function() {
  gulp.src(jsFiles)
    .pipe(concat("angular-moment.js"))
    .pipe(gulp.dest('./dist/'))
    .pipe(rename({ suffix: '.min' }))
    .pipe(uglify({
      outSourceMaps: true,
      preserveComments: 'some'
    }))
    .pipe(gulp.dest('./dist'));
    // .pipe(notify({ message: 'Scripts task complete' }));
});

function karmaTest(action) {
  return gulp.src('./defined-in-karma.conf.js')
    .pipe(karma({
      configFile: 'karma.conf.js',
      action: action
    }));
}

Fix gulp file to no longer use deprecated gulp.run


import React from "react";
import Dropzone from "react-dropzone";
import classNames from "classnames";
import "./DropHandler.css";

export default class DropHandler extends React.Component {
  handleDrop = (files) => {
    this.props.importSequenceFromFile(files[0]);
  };
  render() {
    const { children, style, className, disabled } = this.props;
    return (
      <Dropzone
        disabled={disabled}
        onClick={(evt) => evt.preventDefault()}
        multiple={false}
        accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
        activeClassName="isActive"
        rejectClassName="isRejected"
        onDropRejected={() => {
          window.toastr.error("Error: Incorrect File Type");
        }}
        onDrop={this.handleDrop}
      >
        {({ getRootProps, isDragActive }) => (
          <div
            {...getRootProps()}
            {...{
              style,
              className: classNames(className, { isActive: isDragActive })
            }}
          >
            <DraggingMessage />
            {children}
          </div>
        )}
      </Dropzone>
    );
  }
}
function DraggingMessage() {
  return (
    <div className="dropzone-dragging-message">
      Drop Fasta or Genbank files to view them in the editor. The following
      extensions are accepted: .gb .gbk .fasta .fa .gp .txt
    </div>
  );
}

import React from "react";
import Dropzone from "react-dropzone";
import classNames from "classnames";
import "./DropHandler.css";

export default class DropHandler extends React.Component {
  handleDrop = (files) => {
    this.props.importSequenceFromFile(files[0]);
  };
  render() {
    const { children, style, className, disabled } = this.props;
    return (
      <Dropzone
        disabled={disabled}
        onClick={(evt) => evt.preventDefault()}
        multiple={false}
        accept={[".gb", ".gbk", ".fasta", ".fa", ".gp", ".txt", ".dna"]}
        onDropRejected={() => {
          window.toastr.error("Error: Incorrect File Type");
        }}
        onDrop={this.handleDrop}
      >
        {({ getRootProps, isDragActive, isDragReject }) => (
          <div
            {...getRootProps()}
            {...{
              style,
              className: classNames(className, {
                isActive: isDragActive,
                isRejected: isDragReject
              })
            }}
          >
            <DraggingMessage />
            {children}
          </div>
        )}
      </Dropzone>
    );
  }
}
function DraggingMessage() {
  return (
    <div className="dropzone-dragging-message">
      Drop Fasta or Genbank files to view them in the editor. The following
      extensions are accepted: .gb .gbk .fasta .fa .gp .txt
    </div>
  );
}

Remove deprecated class name props to Dropzone component


function makeRequest(authToken, path, data) {
  const d = $.extend({}, { format: 'json', auth_token: authToken }, data);
  const u = `https://api.pinboard.in/v1/${path}`;

  console.log('%cmakeRequest url: %s $data: %o', 'background: blue; color: white', u, d);

  return new Promise((resolve, reject) => {
    $.ajax({
      url: u,
      method: 'GET',
      data: d,
      timeout: 3000,
    }).done((response) => {
      console.log('response: %o', response);

      try {
        resolve(JSON.parse(response));
      } catch (e) {
        console.error(e);
        reject();
      }
    }).fail((_, textStatus, error) => {
      console.error('textStatus: %s error: %s', textStatus, error);

      reject();
    });
  });
}

const Api = {};

Api.getLastUpdated = (authToken) => makeRequest(authToken, 'posts/update');

Api.addBookmark = (authToken, data) => makeRequest(authToken, 'posts/add', data);

Api.deleteBookmark = (authToken, url) => makeRequest(authToken, 'posts/delete', { url });

Api.getBookmark = (authToken, url) => makeRequest(authToken, 'posts/get', { url });

Api.getTags = (authToken) => makeRequest(authToken, 'tags/get');

export default Api;

function makeRequest(authToken, path, data) {
  const d = $.extend({}, { format: 'json', auth_token: authToken, id: 'pinboard-plusplus' }, data);
  const u = `https://api.pinboard.in/v1/${path}`;

  console.log('%cmakeRequest url: %s $data: %o', 'background: blue; color: white', u, d);

  return new Promise((resolve, reject) => {
    $.ajax({
      url: u,
      method: 'GET',
      data: d,
      timeout: 3000,
    }).done((response) => {
      console.log('response: %o', response);

      try {
        resolve(JSON.parse(response));
      } catch (e) {
        console.error(e);
        reject();
      }
    }).fail((_, textStatus, error) => {
      console.error('textStatus: %s error: %s', textStatus, error);

      reject();
    });
  });
}

const Api = {};

Api.getLastUpdated = (authToken) => makeRequest(authToken, 'posts/update');

Api.addBookmark = (authToken, data) => makeRequest(authToken, 'posts/add', data);

Api.deleteBookmark = (authToken, url) => makeRequest(authToken, 'posts/delete', { url });

Api.getBookmark = (authToken, url) => makeRequest(authToken, 'posts/get', { url });

Api.getTags = (authToken) => makeRequest(authToken, 'tags/get');

export default Api;

Send an id in all API request


import flattenStyle from './flattenStyle';
import StyleRegistry from './registry';

const absoluteFillObject = {
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0
};
const absoluteFill = StyleRegistry.register(absoluteFillObject);

const StyleSheet = {
  absoluteFill,
  absoluteFillObject,
  create(styles) {
    const result = {};
    Object.keys(styles).forEach(key => {
      if (process.env.NODE_ENV !== 'production') {
        const StyleSheetValidation = require('./StyleSheetValidation').default;
        StyleSheetValidation.validateStyle(key, styles);
      }
      result[key] = StyleRegistry.register(styles[key]);
    });
    return result;
  },
  flatten: flattenStyle,
  getStyleSheets() {
    return StyleRegistry.getStyleSheets();
  },
  hairlineWidth: 1
};

export default StyleSheet;

import flattenStyle from './flattenStyle';
import StyleRegistry from './registry';

// allow component styles to be editable in React Dev Tools
if (process.env.NODE_ENV !== 'production') {
  const { canUseDOM } = require('fbjs/lib/ExecutionEnvironment');
  if (canUseDOM && window.__REACT_DEVTOOLS_GLOBAL_HOOK__) {
    window.__REACT_DEVTOOLS_GLOBAL_HOOK__.resolveRNStyle = flattenStyle;
  }
}

const absoluteFillObject = {
  position: 'absolute',
  left: 0,
  right: 0,
  top: 0,
  bottom: 0
};
const absoluteFill = StyleRegistry.register(absoluteFillObject);

const StyleSheet = {
  absoluteFill,
  absoluteFillObject,
  create(styles) {
    const result = {};
    Object.keys(styles).forEach(key => {
      if (process.env.NODE_ENV !== 'production') {
        const StyleSheetValidation = require('./StyleSheetValidation').default;
        StyleSheetValidation.validateStyle(key, styles);
      }
      result[key] = StyleRegistry.register(styles[key]);
    });
    return result;
  },
  flatten: flattenStyle,
  getStyleSheets() {
    return StyleRegistry.getStyleSheets();
  },
  hairlineWidth: 1
};

export default StyleSheet;

Allow component styles to be editable in React Dev Tools


import { connect } from 'react-redux'
import I18n from 'i18n-js'
import { toggleSessionPopup } from '../../UserSession/actions/sessionActions'
import { setEntity } from '../../lib/actions/entityActions'
import PledgeForm from '../components/PledgeForm'

const mapStateToProps = function(state, ownProps) {
  return {
    availableTags: assembleTags(ownProps.tags),
    userLoggedIn: state.currentUser !== null,
    formId: ['PledgeForm', ownProps.id].join('-'),
  }
}

function assembleTags(tags) {
  return tags.map(function(tag) {
    return {
      value: tag.id,
      label: I18n.t(`tags.names.${tag.name}`),
    }
  })
}

const mapDispatchToProps = dispatch => ({
  onLinkClick: function(event) {
    event.preventDefault()

    dispatch(toggleSessionPopup())
    window.scrollTo(0, 0)
  },

  dispatch
})

const mergeProps = (stateProps, dispatchProps, ownProps) => ({
  ...stateProps,
  ...dispatchProps,
  ...ownProps,

  afterResponse: json => {
    console.log(json)
    if (json.status === 'success') {
      dispatchProps.dispatch(setEntity(stateProps.formId, {}))
    }
  }
})

export default connect(
  mapStateToProps,
  mapDispatchToProps,
  mergeProps
)(PledgeForm)

import { connect } from 'react-redux'
import I18n from 'i18n-js'
import { toggleSessionPopup } from '../../UserSession/actions/sessionActions'
import { setEntity } from '../../lib/actions/entityActions'
import PledgeForm from '../components/PledgeForm'
import redirectTo from '../../lib/browser/redirectTo'

const mapStateToProps = function(state, ownProps) {
  return {
    availableTags: assembleTags(ownProps.tags),
    userLoggedIn: state.currentUser !== null,
    formId: ['PledgeForm', ownProps.id].join('-'),
  }
}

function assembleTags(tags) {
  return tags.map(function(tag) {
    return {
      value: tag.id,
      label: I18n.t(`tags.names.${tag.name}`),
    }
  })
}

const mapDispatchToProps = dispatch => ({
  onLinkClick: function(event) {
    event.preventDefault()

    dispatch(toggleSessionPopup())
    window.scrollTo(0, 0)
  },

  dispatch
})

const mergeProps = (stateProps, dispatchProps, ownProps) => ({
  ...stateProps,
  ...dispatchProps,
  ...ownProps,

  afterResponse: json => {
    if (json.meta && json.meta.redirect) {
      redirectTo(json.meta.redirect)
    } else if (json.status === 'success') {
      dispatchProps.dispatch(setEntity(stateProps.formId, {}))
    }
  }
})

export default connect(
  mapStateToProps,
  mapDispatchToProps,
  mergeProps
)(PledgeForm)

Fix redirect after new pledge form is sent


/* exported configureTripKeyForPath, getTripKeyFromUrl, setProgressBar */
/**
* Sets Progress Bar to correct location based on the page number
* @param {int} pageNumber
*/
function setProgressBar(pageNumber){
  let ul = document.getElementById("progressbar");
  let items = ul.getElementsByTagName("li");
  for(let i=0; i < pageNumber;i++){
    items[i].className = 'active';
  }
}

/**
 * Go through url to retrieve the trip key.
 * @return String of trip key
 */
function getTripKeyFromUrl() {
  return new URLSearchParams(location.search).get('tripKey');
}

/**
 * Uses the trip key passed in to create a modified path from
 * the path parameter. If the trip key is null, redirects the
 * user to the page where they can make a new trip and have
 * a valid trip key to reference.
 * @param {String} tripKey unique value for a trip
 * @param {String} path to send tripKey across
 * @return String of path with tripKey in query params
 */
function configureTripKeyForPath(tripKey, path) {
  if(tripKey === null) {
    // Send back to page where a trip can be made
    alert("tripKey not created! Create a new trip.");
    window.location.href = '/index.html';
    return "";
  } else {
    return path + "?" + new URLSearchParams({tripKey}).toString();
  }
}

/* exported configureTripKeyForPath, getTripKeyFromUrl, setProgressBar */
/**
* Sets Progress Bar to correct location based on the page number
* @param {int} pageNumber
*/
function setProgressBar(pageNumber){
  let ul = document.getElementById("progressbar");
  let items = ul.getElementsByTagName("li");
  for(let i=0; i < pageNumber;i++){
    items[i].className = 'active';
  }
}

/**
 * Go through url to retrieve the trip key. If the trip key is null,
 * redirects the user to the page where they can make a new trip
 * and have a valid trip key to reference.
 * @return String of trip key
 */
function getTripKeyFromUrl() {
  const url = new URLSearchParams(location.search).get('tripKey');
  if(url === null) {
    alert("tripKey not created! Create a new trip.");
    window.location.href = '/index.html';
    return "";
  } else {
    return url;
  }
}

/**
 * Uses the trip key passed in to create a modified path from
 * the path parameter.
 * @param {String} tripKey unique value for a trip
 * @param {String} path to send tripKey across
 * @return String of path with tripKey in query params
 */
function configureTripKeyForPath(tripKey, path) {
  return path + "?" + new URLSearchParams({tripKey}).toString();
}

Check for a valid trip key when first searching in url


angular.module("proBebe.services")
.factory('ChildAgePresenter', function() {

  function Presenter() {}

  Presenter.build = function(messages){
    messages.forEach(function(message){
      message.category = "category-1";
      if(message.mon_is_pregnant){
        message.child_age_in_week_at_delivery += " semana(s)"
        message.pregnancy = true;
        message.type = "week";
      }else{
        var age = message.child_age_in_week_at_delivery;
        var month = parseInt(age * 7 / 30);
        message.age = age;
        message.type = "month";
        if(month != 0) {
          message.child_age_in_week_at_delivery = month + " meses";
        }else if(month == 1){
          message.child_age_in_week_at_delivery = month + " mês";
        }
        if(month == 0){
          message.child_age_in_week_at_delivery = age + " semana(s)";
        }
      }
      message.category = messageCategory(message);
    })
    return messages;
  }

  function messageCategory(message){
    if(message.article_category.toLowerCase() == "saúde") return "category-1";
    if(message.article_category.toLowerCase() == "educação") return "category-2";
    if(message.article_category.toLowerCase() == "desenvolvimento") return "category-3";
    if(message.article_category.toLowerCase() == "segurança") return "category-4";
    if(message.article_category.toLowerCase() == "finanças") return "category-5";
    if(message.article_category.toLowerCase() == "jurídico") return "category-6";
    if(message.article_category.toLowerCase() == "comportamento") return "category-7";
  }

  return Presenter;

});

angular.module("proBebe.services")
.factory('ChildAgePresenter', function() {

  function Presenter() {}

  Presenter.build = function(messages){
    messages.forEach(function(message){
      message.category = "category-1";
      if(message.mon_is_pregnant){
        message.child_age_in_week_at_delivery += " semana(s)"
        message.pregnancy = true;
        message.type = "week";
      }else{
        var age = message.child_age_in_week_at_delivery;
        var month = parseInt(age * 7 / 30);
        message.age = age;
        message.type = "month";
        if(month != 0) {
          message.child_age_in_week_at_delivery = month + " meses";
        }else if(month == 1){
          message.child_age_in_week_at_delivery = month + " mês";
        }
        if(month == 0){
          message.child_age_in_week_at_delivery = age + " semana(s)";
        }
      }
    })
    return messages;
  }

  return Presenter;

});

Add category color by server


import { resolve as resolvePath } from 'path';

/**
 * Require local file or node modules
 *
 * @param {String} path
 * @returns {*}
 */
export default function requireLocalFileOrNodeModule(path) {
    const localFile = resolvePath(process.cwd(), path);

    try {
        // first try to require local file
        return require(localFile);
    } catch (e) {
        // try to require node_module
        return require(path);
    }
}

import { resolve as resolvePath } from 'path';

/**
 * Require local file or node modules
 *
 * @param {String} path
 * @returns {*}
 */
export default function requireLocalFileOrNodeModule(path) {
    const localFile = resolvePath(process.cwd(), path);

    try {
        // first try to require local file
        return require(localFile);
    } catch (e) {
        if (e.code === 'MODULE_NOT_FOUND') {
            // try to require node_module
            return require(path);
        }

        throw e;
    }
}

Handle exceptions inside requiring module


/*
 * Copyright: 2012, V. Glenn Tarcea
 * MIT License Applies
 */

angular.module('AngularStomp', []).
    factory('ngstomp', function($rootScope) {
        Stomp.WebSocketClass = SockJS;
        var stompClient = {};

        function NGStomp(url) {
            this.stompClient = Stomp.client(url);
        }

        NGStomp.prototype.subscribe = function(queue, callback) {
            this.stompClient.subscribe(queue, function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback(args[0]);
                })
            })
        }

        NGStomp.prototype.send = function(queue, headers, data) {
            this.stompClient.send(queue, headers, data);
        }

        NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) {
            this.stompClient.connect(user, password,
                function(frame) {
                    $rootScope.$apply(function() {
                        on_connect.apply(stompClient, frame);
                    })
                },
                function(frame) {
                    $rootScope.$apply(function() {
                        on_error.apply(stompClient, frame);
                    })
                }, vhost);
        }

        NGStomp.prototype.disconnect = function(callback) {
            this.stompClient.disconnect(function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback.apply(args);
                })
            })
        }

        return function(url) {
            return new NGStomp(url);
        }
    });

/*
 * Copyright: 2012, V. Glenn Tarcea
 * MIT License Applies
 */

angular.module('AngularStomp', []).
    factory('ngstomp', function($rootScope) {
        var stompClient = {};

        function NGStomp(url) {
            this.stompClient = Stomp.client(url);
        }

        NGStomp.prototype.subscribe = function(queue, callback) {
            this.stompClient.subscribe(queue, function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback(args[0]);
                })
            })
        }

        NGStomp.prototype.send = function(queue, headers, data) {
            this.stompClient.send(queue, headers, data);
        }

        NGStomp.prototype.connect = function(user, password, on_connect, on_error, vhost) {
            this.stompClient.connect(user, password,
                function(frame) {
                    $rootScope.$apply(function() {
                        on_connect.apply(stompClient, frame);
                    })
                },
                function(frame) {
                    $rootScope.$apply(function() {
                        on_error.apply(stompClient, frame);
                    })
                }, vhost);
        }

        NGStomp.prototype.disconnect = function(callback) {
            this.stompClient.disconnect(function() {
                var args = arguments;
                $rootScope.$apply(function() {
                    callback.apply(args);
                })
            })
        }

        return function(url) {
            return new NGStomp(url);
        }
    });

Remove hard coded socket provider class.


import express from 'express'
import session from 'express-session'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import passport from 'passport'
import routes from './api/routes'
import dotenv from 'dotenv'
import container from './dependency-container/container'

// Load environment variables from .env file
dotenv.load()

let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()

app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))
app.use(session({
  resave: false,
  secret: 'TEST'
}))
app.use(passport.initialize())
app.use(passport.session())

routes(app, passport)

// app.all('*', (req, res) => res.send('Hello World'))

app.listen(port, () => {
  console.log('Mission Control listening at http://%s:%s', host, port)
})

import express from 'express'
import session from 'express-session'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import morgan from 'morgan'
import passport from 'passport'
import routes from './api/routes'
import dotenv from 'dotenv'
import container from './dependency-container/container'

// Load environment variables from .env file
dotenv.load()

let port = process.env.PORT || 3000
let host = process.env.HOST || 'localhost'
let app = express()

app.use(morgan('dev'))
app.use(cookieParser())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
  extended: true
}))
app.use(session({
  resave: false,
  secret: 'TEST'
}))
app.use(passport.initialize())
app.use(passport.session())

routes(app, passport)

app.listen(port, () => {
  console.log('Mission Control listening at http://%s:%s', host, port)
})

Fix code style for pm2 module


// Bulk Operation
exports.updateOperation = (id, actionType, contentType, connection) => {
  return connection(contentType)
  .where(`${contentType}.id`, '=', id)
  .update(`${contentType}.status`, actionType)
  .then((result) => {
    return connection(contentType)
    .select()
  })
}

exports.deleteOperation = (id, contentType, connection) => {
  return connection(contentType)
  .where(`${contentType}.id`, '=', id)
  .delete()
  .then((result) => {
    return connection(contentType)
    .select()
  })
}

// ADMIN SECTION SQL

// Manage Content - URL - /admin/contenttype/content
exports.getAdminContent = (contentType, connection) => {
  return connection(contentType)
  .join('users', 'users.id', `${contentType}.author`)
  .select(`${contentType}.id as contentId`, 'title', 'status', 'type', 'published_date', 'users.name as name', 'slug')
  .orderByRaw(`${contentType}.id DESC`)
}

// Manage Taxonomy & Tags - URL - /admin/taxonomies

// Manage Menu Structure - URL - /admin/menus

// Manage Users - URL - /admin/users

// TAXONOMY SQL
exports.getTaxonomy = (connection) => {
  return connection('taxonomy_vocabulary')
  .select()
}

// Bulk Operation
exports.updateOperation = (id, actionType, contentType, connection) => {
  return connection(contentType)
  .where(`${contentType}.id`, '=', id)
  .update(`${contentType}.status`, actionType)
  .then((result) => {
    return connection(contentType)
    .select()
  })
}

exports.deleteOperation = (id, contentType, connection) => {
  return connection(contentType)
  .where(`${contentType}.id`, '=', id)
  .delete()
  .then((result) => {
    return connection(contentType)
    .select()
  })
}

// ADMIN SECTION SQL

// Manage Content - URL - /admin/contenttype/content
exports.getAdminContent = (contentType, connection) => {
  return connection(contentType)
  .join('users', 'users.id', `${contentType}.author`)
  .select(`${contentType}.id as contentId`, 'title', 'status', 'type', 'published_date', 'users.name as name', 'slug')
  .orderByRaw(`${contentType}.id DESC`)
}

// Manage Taxonomy & Tags - URL - /admin/taxonomies
exports.getTaxonomy = (connection) => {
  return connection('taxonomy_vocabulary')
  .select()
  .orderByRaw(`${taxonomy_vocabulary}.name DESC`)
}
// Manage Menu Structure - URL - /admin/menus

// Manage Users - URL - /admin/users

// TAXONOMY SQL

Move query to line 33


jQuery( document ).ready(function( $ ) {

	// Variables
	var open 			 = false, // Set the state of the menu on load (false = closed)
		body             = $('body'),
		siteContainer    = $('.site-container'),
		toggleButtons    = $('.menu-btn, .close-btn, .site-overlay, .nav-primary a'); // Also select menu links to cause a trigger when navigating

	// Function to open the menu
	function openMenu() {
		body.addClass('off-canvas-active');
		siteContainer.css({"overflow-x": "hidden"}); // IE Bug
	}

	// Function to close the menu
	function closeMenu() {
		body.removeClass('off-canvas-active');
		siteContainer.css({"overflow-x": ""}); // IE Bug
	}

	/**
		This is our main function. It checks the "open" variable to see
		whether our menu is open or not. Depending on the response, we either
		open or close the menu.
	**/
	function animateMenu() {
		if (open) {
			closeMenu();
			open = false;
		} else {
			openMenu();
			open = true;
		}
	}

	/**
		Listen for clicks of any of the toggle buttons set at the top,
		and initiate the animateMenu() function.
	**/
	toggleButtons.click(function(event) {

		// Prevent the default action of clicking a link
		event.preventDefault();

		// Run the main function
		animateMenu();
	});
});

jQuery( document ).ready(function( $ ) {

	// Variables
	var open 			 = false, // Set the state of the menu on load (false = closed)
		body             = $('body'),
		siteContainer    = $('.site-container'),
		toggleButtons    = $('.menu-btn, .close-btn, .site-overlay');

	// Function to open the menu
	function openMenu() {
		body.addClass('off-canvas-active');
		siteContainer.css({"overflow-x": "hidden"}); // IE Bug
	}

	// Function to close the menu
	function closeMenu() {
		body.removeClass('off-canvas-active');
		siteContainer.css({"overflow-x": ""}); // IE Bug
	}

	/**
		This is our main function. It checks the "open" variable to see
		whether our menu is open or not. Depending on the response, we either
		open or close the menu.
	**/
	function animateMenu() {
		if (open) {
			closeMenu();
			open = false;
		} else {
			openMenu();
			open = true;
		}
	}

	/**
		Listen for clicks of any of the toggle buttons set at the top,
		and initiate the animateMenu() function.
	**/
	toggleButtons.click(function(event) {

		// Prevent the default action of clicking a link
		event.preventDefault();

		// Run the main function
		animateMenu();
	});
});

Remove menu links as triggers.