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

/**
 * WordPress dependencies
 */
import { Fragment } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { useFeature } from '../../hooks/useFeature';
import { ActivationBanner } from '../../modules/analytics-4/components/dashboard';
import ZeroDataNotifications from './ZeroDataStateNotifications';

export default function EntityBannerNotifications() {
	const ga4ActivationBannerEnabled = useFeature( 'ga4ActivationBanner' );

	return (
		<Fragment>
			{ ga4ActivationBannerEnabled && <ActivationBanner /> }
			<ZeroDataNotifications />
		</Fragment>
	);
}

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

/**
 * WordPress dependencies
 */
import { Fragment } from '@wordpress/element';

/**
 * Internal dependencies
 */
import { useFeature } from '../../hooks/useFeature';
import { ActivationBanner } from '../../modules/analytics-4/components/dashboard';
import ZeroDataNotifications from './ZeroDataStateNotifications';
import useViewOnly from '../../hooks/useViewOnly';

export default function EntityBannerNotifications() {
	const viewOnly = useViewOnly();
	const ga4ActivationBannerEnabled = useFeature( 'ga4ActivationBanner' );

	return (
		<Fragment>
			{ ! viewOnly && ga4ActivationBannerEnabled && <ActivationBanner /> }
			<ZeroDataNotifications />
		</Fragment>
	);
}

Add view-only mode to GA4 activation banner.


var express = require('express');
var app = express();

var CurrentUser = require('../Architecture/CurrentUser').CurrentUser;
var WebService = require('../Architecture/WebService').WebService;
var MongoAdapter = require('../Adapters/Mongo').MongoAdapter;
var RedisAdapter = require('../Adapters/Redis').RedisAdapter;

var mongodb = new MongoAdapter();
var redis = new RedisAdapter();

var webServiceRun;

var runService = function (name, allowedTypeAccount, params) {
	return function (req, res) {
		params.req = req;
		params.res = res;
		webServiceRun(name, allowedTypeAccount, params);
	};
};

app.use(mongodb.connect());
app.use(redis.connect());

app.use(function (req, res, next) {
	var webServiceInit = new WebService(new CurrentUser());

	webServiceInit.addDependency('mongo', mongodb);
	webServiceInit.addDependency('redis', redis);
	webServiceRun = webServiceInit.run.bind(webServiceInit);
	next();
});

app.use(express.static('Resources'));

// ### Routing ###

app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' }));
app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' }));

app.listen(4444);
console.log('Server listening on port 4444.');

var express = require('express');
var app = express();

var CurrentUser = require('../Architecture/CurrentUser').CurrentUser;
var WebService = require('../Architecture/WebService').WebService;
var MongoAdapter = require('../Adapters/Mongo').MongoAdapter;
var RedisAdapter = require('../Adapters/Redis').RedisAdapter;

var webServiceInit = new WebService(new CurrentUser());
var runService = webServiceInit.runWrapper();

// Database adapters.
var mongodb = new MongoAdapter();
var redis = new RedisAdapter();

app.use(mongodb.connect());
app.use(redis.connect());

app.use(function (req, res, next) {
	// Add things to dependencies in everything service.
	webServiceInit.addDependency('mongo', mongodb);
	webServiceInit.addDependency('redis', redis);
	next();
});

app.use(function (req, res, next) {
	webServiceInit.runRef = webServiceInit.run.bind(webServiceInit);
	next();
});

app.use(express.static('Resources'));

// ### Routing ###

app.get('/login', runService('loginGet', [0, 1, 2, 3], { param1: 'value1', param2: 'value2' }));
app.get('/secret', runService('secretGet', [2, 3], { param1: 'value1', param2: 'value2' }));

app.listen(process.argv[2]);
console.log('Server listening on port ' + process.argv[2] + '.');

Move runService function to WebService. Add comments. Get possibility set port via process.argv.


const stream = require('stream')
const url = require('url')

const logger = require('prolific.logger').create('compassion.colleague')

const axios = require('axios')
const httpAdapter = require('axios/lib/adapters/http')

module.exports = {
    json: async (location, path, body) => {
        const resolved = url.resolve(location, path)
        try {
            if (body == null) {
                return (await axios.get(resolved)).data
            } else {
                return (await axios.post(resolved, body)).data
            }
        } catch (error) {
            logger.error('ua', { url: resolved, stack: error.stack })
            return null
        }
    },

    // See: // https://github.com/andrewstart/axios-streaming/blob/master/axios.js
    stream: async (location, path, body) => {
        const resolved = url.resolve(location, path)
        try {
            const response = await axios.post(resolved, body, {
                responseType: 'stream',
                adapter: httpAdapter
            })
            if (Math.floor(response.status / 100) == 2) {
                return response.data
            }
        } catch (error) {
            logger.error('ua', { url: resolved, stack: error.stack })
        }
        const empty = new stream.PassThrough
        empty.end()
        return empty
    }
}

const stream = require('stream')
const url = require('url')

const logger = require('prolific.logger').create('compassion.colleague')

const axios = require('axios')
const httpAdapter = require('axios/lib/adapters/http')

module.exports = {
    json: async (location, path, body) => {
        const resolved = url.resolve(location, path)
        try {
            if (body == null) {
                return (await axios.get(resolved)).data
            } else {
                return (await axios.post(resolved, body)).data
            }
        } catch (error) {
            logger.error('ua', { url: resolved, stack: error.stack })
            return null
        }
    },

    // See: // https://github.com/andrewstart/axios-streaming/blob/master/axios.js
    stream: async (location, path, body) => {
        const resolved = url.resolve(location, path)
        try {
            return (await axios.post(resolved, body, {
                responseType: 'stream',
                adapter: httpAdapter
            })).data
        } catch (error) {
            logger.error('ua', { url: resolved, stack: error.stack })
        }
        const empty = new stream.PassThrough
        empty.end()
        return empty
    }
}

Remove dead error check from user agent.


// create a new signaller, connecting to the target switchboard
var signaller = require('..')('//switchboard.rtc.io/');

// when a new peer is announced, log it
signaller.on('peer:announce', function(data) {
 console.log('new peer found in room: ', data);
});

signaller.on('peer:disconnected', function(id) {
  console.log('peer ' + id + ' has been disconnected');
});

// when a peer leaves the switchboard, log it
signaller.on('peer:leave', function(id) {
  console.log('peer ' + id + ' has left the room');
});

// for our sanity, pop a message once we are connected
signaller.once('connected', function() {
  console.log('we have successfully connected');
});

// send through an announce message
// this will occur once the primus socket has been opened and active
signaller.announce({ room: 'signaller-getting-started' });

// create a new signaller, connecting to the target switchboard
var signaller = require('..')('//switchboard.rtc.io/');

// when a new peer is announced, log it
signaller.on('peer:announce', function(data) {
 console.log('new peer found in room: ', data);
});

// for our sanity, pop a message once we are connected
signaller.once('connected', function() {
  console.log('we have successfully connected');
});

// send through an announce message
// this will occur once the primus socket has been opened and active
signaller.announce({ room: 'signaller-getting-started' });

Remove references to disconnection and leave events in the signaller


Components.utils.import('resource://greasemonkey/util.js');

var EXPORTED_SYMBOLS = ['uriFromUrl'];

function uriFromUrl(url, base) {
  var ioService = Components.classes["@mozilla.org/network/io-service;1"]
      .getService(Components.interfaces.nsIIOService);
  var baseUri = null;

  if (typeof base === "string") {
    baseUri = GM_util.uriFromUrl(base);
  } else if (base) {
    baseUri = base;
  }

  try {
    return ioService.newURI(url, null, baseUri);
  } catch (e) {
    return null;
  }
}
uriFromUrl = GM_util.memoize(uriFromUrl);

Components.utils.import('resource://greasemonkey/util.js');

var EXPORTED_SYMBOLS = ['uriFromUrl'];

var ioService = Components.classes["@mozilla.org/network/io-service;1"]
    .getService(Components.interfaces.nsIIOService);

function uriFromUrl(url, base) {
  var baseUri = null;
  if (typeof base === "string") {
    baseUri = GM_util.uriFromUrl(base);
  } else if (base) {
    baseUri = base;
  }

  try {
    return ioService.newURI(url, null, baseUri);
  } catch (e) {
    return null;
  }
}
uriFromUrl = GM_util.memoize(uriFromUrl);

Make a single io service, not one per run.


$(function(){
    setup_table();
});

function setup_table() {
    $('#dists').DataTable({
        paging: false,
        autoWidth: false,
        scrollX: false,
        info: false,
        columnDefs: [
            {
                targets: [ 2, 3, 4, 5, 6 ],
                searchable: false
            },
            {
                targets: [ 6 ],
                orderSequence: [ "desc", "asc" ]
            }
        ]
    });

    $('#dists_wrapper').addClass('table-responsive').unwrap();
    $('#search').remove();

    var filter_container = $('#dists_filter');
    var filter = filter_container.addClass('form-group').find('[type=search]')
        .addClass('form-control').attr('placeholder', 'Search');
    filter_container.append(filter);
    filter_container.find('label').remove();

    filter.focus();
}

$(function(){
    setup_table();
});

function setup_table() {
    var filter_container, filter;

    $('#dists').DataTable({
        paging: false,
        autoWidth: false,
        scrollX: false,
        info: false,
        columnDefs: [
            {
                targets: [ 2, 3, 4, 5, 6 ],
                searchable: false
            },
            {
                targets: [ 6 ],
                orderSequence: [ "desc", "asc" ]
            }
        ]
    });

    // Mess around with markup to accomodate the table plugin and marry
    // it nicely with both our JS-less version of the site and Bootstrap
    $('#dists_wrapper').addClass('table-responsive').unwrap();
    $('#search').remove();
    filter_container = $('#dists_filter');
    filter = filter_container.addClass('form-group').find('[type=search]')
        .addClass('form-control').attr('placeholder', 'Search');
    filter_container.append(filter);
    filter_container.find('label').remove();
    filter.focus();
}

Clarify what the code is for


import Fuse from 'fuse.js';

const annotateType = type => tab => Object.assign({}, tab, { type });

export default function filterResults(
  query,
  options,
  {
    showRecentlyClosed,
    recentlyClosedLimit,
  },
) {
  return function promiseTabResults(loadedTabs) {
    const tabsToSearch = loadedTabs.map(annotateType('tab'));
    return showRecentlyClosed
      ? Promise.all([
        tabsToSearch,
        getRecentlyClosed(recentlyClosedLimit),
      ]).then(([tabs, sessions]) => [...tabs, ...sessions])
      : Promise.resolve(new Fuse(tabsToSearch, options).search(query));
  };
}

function getRecentlyClosed(maxResults) {
  const tab = ({ tab: _tab }) => _tab;
  return browser.sessions.getRecentlyClosed({ maxResults })
    .then(sessionObjects =>
      sessionObjects.filter(tab).map(tab).map(annotateType('session')),
    )
    .then(x => { console.log('sessions', x); return x; });
}

import Fuse from 'fuse.js';
import { deletedTabsCache } from './caches';
import {
  TAB_TYPE,
  OTHER_WINDOW_TAB_TYPE,
  SESSION_TYPE,
} from './constants';
import {
  identity,
  isOfWindow,
  isOfType,
  annotateTypeCondtionally,
  annotateType,
  doubleFilterAndMerge,
} from './utils/array';

export default function filterResult(
  query,
  options,
  {
    showRecentlyClosed,
    recentlyClosedLimit,
    alwaysShowRecentlyClosedAtTheBottom,
  },
) {
  return function promiseSearchResults(loadedTabs) {
    const isQueryEmpty = query.length === 0;
    const isTabType = isOfType(TAB_TYPE);
    const tabFilter = showRecentlyClosed
      ? identity
      : ({ id }) => !deletedTabsCache().includes(id);
    // First filter any unwanted results
    const annotatedTabs = loadedTabs.filter(tabFilter)
      .map(
        annotateTypeCondtionally(
          isOfWindow(3),
          [TAB_TYPE, OTHER_WINDOW_TAB_TYPE],
        ),
      );
    // If we want to move the closed tabs to the botttom filter it
    const shouldMoveClosedToBottom = showRecentlyClosed
      && alwaysShowRecentlyClosedAtTheBottom;
    const arrayToSearch = showRecentlyClosed
      ? Promise.all([
        annotatedTabs,
        getRecentlyClosed(recentlyClosedLimit),
      ]).then(([tabs, sessions]) => [...tabs, ...sessions])
      : Promise.resolve(annotatedTabs);
    const doFinalOperation = shouldMoveClosedToBottom
      ? doubleFilterAndMerge(isTabType)
      : identity;
    const search = isQueryEmpty
      ? identity
      : arr => new Fuse(arr, options).search(query);
    return arrayToSearch
      .then(search)
      .then(doFinalOperation);
  };
}

function getRecentlyClosed(maxResults) {
  const tab = ({ tab: _tab }) => _tab;
  const getTabsAndAnnotate = objects =>
    objects.filter(tab).map(tab).map(annotateType(SESSION_TYPE));
  return browser.sessions.getRecentlyClosed({ maxResults })
    .then(getTabsAndAnnotate);
}

Annotate object array with the object types, and handle specified settings


function NightRainbowTheme () {
  this.paletteBuilder = new SingleColorPaletteBuilder(new HSL(180, 60, 29));
}

NightRainbowTheme.prototype.colors = [
  new HSL(0, 100, 84),
  new HSL(25, 100, 72),
  new HSL(55, 100, 43),
  new HSL(150, 100, 50),
  new HSL(200, 100, 70),
  new HSL(252, 100, 86),
  new HSL(290, 100, 82)
];

NightRainbowTheme.prototype.numberColor = '#202030';

NightRainbowTheme.prototype.defaultBackgroundColor = '#202030';

NightRainbowTheme.prototype.textColor = '#000000';

NightRainbowTheme.prototype.textBackground = '#FFFFFF';

NightRainbowTheme.prototype.sliderColor = '#FFFFFF';

NightRainbowTheme.prototype.changesDocumentTextColor = true;

NightRainbowTheme.prototype.getLevelPalette = function (level) {
  var numberColor = this.colors[(level - 1) % 7];
  var boardColors = this.paletteBuilder.build(16);
  return new LevelPalette(numberColor, boardColors);
};

function NightRainbowTheme () {
  this.paletteBuilder = new SingleColorPaletteBuilder(new HSL(180, 60, 30));
}

NightRainbowTheme.prototype.colors = [
  new HSL(0, 100, 77),
  new HSL(25, 100, 64),
  new HSL(57, 100, 37),
  new HSL(150, 100, 43),
  new HSL(200, 100, 60),
  new HSL(252, 100, 80),
  new HSL(290, 100, 77)
];

NightRainbowTheme.prototype.numberColor = '#202030';

NightRainbowTheme.prototype.defaultBackgroundColor = '#202030';

NightRainbowTheme.prototype.textColor = '#000000';

NightRainbowTheme.prototype.textBackground = '#FFFFFF';

NightRainbowTheme.prototype.sliderColor = '#FFFFFF';

NightRainbowTheme.prototype.changesDocumentTextColor = true;

NightRainbowTheme.prototype.getLevelPalette = function (level) {
  var numberColor = this.colors[(level - 1) % 7];
  var boardColors = this.paletteBuilder.build(16);
  return new LevelPalette(numberColor, boardColors);
};

Adjust night rainbow theme colors


(function() {
  'use strict';

  var app = angular.module('radar.filters');

  app.filter('ageFormat', [function() {
    return function ageFormat(seconds) {
      var output;

      if (seconds) {
        var years = seconds / (365 * 24 * 60 * 60);
        var months = Math.floor((years - Math.floor(years)) * 12);
        years = Math.floor(years);

        output = years + ' ' + (years === 1 ? 'year' : 'years') + ', ' + months + ' ' + (months === 1 ? 'month' : 'months');
      } else {
        output = '-';
      }

      return output;
    };
  }]);
})();

(function() {
  'use strict';

  var app = angular.module('radar.filters');

  app.filter('ageFormat', [function() {
    return function ageFormat(seconds) {
      var output;

      if (seconds !== null && seconds !== undefined) {
        var years = seconds / (365 * 24 * 60 * 60);
        var months = Math.floor((years - Math.floor(years)) * 12);
        years = Math.floor(years);

        output = years + ' ' + (years === 1 ? 'year' : 'years');

        if (months > 0) {
            output +=  ', ' + months + ' ' + (months === 1 ? 'month' : 'months');
        }
      } else {
        output = '-';
      }

      return output;
    };
  }]);
})();

Add age of onset and diagnosis


const fs = require('fs');
const path = require('path');
const express = require('express');

const router = express.Router();

router.get('/', function (req, res) {
  res.send('Add a Project or Owner id to the URL bar!');
});

router.get('/:owner', [
  require('./owner-project-list'),
  require('./redirect-to-project')
]);

router.get([
  '/:owner/:project',
  '/:owner/:project/report',
  '/:owner/:project/presentation'
], [
  require('./cache-project'),
  require('./render-project')
]);

// reveal.js assets
router.use('/:owner/:project/presentation', express.static('public/reveal'));

// pull presentation.md from project dir
router.get('/:owner/:project/presentation/presentation.md', function (req, res) {
  const mdPath = path.join(req.app.locals.cacheDir, req.params.owner, req.params.project, 'presentation.md');
  fs.readFile(mdPath, {encoding: 'utf8'}, (err, data) => {
    if (err) throw err

    res.send(data);
  });
});

module.exports = router;

const fs = require('fs');
const path = require('path');
const express = require('express');

const router = express.Router();

router.get('/', function (req, res) {
  res.send('Add a Project or Owner id to the URL bar!');
});

router.get('/:owner', [
  require('./owner-project-list'),
  require('./redirect-to-project')
]);

router.get([
  '/:owner/:project',
  '/:owner/:project/report',
  '/:owner/:project/presentation'
], [
  require('./cache-project'),
  require('./render-project')
]);

// :type is the /report or /presentation url fragment
// since it's virtual we map the file path by omitting it
router.get('/:owner/:project/:type/:asset', function (req, res, next) {
  const p = req.params;
  res.sendFile(path.join(req.app.locals.cacheDir, p.owner, p.project, p.asset));
});

// reveal.js assets
router.use('/:owner/:project/presentation', express.static('public/reveal'));

module.exports = router;

Add support for project assets like parallax and other files


'use strict';

var eventsApp = angular.module('eventsApp', ['ngResource', 'ngCookies'])
	.factory('myCache', function($cacheFactory) {
		return $cacheFactory('myCache', {capacity: 3});
	});

'use strict';

var eventsApp = angular.module('eventsApp', ['ngResource'])
	.factory('myCache', function($cacheFactory) {
		return $cacheFactory('myCache', {capacity: 3});
	});

Remove ngCookies as a dependency (we won't need it anymore)


(function() {
  window.shared || (window.shared = {});
  var Simulate = React.addons.TestUtils.Simulate;

  /* Sugar for common test setup and interactions */
  var SpecSugar = window.shared.SpecSugar = {
    withTestEl: function(description, testsFn) {
      return describe(description, function() {
        beforeEach(function() {
          this.testEl = $('<div id="test-el" />').get(0);
          $('body').append(this.testEl);
        });

        afterEach(function() {
          $(this.testEl).remove();
        });

        testsFn.call(this);
      });
    },

    // Update the text value of an input or textarea, and simulate the React
    // change event.
    changeTextValue: function($el, value) {
      $el.val(value);
      Simulate.change($el.get(0));
      return undefined;
    },

    // Simulates opening the react-select dropdown and clicking the item
    // with `optionText`.
    changeReactSelect: function($el, optionText) {
      React.addons.TestUtils.Simulate.mouseDown($selectEl.find('.Select-arrow-zone').get(0));
      React.addons.TestUtils.Simulate.focus($selectEl.find('input:last').get(0));
      $selectEl.find('.Select-option:contains(' + optionText + ')').click()
      return undefined;
    }
  };
})();

(function() {
  window.shared || (window.shared = {});
  var Simulate = React.addons.TestUtils.Simulate;

  /* Sugar for common test setup and interactions */
  var SpecSugar = window.shared.SpecSugar = {
    withTestEl: function(description, testsFn) {
      return describe(description, function() {
        beforeEach(function() {
          this.testEl = $('<div id="test-el" />').get(0);
          $('body').append(this.testEl);
        });

        afterEach(function() {
          $(this.testEl).remove();
        });

        testsFn.call(this);
      });
    },

    // Update the text value of an input or textarea, and simulate the React
    // change event.
    changeTextValue: function($el, value) {
      $el.val(value);
      Simulate.change($el.get(0));
      return undefined;
    },

    // Simulates opening the react-select dropdown and clicking the item
    // with `optionText`.
    changeReactSelect: function($selectEl, optionText) {
      React.addons.TestUtils.Simulate.mouseDown($selectEl.find('.Select-arrow-zone').get(0));
      React.addons.TestUtils.Simulate.focus($selectEl.find('input:last').get(0));
      $selectEl.find('.Select-option:contains(' + optionText + ')').click()
      return undefined;
    }
  };
})();

Add integration test for recording service form


(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        return mod(require("tern/lib/infer"), require("tern/lib/tern"), require("acorn/dist/acorn"), require("acorn-jsx"));
    if (typeof define == "function" && define.amd) // AMD
        return define([ "tern/lib/infer", "tern/lib/tern", "acorn/dist/acorn", "acorn-jsx" ], mod);
    mod(tern, tern, acorn, acornJSX);
})(function(infer, tern, acorn, acornJSX) {
  "use strict";

  tern.registerPlugin("react", function(server, options) {
	  acornJSX(acorn);
	  server.on("preParse", preParse);
  });

  function preParse(text, options) {
	var plugins = options.plugins;
	if (!plugins) plugins = options.plugins = {};
    plugins["jsx"] = true;
  }

})

(function(mod) {
    if (typeof exports == "object" && typeof module == "object") // CommonJS
        return mod(require("tern/lib/infer"), require("tern/lib/tern"), require("acorn/dist/acorn"), require("acorn/dist/walk"), require("acorn-jsx"));
    if (typeof define == "function" && define.amd) // AMD
        return define([ "tern/lib/infer", "tern/lib/tern", "acorn/dist/acorn", "acorn/dist/walk", "acorn-jsx" ], mod);
    mod(tern, tern, acorn, acorn.walk, acornJSX); // Plain browser env
})(function(infer, tern, acorn, walk, acornJSX) {
  "use strict";

  // Override acorn.walk with JSX
  // see https://github.com/chtefi/acorn-jsx-walk/blob/master/index.js
  var base = walk.base;
  base.JSXElement = function (node, st, c) {
   // node.openingElement.name
   node.children.forEach(function (n) {
     c(n, st);
   });
   // node.closingElement.name
  };

  base.JSXExpressionContainer = function (node, st, c) {
    c(node.expression, st);
  };

  tern.registerPlugin("react", function(server, options) {
    acornJSX(acorn);
    server.on("preParse", preParse);
  });

  function preParse(text, options) {
	var plugins = options.plugins;
	if (!plugins) plugins = options.plugins = {};
    plugins["jsx"] = true;
  }

})

Customize acorn walk with JSX.


import React from "react";
import ReactDOM from "react-dom";
import jQuery from "jquery";
import { CommentBox } from "./components/comment-box";

import { Router, Route } from 'react-router';
import { LTopMenu } from './layouts/l-top-menu';

jQuery(function() {
  ReactDOM.render(
    <CommentBox />,
    document.getElementById('comment-box'),
    function () {
      console.timeEnd('react-app');
    }
  );
})

import React from "react";
import ReactDOM from "react-dom";
import jQuery from "jquery";
import { CommentBox } from "./components/comment-box";

import { Router, Route } from 'react-router';
import { LTopMenu } from './layouts/l-top-menu';

const App = (
  <Router>
    <Route path="/" component={LTopMenu} ></Route>
  </Router>
)

jQuery(function() {
  ReactDOM.render(
    App,
    document.getElementById('comment-box'),
    function () {
      console.timeEnd('react-app');
    }
  );
})

Add App with Router, Route


function initMocha(files) {
  files.push({pattern: __dirname + '/src/circus-init.js', included: true, served: true, watched: false});
}

initMocha.$inject = ['config.files'];

module.exports = {
  'framework:circus': ['factory', initMocha]
};

function init(files) {
  files.push({pattern: __dirname + '/src/circus-init.js', included: true, served: true, watched: false});
}

init.$inject = ['config.files'];

module.exports = {
  'framework:circus': ['factory', init]
};

Fix copy and paste naming error


var fs = require('fs'),
    levelup = require('levelup'),
    leveldown = require('leveldown'),
    key = require('./lib/key.js');

var dbs = fs.readdirSync('./ldb/').filter(function(item) {
   return item.indexOf('.ldb') > -1;
});

dbs.forEach(function(ldb, idx) {
    levelup('./ldb/' + ldb, {
        createIfMissing: false,
        max_open_files: 500
    }, function(err, db) {
        if (err) return console.log(err);
        var file = fs.createWriteStream('./fixed/' + ldb);
        file.once('open', function() {
            db.createReadStream({lt: '0001'})
                .on('data', function(data) {
                    file.write(key.decompose(data.key).hash + '\n');
                })
                .on('end', function(data) {
                    file.end();
                });
        });
    });
});

var fs = require('fs'),
    levelup = require('levelup'),
    leveldown = require('leveldown'),
    key = require('./lib/key.js');

var dbs = fs.readdirSync('./ldb/').filter(function(item) {
   return item.indexOf('.ldb') > -1;
});

fs.stat('./fixed', function(err, stats) {
    if (err && (err.errno == 34)) fs.mkdirSync('./fixed');
});

dbs.forEach(function(ldb, idx) {
    levelup('./ldb/' + ldb, {
        createIfMissing: false,
        max_open_files: 500
    }, function(err, db) {
        if (err) return console.log(err);
        var file = fs.createWriteStream('./fixed/' + ldb);
        file.once('open', function() {
            db.createReadStream({lt: '0001'})
                .on('data', function(data) {
                    file.write(key.decompose(data.key).hash + '\n');
                })
                .on('end', function(data) {
                    file.end();
                });
        });
    });
});

Create the dir if missing


// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

exports.releaseReadyWait = function() {
  cordova.exec(null,null,'ChromeExtensionURLs','release',[])
};

// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

var exports = module.exports;
var exec = cordova.require('cordova/exec');

exports.releaseReadyWait = function() {
  cordova.exec(null,null,'ChromeExtensionURLs','release',[])
};

Fix cordova requires in releaseReadyWait method


var nocache = require('..')

var assert = require('assert')
var connect = require('connect')
var request = require('supertest')

describe('nocache', function () {
  it('sets headers properly', function (done) {
    var app = connect()
    app.use(function (req, res, next) {
      res.setHeader('ETag', 'abc123')
      next()
    })
    app.use(nocache())
    app.use(function (req, res) {
      res.end('Hello world!')
    })

    request(app).get('/')
    .expect('Surrogate-Control', 'no-store')
    .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
    .expect('Pragma', 'no-cache')
    .expect('Expires', '0')
    .expect('ETag', 'abc123')
    .end(done)
  })

  it('names its function and middleware', function () {
    assert.equal(nocache.name, 'nocache')
    assert.equal(nocache().name, 'nocache')
  })
})

var nocache = require('..')

var assert = require('assert')
var connect = require('connect')
var request = require('supertest')

describe('nocache', function () {
  it('sets headers properly', function (done) {
    var app = connect()
    app.use(function (req, res, next) {
      res.setHeader('ETag', 'abc123')
      next()
    })
    app.use(nocache())
    app.use(function (req, res) {
      res.end('Hello world!')
    })

    request(app).get('/')
    .expect('Surrogate-Control', 'no-store')
    .expect('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate')
    .expect('Pragma', 'no-cache')
    .expect('Expires', '0')
    .expect('ETag', 'abc123')
    .expect('Hello world!')
    .end(done)
  })

  it('names its function and middleware', function () {
    assert.equal(nocache.name, 'nocache')
    assert.equal(nocache().name, 'nocache')
  })
})

Add test to make sure nocache calls `next()`


export default {
  input: 'js/app.js',
  output: {
    file: 'dist/index.js',
    format: 'umd'
  }
};

import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';

export default {
  input: 'js/app.js',
  output: {
    file: 'dist/index.js',
    format: 'umd'
  },
  plugins: [
    commonjs(),
    nodeResolve()
  ]
};

Use plugins to import modules from `node_modules`


import test from 'ava'
import names from '../dist'

const isObject = obj => typeof obj === 'object' && obj !== null

test.beforeEach('requesting data', async t => {
  let list

  try {
    list = await names()
  } catch (err) {
    t.fail(err)
  }

  t.context = list
  t.pass()
})

test('response is valid object', async t => {
  t.truthy(isObject(t.context))
})

import test from 'ava'
import names from '../dist'

const isObject = obj => typeof obj === 'object' && obj !== null

test.beforeEach('requesting data', async t => {
  let list

  try {
    list = await names()
  } catch (err) {
    t.fail(err)
  }

  t.context = list
  t.pass()
})

test('response is valid object', t => {
  t.truthy(isObject(t.context))
})

test('no fields missing', t => {
  const needed = [
    'name',
    'surname',
    'gender',
    'region'
  ]

  for (let field of needed) {
    if (!t.context[field]) t.fail()
  }

  t.pass()
})

Check if field is missing


const router = require('express').Router();

/* GET users listing. */
router.get('/*', (req, res, next) => {
  const urlPath = req.originalUrl;
  const domainName = urlPath.split('/')[1];
  res.send('Looking up ' + domainName);
});

module.exports = router;

const router = require('express').Router();

/* GET users listing. */
router.get('/*', (req, res, next) => {
  const domainName = parseDomainFromUrlPath(req.originalUrl);

  res.send('Looking up ' + domainName);
});

function parseDomainFromUrlPath(urlPath) {
  return urlPath.split('/')[1];
}

module.exports = router;

Refactor domain parsing into separate method


import app from '../app';

const polyT = function (...args) {
  return app.polyglot.t(...args);
};

export {
  polyT,
};

import app from '../app';

export function polyT(...args) {
  return app.polyglot.t(args);
}

Put export back to previous pattern.


module.exports = function(content) {
  this.cacheable();
  return content + '\nmodule.exports = [module.exports[0][1]]';
};

module.exports = function(content) {
  this.cacheable();
  return content + '\nmodule.exports = module.exports[0][1]';
};

Return string instead of array


var q = require('q');
module.exports = {
  waitFor: function(condition, timeout, frequency){
    timeout = timeout || 1000
    frequency = frequency || 10
    return new q.Promise(function(resolve, reject){
      var timedout = false, it = setInterval(function(){
        try {
          condition()

          resolve()
          clearInterval(it)
        } catch(e){
          if(timedout) {
            reject(e)
            clearInterval(it)
          }
        }
      }, frequency)
      setTimeout(function(){
        timedout=true
      }, timeout)
    })
  },
  justWait: function(timeout){
    return new q.Promise(function(resolve, reject){
      setTimeout(resolve, timeout)
    })
  }
}

var q = require('q');
module.exports = {
  waitFor: function(condition, timeout, frequency){
    timeout = timeout || 1000
    frequency = frequency || 10
    return new q.promise(function(resolve, reject){
      var timedout = false, it = setInterval(function(){
        try {
          condition()

          resolve()
          clearInterval(it)
        } catch(e){
          if(timedout) {
            reject(e)
            clearInterval(it)
          }
        }
      }, frequency)
      setTimeout(function(){
        timedout=true
      }, timeout)
    })
  },
  justWait: function(timeout){
    return new q.promise(function(resolve, reject){
      setTimeout(resolve, timeout)
    })
  }
}

Fix typo accessing q's promise constructor


function escapeCarriageReturn(txt) {
  txt = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
  while (txt.search(/\r/g) > -1) {
    let base = txt.match(/^.*\r+/m)[0].replace(/\r/, '');
    let insert = txt.match(/\r+.*$/m)[0].replace(/\r/, '');
    insert = insert + base.slice(insert.length, base.length);

    txt = txt.replace(/\r+.*$/m, '\r').replace(/^.*\r+/m, insert);
  }
  return txt;
}

module.exports = escapeCarriageReturn;

function escapeCarriageReturn(txt) {
  txt = txt.replace(/\r+\n/gm, '\n'); // \r followed by \n --> newline
  while (txt.search(/\r/g) > -1) {
    var base = txt.match(/^.*\r+/m)[0].replace(/\r/, '');
    var insert = txt.match(/\r+.*$/m)[0].replace(/\r/, '');
    insert = insert + base.slice(insert.length, base.length);

    txt = txt.replace(/\r+.*$/m, '\r').replace(/^.*\r+/m, insert);
  }
  return txt;
}

module.exports = escapeCarriageReturn;

Use var instead of let


'use strict';

module.exports = {
  name: require('./package').name,

  options: {
    autoImport: {
      webpack: {
        module: {
          rules: [
            /* fixes issue with graphql-js's mjs entry */
            /* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */
            {
              test: /\.mjs$/,
              include: /node_modules\/graphql/,
              type: 'javascript/auto',
            },
          ],
        },
        externals: {
          react: 'react',
        },
      },
    },
  },

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

    this.app = app;
  },

  getOptions() {
    const hostOptions =
      (this.parent && this.parent.options) ||
      (this.app && this.app.options) ||
      {};

    return (
      hostOptions.emberApolloClient || {
        keepGraphqlFileExtension: true,
      }
    );
  },

  setupPreprocessorRegistry(type, registry) {
    const options = this.getOptions();

    if (type === 'parent') {
      registry.add('js', {
        name: require('./package').name,
        ext: 'graphql',
        toTree(tree) {
          const GraphQLFilter = require('broccoli-graphql-filter');

          return new GraphQLFilter(tree, {
            keepExtension: options.keepGraphqlFileExtension,
          });
        },
      });
    }
  },
};

'use strict';

module.exports = {
  name: require('./package').name,

  options: {
    autoImport: {
      webpack: {
        module: {
          rules: [
            /* fixes issue with graphql-js's mjs entry */
            /* see: https://github.com/graphql/graphql-js/issues/1272#issuecomment-393903706 */
            {
              test: /\.mjs$/,
              include: /node_modules\/graphql/,
              type: 'javascript/auto',
            },
          ],
        },
      },
    },
  },

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

    this.app = app;
  },

  getOptions() {
    const hostOptions =
      (this.parent && this.parent.options) ||
      (this.app && this.app.options) ||
      {};

    return (
      hostOptions.emberApolloClient || {
        keepGraphqlFileExtension: true,
      }
    );
  },

  setupPreprocessorRegistry(type, registry) {
    const options = this.getOptions();

    if (type === 'parent') {
      registry.add('js', {
        name: require('./package').name,
        ext: 'graphql',
        toTree(tree) {
          const GraphQLFilter = require('broccoli-graphql-filter');

          return new GraphQLFilter(tree, {
            keepExtension: options.keepGraphqlFileExtension,
          });
        },
      });
    }
  },
};

Remove webpack configuration for externalising react


var path = require('path'),
    fs = require('fs');

function AssetManifestPlugin(output) {
  this.output = output;
}

AssetManifestPlugin.prototype.apply = function(compiler) {
  var assets = {},
      output  = this.output;

  var outputPath = compiler.options.output.path,
      publicPath = compiler.options.output.publicPath;

  function publicRelative(url) {
    return publicPath + url;
  }

  function keyForModule(module) {
    return Object.keys(module.assets)[0];
  }

  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('module-asset', function(module, file) {
      assets[keyForModule(module)] = publicRelative(file);
    });
  });

  compiler.plugin('done', function() {
    fs.writeFileSync(output, JSON.stringify(assets, null, 2));
  });
};

module.exports = AssetManifestPlugin;

var path = require('path'),
    fs = require('fs');

function AssetManifestPlugin(output, assetRoot) {
  this.output = output;
  this.assetRoot = assetRoot;
}

AssetManifestPlugin.prototype.apply = function(compiler) {
  var assets = {},
      output  = this.output,
      assetRoot = this.assetRoot;

  var publicPath = compiler.options.output.publicPath;

  function publicRelative(url) {
    return publicPath + url;
  }

  function removeAssetRoot(resource) {
    var replaceRoot = new RegExp("^" + assetRoot + "(\/)?");
    return resource.replace(replaceRoot, '');
  }

  function keyForModule(module) {
    return removeAssetRoot(module.resource);
  }

  compiler.plugin('compilation', function(compilation) {
    compilation.plugin('module-asset', function(module, file) {
      assets[keyForModule(module)] = publicRelative(file);
    });
  });

  compiler.plugin('done', function() {
    fs.writeFileSync(output, JSON.stringify(assets, null, 2));
  });
};

module.exports = AssetManifestPlugin;

Fix Asset Keys For Hashed Assets


let debug = require( 'debug' )( 'metalsmith-nested-collections' );
let collections = require( 'metalsmith-collections' );
let addCollectionLinks = require( './lib/helpers/addCollectionLinks' );

let plugin = function plugin( options ) {

    let oldWorker = collections( options );

    return function( files, metalsmith, done ) {
        setImmediate( done );

        let newWorker = function() {
            let metadata = metalsmith.metadata();
            addCollectionLinks( metadata );
        };

        oldWorker( files, metalsmith, newWorker );
    }
};

module.exports = plugin;

let debug = require( 'debug' )( 'metalsmith-nested-collections' );
let collections = require( 'metalsmith-collections' );
let addCollectionLinks = require( './lib/helpers/addCollectionLinks' );

let plugin = function plugin( options ) {

    /*
     * A Metalsmith plugin is basically a factory that returns a "worker"
     * function (for lack of a better term). Metalsmith calls the worker
     * function on its turn, and the worker modifies the files, metadata, etc.
     * These transformations happen in place and are available to the next
     * worker in the chain. Since this plugin is a drop-in replacement for
     * "metalsmith collections," we need to get the worker function from the
     * original plugin.
     */
    let oldWorker = collections( options );

    /*
     * This statement returns the default worker function for "nested
     * collections"
     */
    return function( files, metalsmith, done ) {
        /*
         * Set the next function to run once we are done
         */
        setImmediate( done );

        /*
         * Create a new worker function inside the default worker function.
         * We will pass this worker to the `oldWorker` function so that
         * `oldWorker` will call `newWorker` when `oldWorker` is done doing its
         * thing. The arguments to the default worker will be available to
         * `newWorker` and `oldWorker` thanks to the magic of closure.
         *
         * In fact, this magic will allow `oldWorker` to make changes to, e.g.,
         * the `files` argument. Then these changes will be available to
         * `newWorker` even though we are **NOT** passing any data between the
         * functions! See? Magic. <poof... disappears>
         */
        let newWorker = function() {
            let metadata = metalsmith.metadata();
            addCollectionLinks( metadata );
        };

        /*
         * Call the original worker function, and pass it the new worker. Oldie
         * will call this function when its done with its work.
         */
        oldWorker( files, metalsmith, newWorker );
    }
};

module.exports = plugin;

Add thorough comments explaining the organization and execution of the main file


/*!
 * word-wrap <https://github.com/jonschlinkert/word-wrap>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 *
 * Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
 * @attribution
 */

module.exports = function(str, options) {
  options = options || {};
  if (str == null) {
    return str;
  }

  var width = options.width || 50;
  var indent = (typeof options.indent === 'string')
    ? options.indent
    : '  ';

  var newline = options.newline || '\n' + indent;

  var escape = options.escape || function(str){return str;};

  var re = new RegExp('.{1,' + width + '}(\\s+|$)|\\S+?(\\s+|$)', 'g');

  if (options.cut) {
    re = new RegExp('.{1,' + width + '}', 'g');
  }

  var lines = str.match(re) || [];
  var res = indent + lines.map(function(str){return escape(str)}).join(newline);

  if (options.trim === true) {
    res = res.replace(/[ \t]*$/gm, '');
  }
  return res;
};

/*!
 * word-wrap <https://github.com/jonschlinkert/word-wrap>
 *
 * Copyright (c) 2014-2015, Jon Schlinkert.
 * Licensed under the MIT License.
 *
 * Adapted from http://james.padolsey.com/javascript/wordwrap-for-javascript/
 * @attribution
 */

module.exports = function(str, options) {
  options = options || {};
  if (str == null) {
    return str;
  }

  var width = options.width || 50;
  var indent = (typeof options.indent === 'string')
    ? options.indent
    : '  ';

  var newline = options.newline || '\n' + indent;

  function identity(str) {
    return str;
  };
  var escape = typeof options.escape === 'function'
    ? options.escape
    : identity;

  var re = new RegExp('.{1,' + width + '}(\\s+|$)|\\S+?(\\s+|$)', 'g');

  if (options.cut) {
    re = new RegExp('.{1,' + width + '}', 'g');
  }

  var lines = str.match(re) || [];
  var res = indent + lines.map(escape).join(newline);

  if (options.trim === true) {
    res = res.replace(/[ \t]*$/gm, '');
  }
  return res;
};

Make code for options.escape cleaner


var rimraf = require('rimraf')
var path = require('path');
var join = path.join;

function Plugin(paths, context) {
  // determine webpack root
  this.context = context || path.dirname(module.parent.filename);

  // allows for a single string entry
  if (typeof paths == 'string' || paths instanceof String){
    paths = [paths];
  }

  // store paths
  this.paths = paths;
}

Plugin.prototype.apply = function(compiler) {
  var self = this;

  // preform an rm -rf on each path
  self.paths.forEach(function(path){
    var path = join(self.context, path);
    rimraf.sync(path);
  });
}

module.exports = Plugin;

var rimraf = require('rimraf');
var path = require('path');
var resolve = path.resolve;

function Plugin(paths, context) {
  // determine webpack root
  this.context = context || path.dirname(module.parent.filename);

  // allows for a single string entry
  if (typeof paths == 'string' || paths instanceof String){
    paths = [paths];
  }

  // store paths
  this.paths = paths;
}

Plugin.prototype.apply = function(compiler) {
  var self = this;

  // preform an rm -rf on each path
  self.paths.forEach(function(path){
    path = resolve(self.context, path);
    rimraf.sync(path);
  });
};

module.exports = Plugin;

Resolve paths instead of joining


var flyd = require('flyd')

module.exports = function (stream$) {
  var executed = false
  return flyd.combine(function (s$, self) {
    if (!executed) {
      executed = true
      self(s$())
    }
  }, [stream$])
}

var flyd = require('flyd')

module.exports = function (stream$) {
  return flyd.combine(function (s$, self) {
    self(s$())
    self.end(true);
  }, [stream$])
}

Reimplement using the end stream


'use strict';
require('whatwg-fetch');

var path = require('path'),
    querystring = require('querystring').parse;

var registry = 'http://npm-registry-cors-proxy.herokuapp.com/';

var name = querystring(window.location.search.slice(1)).q;

window.fetch(path.join(registry, name))
  .then((response) => response.json())
  .then((info) => window.location = info.homepage);

'use strict';
require('whatwg-fetch');

const path = require('path'),
      querystring = require('querystring').parse;

const registry = 'http://npm-registry-cors-proxy.herokuapp.com/';

const query = querystring(window.location.search.slice(1)).q;

if (query) {
  window.fetch(path.join(registry, name))
    .then((response) => response.json())
    .then((info) => {
      document.write(`Redirecting to ${info.homepage}...`);
      window.location = info.homepage;
    });
}
else {
  document.write('<form method="get"><input type="text" name="q"><input type="submit" value="Go"></form>');
}

Put a form as a fallback


'use strict';

var fio = require('imacros-fio');
var vsprintf = require('format').vsprintf;
var formatDate = require('isolocaldateformat');

function FileTransport ( options ){
  options = options || {};

  // Transport must set groupsEnabled and groupsDisabled to provide transport
  // level support for overriding what groups to log
  // (NOTE - the user does not need to pass in groupsEnabled, but the
  // transport must set these properties)
  this.groupsEnabled = options.groupsEnabled;
  this.groupsDisabled = options.groupsDisabled;

  // Transport specific settings
  // ------------------------------
  this.logFileName = options.logFileName;
  this.spacing = options.spacing === undefined ? '\t' : options.spacing;

  return this;
}

FileTransport.prototype.name = 'FileTransport';
FileTransport.prototype.log = function FileTransportLog( loggedObject ){
  // Do something with loggedObject
  //window.console.log(loggedObject);
  var spacing = this.spacing;
  var time = formatDate(new Date(loggedObject.unixTimestamp * 1000));
  var group = loggedObject.group;
  var message = time + spacing + group;

  if (loggedObject.originalArgs.length > 0)
    message += spacing + vsprintf(loggedObject.message, loggedObject.originalArgs);
  else {
    message += spacing + loggedObject.message;
  }

  fio.append(this.logFileName, message + '\n');
  return this;
};

module.exports = FileTransport;

'use strict';

var fio = require('imacros-fio');
var vsprintf = require('format').vsprintf;
var formatDate = require('isolocaldateformat');

function FileTransport ( options ){
  options = options || {};

  // Transport must set groupsEnabled and groupsDisabled to provide transport
  // level support for overriding what groups to log
  // (NOTE - the user does not need to pass in groupsEnabled, but the
  // transport must set these properties)
  this.groupsEnabled = options.groupsEnabled;
  this.groupsDisabled = options.groupsDisabled;

  // Transport specific settings
  // ------------------------------
  this.logFileName = options.logFileName;
  this.delimiter = options.delimiter === undefined ? '\t' : options.delimiter;

  return this;
}

FileTransport.prototype.name = 'FileTransport';
FileTransport.prototype.log = function FileTransportLog( loggedObject ){
  // Do something with loggedObject
  //window.console.log(loggedObject);
  var delim = this.delimiter;
  var time = formatDate(new Date(loggedObject.unixTimestamp * 1000));
  var group = loggedObject.group;
  var message = time + delim + group;

  if (loggedObject.originalArgs.length > 0)
    message += delim + vsprintf(loggedObject.message, loggedObject.originalArgs);
  else {
    message += delim + loggedObject.message;
  }

  fio.append(this.logFileName, message + '\n');
  return this;
};

module.exports = FileTransport;

Replace spacing option with delimiter


var Factory = require('factory-girl'),
    Adapter = Factory.Adapter;

var SequelizeAdapter = function() {};
SequelizeAdapter.prototype = new Adapter();
SequelizeAdapter.prototype.create = function(Model, props) {
  return Model.build(props);
};
SequelizeAdapter.prototype.save = function(doc, Model, cb) {
  doc.save()
    .success(cb)
    .error(function(event) {
      var err = new Error('Failed to save fixture');
      err.event = event;
      cb(err);
    });
};
SequelizeAdapter.prototype.destroy = function(doc, Model, cb) {
  doc.destroy()
    .success(cb)
    .error(function(event) {
      var err = new Error('Failed to destroy fixture');
      err.event = event;
      cb(err);
    });
};

var adapter = new SequelizeAdapter();

module.exports = function(models) {
  if (models) {
    for (var i = 0; i < models.length; i++) {
      Factory.setAdapter(adapter, models[i]);
    }
  }
  else {
    Factory.setAdapter(adapter);
  }
};

var Factory = require('factory-girl'),
    Adapter = Factory.Adapter;

var SequelizeAdapter = function () {};
SequelizeAdapter.prototype = new Adapter();

SequelizeAdapter.prototype.build = function(Model, props) {
  return Model.build(props);
};

SequelizeAdapter.prototype.save = function(doc, Model, cb) {
  doc.save().complete(cb);
};

SequelizeAdapter.prototype.destroy = function(doc, Model, cb) {
  doc.destroy().complete(cb);
};

var adapter = new SequelizeAdapter();

module.exports = function(models) {
  if (models) {
    for (var i = 0; i < models.length; i++) {
      Factory.setAdapter(adapter, models[i]);
    }
  }
  else {
    Factory.setAdapter(adapter);
  }
};

Make it actually work, remove `create` method as it is not really used.


var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');

(function() {
  function readConfig(callback) {
    var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));

    if (doc.config !== undefined && doc.config.port !== undefined &&
      doc.config.path !== undefined && doc.config.secret !== undefined) {
        callback(undefined, doc.config);
    } else {
      callback("Malformed .deploy.yml.", undefined);
    }
  }

  readConfig(function(err, data) {
    if (err) {
      console.log(err);
    } else {
      var pot = new chimneypot({
        port: data.port,
        path: data.path,
        secret: data.secret
      });

      pot.route('push', function (event) {
        spawn('sh', ['pull.sh']);
      });

      pot.listen();
    }
  });
})();

var http = require('http');
var yaml = require('js-yaml');
var fs = require('fs');
var spawn = require('child_process').spawn;
var chimneypot = require('chimneypot');

(function() {
  function readConfig() {
    var doc = yaml.safeLoad(fs.readFileSync('.deploy.yml', 'utf8'));

    if (doc.config !== undefined && doc.config.port !== undefined &&
      doc.config.path !== undefined && doc.config.secret !== undefined) {
        return doc.config;
    }
  }

  readConfig(function(err, data) {
    if (err) {
      console.log(err);
    } else {
      var pot = new chimneypot({
        port: data.port,
        path: data.path,
        secret: data.secret
      });

      pot.route('push', function (event) {
        spawn('sh', ['pull.sh']);
      });

      pot.listen();
    }
  });
})();

Return the config, don't hit the callback


'use strict';

exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, 'Hello from Lambda');
};

'use strict';

const AWS = require('aws-sdk');
const codePipeline = new AWS.CodePipeline();

exports.handler = (event, context, callback) => {
    // TODO implement
    callback(null, 'Hello from Lambda');
};

Initialize AWS SDK and CodePipeline client.


'use strict';

var kmp = require('kmp-matcher').kmp;

module.exports = function (query) {
  if (!query.length) {
    return [];
  }

  var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
                                      document, null, XPathResult.ANY_TYPE, null);
  var result = [];
  var node;
  while (node = xpathResult.iterateNext()) {
    kmp(node.textContent, query)
      .forEach(function (start) {
        var range = document.createRange();
        range.setStart(node, start);
        range.setEnd(node, start + query.length);
        result.push(range);
      });
  }
  return result;
};

'use strict';

var kmp = require('kmp-matcher').kmp;

module.exports = function (query) {
  if (!query.length) {
    return [];
  }

  if (query.indexOf('"') >= 0) {
    throw new Error('Unimplemented: can\'t match "');
  }

  var xpathResult = document.evaluate('//text()[contains(.,"' + query + '")]',
                                      document, null, XPathResult.ANY_TYPE, null);
  var result = [];
  var node;
  while (node = xpathResult.iterateNext()) {
    kmp(node.textContent, query)
      .forEach(function (start) {
        var range = document.createRange();
        range.setStart(node, start);
        range.setEnd(node, start + query.length);
        result.push(range);
      });
  }
  return result;
};

Add error message for "


/**
 * Takes coordinates and properties (optional) and returns a new {@link Point} feature.
 *
 * @module turf/point
 * @category helper
 * @param {number[]} coordinates longitude, latitude position (each in decimal degrees)
 * @param {Object=} properties an Object that is used as the {@link Feature}'s
 * properties
 * @returns {Point} a Point feature
 * @example
 * var pt1 = turf.point([-75.343, 39.984]);
 *
 * //=pt1
 */
var isArray = Array.isArray || function(arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
};
module.exports = function(coordinates, properties) {
  if (!isArray(coordinates)) throw new Error('Coordinates must be an array');
  if (coordinates.length < 2) throw new Error('Coordinates must be at least 2 numbers long');
  return {
    type: "Feature",
    geometry: {
      type: "Point",
      coordinates: coordinates
    },
    properties: properties || {}
  };
};

/**
 * Takes coordinates and properties (optional) and returns a new {@link Point} feature.
 *
 * @module turf/point
 * @category helper
 * @param {Number[]} coordinates longitude, latitude position (each in decimal degrees)
 * @param {Object=} properties an Object that is used as the {@link Feature}'s
 * properties
 * @returns {Feature<Point>} a Point feature
 * @example
 * var pt1 = turf.point([-75.343, 39.984]);
 *
 * //=pt1
 */
var isArray = Array.isArray || function(arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
};
module.exports = function(coordinates, properties) {
  if (!isArray(coordinates)) throw new Error('Coordinates must be an array');
  if (coordinates.length < 2) throw new Error('Coordinates must be at least 2 numbers long');
  return {
    type: "Feature",
    geometry: {
      type: "Point",
      coordinates: coordinates
    },
    properties: properties || {}
  };
};

Switch doc to closure compiler templating


#!/usr/bin/env node

"use strict";

process.chdir(__dirname);

// Perform node version check before loading any other files or modules
// Doing this check as soon as possible allows us to avoid ES6 parser errors or other issues
var pkg = require("./package.json");
if (!require("semver").satisfies(process.version, pkg.engines.node)) {
	/* eslint-disable no-console */
	console.error("=== WARNING!");
	console.error("=== The oldest supported Node.js version is", pkg.engines.node);
	console.error("=== We strongly encourage you to upgrade, see https://nodejs.org/en/download/package-manager/ for more details\n");
	/* eslint-enable no-console */
}

require("./src/command-line");

#!/usr/bin/env node

"use strict";

process.chdir(__dirname);

// Perform node version check before loading any other files or modules
// Doing this check as soon as possible allows us to avoid ES6 parser errors or
// other issues
// Try to display warnings nicely, but gracefully degrade if anything goes wrong
var pkg = require("./package.json");
if (!require("semver").satisfies(process.version, pkg.engines.node)) {
	let colors;
	let log;

	try {
		colors = require("colors/safe");
	} catch (e) {
		colors = {};
		colors.green = colors.red = colors.bold = (x) => x;
	}

	try {
		log = require("./src/log");
	} catch (e) {
		log = {};
		log.warn = (msg) => console.error(`[WARN] ${msg}`); // eslint-disable-line no-console
	}

	log.warn(`The Lounge requires Node.js ${colors.green(pkg.engines.node)} (current version: ${colors.red(process.version)})`);
	log.warn(colors.bold("We strongly encourage you to upgrade Node.js"));
	log.warn("See https://nodejs.org/en/download/package-manager/ for more details");
}

require("./src/command-line");

Improve the Node version warning because why not


'use strict';

const $ = require('jquery'),
      remote = require('remote');

let main = remote.getCurrentWindow();

$(function(){
  $('.tools > div').on('click', function(e){
    main[e.target.className]();
  });
});

'use strict';

const $ = require('jquery'),
      remote = require('remote');

let main = remote.getCurrentWindow();

$(function(){
  $('.tools > div').on('click', (e) => main[e.target.className]());
});

Change window tools to 1 line arrow function.


const fs = require('fs-extra')
const path = require('path')

const logPath = path.join(__dirname, '../log/results.log')
fs.ensureFileSync(logPath)

module.exports = result =>
  new Promise((resolve, reject) => {
    fs.appendFile(logPath, `${JSON.stringify(result)}\n`, function(err) {
      if (err) return reject(err)
      resolve(result)
    })
  })

const fs = require('fs-extra')
const path = require('path')

const logPath = path.join(__dirname, '../log/results.log')
fs.ensureFileSync(logPath)

module.exports = result =>
  new Promise((resolve, reject) => {
    const resultWithTimestamp = Object.assign({}, result, { timestamp: Date.now() })
    fs.appendFile(logPath, `${JSON.stringify(resultWithTimestamp)}\n`, function(err) {
      if (err) return reject(err)
      resolve(result)
    })
  })

Add timestamp to log ⌚


'use strict';

angular.module('core').controller('SoundTestController', ['$scope', 'TrialData',
  function($scope, TrialData) {

    /* global io */
    var socket = io();

    socket.on('oscMessageSent', function(data) {
      console.log('socket "oscMessageSent" event received with data: ' + data);
    });

    socket.emit('sendOSCMessage', {
      oscType: 'message',
      address: '/eim/control/soundTest',
      args: [
        {
          type: 'integer',
          value: 1
        },
        {
          type: 'string',
          value: '' + TrialData.data.metadata.session_number
        }
      ]
    });

    $scope.stopSoundTest = function() {
      socket.emit('sendOSCMessage', {
        oscType: 'message',
        address: '/eim/control/soundTest',
        args: [
          {
            type: 'integer',
            value: 0
          },
          {
            type: 'string',
            value: '' + TrialData.data.metadata.session_number
          }
        ]
      });
    };

    // Send stop sound test message when controller is destroyed
    $scope.$on('$destroy', $scope.stopSoundTest);

    $scope.trialDataJson = function() {
      return TrialData.toJson();
    };
  }
]);

'use strict';

angular.module('core').controller('SoundTestController', ['$scope', 'TrialData',
  function($scope, TrialData) {

    /* global io */
    var socket = io();

    // Send a message to Max to start the sound test
    socket.emit('sendOSCMessage', {
      oscType: 'message',
      address: '/eim/control/soundTest',
      args: [
        {
          type: 'integer',
          value: 1
        },
        {
          type: 'string',
          value: '' + TrialData.data.metadata.session_number
        }
      ]
    });

    // Function to send a message to Max to stop the sound test
    $scope.stopSoundTest = function() {
      socket.emit('sendOSCMessage', {
        oscType: 'message',
        address: '/eim/control/soundTest',
        args: [
          {
            type: 'integer',
            value: 0
          },
          {
            type: 'string',
            value: '' + TrialData.data.metadata.session_number
          }
        ]
      });
    };

    // Send stop sound test message when controller is destroyed
    $scope.$on('$destroy', $scope.stopSoundTest);

    $scope.trialDataJson = function() {
      return TrialData.toJson();
    };
  }
]);

Remove extraneous OSC message listener in SoundTestController


var express = require('express')
var app = express()
var bodyParser = require('body-parser')
var jsonParser = bodyParser.json()

var bauhausui = require('./index.js')
var login = require('./example/api/login')
var jsondata = require('./example/api/jsondata')
var config = require('./example/config.json')

app.use('/json', jsondata())

app.use('/static', express.static('./example/static'))

app.use(bauhausui(config))

app.post('/api/login', jsonParser, login)

app.listen(5000)

var express = require('express')
var app = express()
var bodyParser = require('body-parser')
var jsonParser = bodyParser.json()
var proxy = require('http-proxy-middleware');

var bauhausui = require('./index.js')
var login = require('./example/api/login')
var jsondata = require('./example/api/jsondata')
var config = require('./example/config.json')

app.use('/json', jsondata())

app.use('/static', express.static('./example/static'))

app.use(bauhausui(config))

app.post('/api/login', jsonParser, login)

app.use(proxy('/', {
  target: 'http://localhost:3000',
  changeOrigin: false,
  ws: false,
}));

app.listen(5000)

Test proxy to strongloop for inputFiles Test


import React from "react"
import { shallow } from "enzyme"
import { expect } from "chai"

import CategoryColumn from "../../web/static/js/components/category_column"

describe("CategoryColumn", () => {
  it("is renders a list item for each idea in the ideas prop", () => {
    const ideas = [{
      body: ":confused: what happened to our CI server?"
    }, {
      body: ":sad: still no word on tests"
    }]

    const wrapper = shallow(<CategoryColumn ideas={ideas} />)
    expect(wrapper.find("li")).to.have.length(2)
  })
})

import React from "react"
import { shallow } from "enzyme"
import { expect } from "chai"

import CategoryColumn from "../../web/static/js/components/category_column"

describe("CategoryColumn", () => {
  it("is renders a list item for each idea in the ideas prop", () => {
    const ideas = [{
      body: ":confused: what happened to our CI server?"
    }, {
      body: ":sad: still no word on tests"
    }]

    const wrapper = shallow(<CategoryColumn ideas={ideas} category="happy"/>)
    expect(wrapper.find("li")).to.have.length(2)
  })
})

Add required prop in CategoryColumn test


$(function () {
    function restore() {
        $(".ghs-highlight").removeClass("ghs-highlight");
        $(".ghs-partial-highlight").contents().unwrap();
    }

    $("body").mouseup(function (e) {
        restore();

        var selection = $.trim(window.getSelection());
        if (selection) {
            var codeArea = $(".file-box");
            codeArea.find("span:not(:has(*))").each(function () {
                if (this != e.target) {
                    if ($(this).text() == selection) {
                        $(this).addClass("ghs-highlight");
                    }
                    else if ($(this).text().indexOf(selection) > -1) {
                        $(this).html(function(_, html) {
                           return html.replace(selection, '' + selection + '');
                        });
                    }
                }
            });
        }
    });
});

$(function () {
    function restore() {
        $(".ghs-highlight").removeClass("ghs-highlight");
        $(".ghs-partial-highlight").contents().unwrap();
    }

    $("body").mouseup(function (e) {
        restore();

        var selection = $.trim(window.getSelection());
        if (selection) {
            var codeArea = $(".js-file-line-container");
            codeArea.find("span:not(:has(*))").each(function () {
                if (this != e.target) {
                    if ($(this).text() == selection) {
                        $(this).addClass("ghs-highlight");
                    }
                    else if ($(this).text().indexOf(selection) > -1) {
                        $(this).html(function(_, html) {
                           return html.replace(selection, '' + selection + '');
                        });
                    }
                }
            });
        }
    });
});

Fix select outside code area.


function lightswitch()
{
    id = this.id.replace("light_", "");
    $.post("/lightswitch", { id: id });
};

$(document).ready(function () {
    $(".toggle").each(function(index) {
        obj = $(".toggle")[index];
        document.querySelector('#' + obj.id).addEventListener('toggle', lightswitch, obj.id);
    });
});

function lightswitch()
{
    id = this.id.replace("light_", "");
    $.post("/lightswitch", { id: id })
        .fail(location.reload());
};

$(document).ready(function () {
    $(".toggle").each(function(index) {
        obj = $(".toggle")[index];
        document.querySelector('#' + obj.id).addEventListener('toggle', lightswitch, obj.id);
    });
});

Handle failure to toggle light


import deepAssign from 'deep-assign';

export default function defaultconfig(config) {
  return function factory(...configs) {
    return deepAssign(config, ...configs);
  };
}

import deepAssign from 'deep-assign';

export default function defaultconfig(_config) {
  const config = JSON.parse(JSON.stringify(_config));
  return function factory(...configs) {
    return deepAssign(config, ...configs);
  };
}

Make a deep clone before modifying the object


function Store(options) {
  var Adapter = require('./db/' + options.adapter);
  this.adapter = new Adapter(options[options.adapter]);
}

// Methods that should be supported by adaptors.
var methods = [
  'connect',
  'disconnect',
  'setBin',
  'setBinOwner',
  'setBinPanel',
  'getBin',
  'getLatestBin',
  'getLatestBinForUser',
  'getBinsByUser',
  'generateBinId',
  'getUser',
  'getUserByEmail',
  'setUser',
  'touchLogin',
  'touchOwners',
  'updateOwners',
  'updateUserEmail',
  'updateUserKey',
  'upgradeUserKey',
  'getUserByForgotToken',
  'setForgotToken',
  'expireForgotToken',
  'expireForgotTokenByUser',
  'reportBin',
  'getAllOwners',
  'getOwnersBlock',

  'populateOwners'
];

// Proxy the methods through the store.
methods.forEach(function (method) {
  Store.prototype[method] = function () {
    this.adapter[method].apply(this.adapter, arguments);
  };
});

module.exports = function createStore(options) {
  return new Store(options);
};
module.exports.Store = Store;

function Store(options) {
  var Adapter = require('./db/' + options.adapter);
  this.adapter = new Adapter(options[options.adapter]);
  check(this.adapter, methods);
}

var check = function (adapter, methods) {
  methods.forEach(function (method) {
    if (!adapter[method]) throw new Error("DB adapter missing method: " + method);
  });
};

// Methods that should be supported by adaptors.
var methods = [
  'connect',
  'disconnect',
  'setBin',
  'setBinOwner',
  'setBinPanel',
  'getBin',
  'getLatestBin',
  'getLatestBinForUser',
  'getBinsByUser',
  'generateBinId',
  'getUser',
  'getUserByEmail',
  'setUser',
  'touchLogin',
  'touchOwners',
  'updateOwners',
  'updateUserEmail',
  'updateUserKey',
  'upgradeUserKey',
  'getUserByForgotToken',
  'setForgotToken',
  'expireForgotToken',
  'expireForgotTokenByUser',
  'reportBin',
  'getAllOwners',
  'getOwnersBlock',

  'populateOwners'
];

// Proxy the methods through the store.
methods.forEach(function (method) {
  Store.prototype[method] = function () {
    this.adapter[method].apply(this.adapter, arguments);
  };
});

module.exports = function createStore(options) {
  return new Store(options);
};
module.exports.Store = Store;

Check DB adapter before allowing it to be used.


'use strict';

const chalk = require('chalk');
const { version } = require('../package.json');

// Prints version of preact-init
module.exports.showVersion = () => {
  console.log(`v${version}`);
  process.exit(0);
};

// Prints helpful information about preact-init
module.exports.showHelp = () => {
  const command = chalk.green('preact-init');
  const firstArg = chalk.yellow('<project-name>');
  const secondArg = chalk.yellow('<template-repo>');
  const options = chalk.yellow('[options]');
  console.log(
`\npreact-init v${version}
-------------------------------------

Usage: ${command} ${firstArg} ${secondArg} ${options}`
  );
  process.exit(0);
};

'use strict';

const chalk = require('chalk');
const validatePackageName = require('validate-npm-package-name');

/**
 * Cleans the terminal
 * ------------------------------------------------- */
module.exports.clearConsole = () => {
	process.stdout.write(
		process.platform === 'win32' ? '\x1Bc' : '\x1B[2J\x1B[3J\x1B[H'
  );
};

/**
 * Ends a promise, used on catch errors
 * ------------------------------------------------- */
module.exports.endWithError = (err) => {
  console.log(`${chalk.red('>>')} ${err.message || err}`);
  process.exit(1);
};

/**
 * Validates the project's name
 * ------------------------------------------------- */
module.exports.isValidAppName = (name) => {
	const its = validatePackageName(name);
	if (!its.validForNewPackages) {
		const errors = (its.errors || []).concat(its.warnings || []);
		return `Sorry, ${errors.join(' and ')} .`;
	}
	return true;
};

Create a file for common methods


var mode = 0; //primary

function calc_mode() {
	var modes = ["primary", "secondary", "tertiary"];
	return modes[mode];
}

$(function() {
	$(".add").button();
	$(".edit").button();
	$(".delete").button().click(function() {
		var res = confirm("Are you sure you want to delete this item?");
		if (res)
			window.location.href=$(this).attr('href');
		else
			return false;
	});
	$(".view").button();
	$(".submit").button();

	$("#ingredients_table table").tablesorter();
	$("#effects_table table").tablesorter();

	$("#calc_ingredients tbody").find('tr').each(function(){
		$(this).click(function(){
			$('#'+calc_mode()).html($(this).text());
		});
	});

	$("#primary").click(function(){
		$(this).text('--');
		mode = 0;
	});

	$("#secondary").click(function(){
		$(this).text('--');
		mode = 1;
	});

	$("#tertiary").click(function(){
		$(this).text('--');
		mode = 2;
	});
});

var mode = 0; //primary

function calc_mode() {
	var modes = ["primary", "secondary", "tertiary"];
	return modes[mode];
}

function send_data() {
	$.ajax({
		url: "calculate/"+primary+"/"+secondary+"/"+tertiary,
		context: document.body,
		type: "post",
		beforeSend :function() {
			//loading
		}
	}).done(function(data) {

	});
}

$(function() {
	$(".add").button();
	$(".edit").button();
	$(".delete").button().click(function() {
		var res = confirm("Are you sure you want to delete this item?");
		if (res)
			window.location.href=$(this).attr('href');
		else
			return false;
	});
	$(".view").button();
	$(".submit").button();

	$("#ingredients_table table").tablesorter();
	$("#effects_table table").tablesorter();

	$("#calc_ingredients tbody").find('tr').each(function(){
		$(this).click(function(){
			$('#'+calc_mode()).html($(this).text());
			send_data();
		});
	});

	$("#primary").click(function(){
		$(this).text('--');
		mode = 0;
	});

	$("#secondary").click(function(){
		$(this).text('--');
		mode = 1;
	});

	$("#tertiary").click(function(){
		$(this).text('--');
		mode = 2;
	});
});

Add send data ajax function


var Block = {
Test: function(d) {
		d.drawImage(document.getElementById("image"),0,0,20,20);
},
TestB: function(d) {
	d.fillStyle("#00FF00").fillRect(0, 0, 20, 20);
},
TestA: function(d) {
	d.fillStyle("#FF0000").fillRect(0, 0, 20, 20);
}
}

var Block = {
Test: function(d) {
	d.drawImage(document.getElementById("image"),0,0,20,20);
},
Empty: function(d) {
},
TestB: function(d) {
	d.fillStyle("#00FF00").fillRect(0, 0, 20, 20);
},
TestA: function(d) {
	d.fillStyle("#FF0000").fillRect(0, 0, 20, 20);
}
}

Add Empty and made Everything in test Empty


export const ENVIRONMENTS = {
  DEVELOPMENT: 'DEVELOPMENT',
  ACCEPTATION: 'ACCEPTATION',
  PRE_PRODUCTION: 'PRE_PRODUCTION',
  PRODUCTION: 'PRODUCTION'
};

export const HOSTS = {
  PRODUCTION: 'data.amsterdam.nl',
  PRE_PRODUCTION: 'pre.data.amsterdam.nl',
  ACCEPTATION: 'acc.data.amsterdam.nl',
  DEVELOPMENT: 'localhost'
};

// deprecated
export const getEnvironment = (host) => {
  switch (host) {
    case 'data.amsterdam.nl':
      return ENVIRONMENTS.PRODUCTION;
    case 'pre.data.amsterdam.nl':
      return ENVIRONMENTS.PRE_PRODUCTION;
    case 'acc.data.amsterdam.nl':
      return ENVIRONMENTS.ACCEPTATION;
    default:
      return ENVIRONMENTS.DEVELOPMENT;
  }
};

const ENVIRONMENT = (process.env.NODE_ENV).toUpperCase();

export const getEnv = () => ENVIRONMENT;

export default ENVIRONMENT;

export const ENVIRONMENTS = {
  DEVELOPMENT: 'DEVELOPMENT',
  ACCEPTATION: 'ACCEPTATION',
  PRE_PRODUCTION: 'PRE_PRODUCTION',
  PRODUCTION: 'PRODUCTION'
};

export const HOSTS = {
  PRODUCTION: 'data.amsterdam.nl',
  PRE_PRODUCTION: 'pre.data.amsterdam.nl',
  ACCEPTATION: 'acc.data.amsterdam.nl',
  DEVELOPMENT: 'localhost'
};

// DEPRECATED: used by modules/shared/services/eviroment/environment.factory.js
// NODE_ENV doesn't differentiate between pre-production and production
export const getEnvironment = (host) => {
  switch (host) {
    case 'data.amsterdam.nl':
      return ENVIRONMENTS.PRODUCTION;
    case 'pre.data.amsterdam.nl':
      return ENVIRONMENTS.PRE_PRODUCTION;
    case 'acc.data.amsterdam.nl':
      return ENVIRONMENTS.ACCEPTATION;
    default:
      return ENVIRONMENTS.DEVELOPMENT;
  }
};

const ENVIRONMENT = (process.env.NODE_ENV).toUpperCase();

export const getEnv = () => ENVIRONMENT;

export default ENVIRONMENT;

Add description in deprecated function


$('video').each( function() {
    var video = this;
    var nodes = [];
    var time = 0;
      $('.videosync').not('video').each(function(){
          var $this = $(this);
          $this.hide();
          nodes.push({
              start: this.getAttribute('data-videosync-start'),
              end: this.getAttribute('data-videosync-end'),
              element: $this,
          });
      });
    video.addEventListener('timeupdate',function(){
        time = parseInt(video.currentTime);
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i];
            if (time >= node.start) {
                node.element.show();
            }
        }
    }, false);
});

$('video').each( function() {
    var video = this;
    var nodes = [];
    var time = 0;
      $('.videosync').not('video').each(function(){
          var $this = $(this);
          $this.hide();
          nodes.push({
              start: this.getAttribute('data-videosync-start'),
              end: this.getAttribute('data-videosync-end'),
              element: $this,
          });
      });
    video.addEventListener('timeupdate',function(){
        time = parseInt(video.currentTime);
        for (var i = 0; i < nodes.length; i++) {
            var node = nodes[i];
            if ((time >= node.start) && (node.end ? time < node.end : true)) {
                node.element.show();
            } else if (((time < node.start) || (node.end ? time >= node.end : false))) {
                node.element.hide();
            }
        }
    }, false);
});

Add and track video-end time


module.exports = {
    recursive: true,
    reporter: 'spec',
    slow: 0,
    timeout: 50000,
    ui: 'bdd',
    extension: 'js',
};

module.exports = {
    recursive: true,
    reporter: 'spec',
    slow: 0,
    timeout: 60000,
    ui: 'bdd',
    extension: 'js',
};

Increase mocha timeout to 60000s


'use strict';
var chalk = require( 'chalk' );
var table = require( 'text-table' );

/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function( errorsCollection ) {
  var errorCount = 0;
  /**
   * Formatting every error set.
   */
  var report = errorsCollection.map( function( errors ) {
    if ( ! errors.isEmpty() ) {
      errorCount += errors.getErrorCount();

      var output = errors.getErrorList().map( function( error ) {
        return [
          '',
          chalk.gray( error.line ),
          chalk.gray( error.column ),
          chalk.blue( error.message )
        ];
      } );

      return [
        '',
        chalk.underline( errors.getFilename() ),
        table( output ),
        ''
      ].join('\n');
    }
    return '';
  });

  if ( errorCount ) {
    // Output results
    console.log( report.join('') );
  } else {
    console.log( 'No code style errors found.' );
  }
};

// Expose path to reporter so it can be configured in e.g. grunt-jscs-checker
module.exports.path = __dirname;

'use strict';
var chalk = require( 'chalk' );
var table = require( 'text-table' );

/**
 * @param {Errors[]} errorsCollection
 */
module.exports = function( errorsCollection ) {
  var errorCount = 0;
  /**
   * Formatting every error set.
   */
  var report = errorsCollection.map( function( errors ) {
    if ( ! errors.isEmpty() ) {
      errorCount += errors.getErrorCount();

      var output = errors.getErrorList().map( function( error ) {
        return [
          '',
          chalk.gray( error.line ),
          chalk.gray( error.column ),
          process.platform !== 'win32' ? chalk.blue( error.message ) : chalk.cyan( error.message )
        ];
      } );

      return [
        '',
        chalk.underline( errors.getFilename() ),
        table( output ),
        ''
      ].join('\n');
    }
    return '';
  });

  if ( errorCount ) {
    // Output results
    console.log( report.join('') );
  } else {
    console.log( 'No code style errors found.' );
  }
};

// Expose path to reporter so it can be configured in e.g. grunt-jscs-checker
module.exports.path = __dirname;

Improve error message legibility on windows


"use strict";
var path = require('path');
var HOME = process.env.HOME || process.env.HOMEPATH;
var APP_ENV = process.env.APP_ENV || 'dev';
var config  = require('../config/config')[APP_ENV];

var knex = require('knex')(config.database);

knex.schema.hasTable('users')
  .then(function(exists) {
    if (!exists) {
      return knex.schema.createTable('users', function(t) {
        t.bigIncrements('id').primary();
        t.string('email', 100).index('users_email_idx');
        t.string('password', 255);
        t.dateTime('created_at').defaultTo(knex.raw('now()'));
        t.dateTime('updated_at').defaultTo(knex.raw('now()'));
      });
    } else {
      console.log('users table already exists.');
    }
  }).then(function() {
    return knex.schema.hasTable('tokens').then(function (exists) {
      if (!exists) {
        return knex.schema.createTable('tokens', function (t) {
          t.bigIncrements('id').primary();
          t.biginteger('user_id').references('id').inTable('users');
          t.string('token', 255).index('tokens_token_idx');
          t.dateTime('expiry');
          t.dateTime('created_at').defaultTo(knex.raw('now()'));
          t.dateTime('updated_at').defaultTo(knex.raw('now()'));
        });
      } else {
        console.log('tokens table already exists.');
      }
    });
  }).then(function() {
    process.exit(1);
  });

"use strict";
var config  = require('../config/config');
var knex = require('knex')(config.database);

knex.schema.hasTable('users')
  .then(function(exists) {
    if (!exists) {
      return knex.schema.createTable('users', function(t) {
        t.bigIncrements('id').primary();
        t.string('email', 100).index('users_email_idx');
        t.string('password', 255);
        t.dateTime('created_at').defaultTo(knex.raw('now()'));
        t.dateTime('updated_at').defaultTo(knex.raw('now()'));
      });
    } else {
      console.log('users table already exists.');
    }
  }).then(function() {
    return knex.schema.hasTable('tokens').then(function (exists) {
      if (!exists) {
        return knex.schema.createTable('tokens', function (t) {
          t.bigIncrements('id').primary();
          t.biginteger('user_id').references('id').inTable('users');
          t.string('token', 255).index('tokens_token_idx');
          t.dateTime('expiry');
          t.dateTime('created_at').defaultTo(knex.raw('now()'));
          t.dateTime('updated_at').defaultTo(knex.raw('now()'));
        });
      } else {
        console.log('tokens table already exists.');
      }
    });
  }).then(function() {
    process.exit(1);
  });

Update migration file to use the new config file


import buble from 'rollup-plugin-buble';
import uglify from 'rollup-plugin-uglify';

const config = {
  entry: 'src/index.js',
  plugins: [buble()],
  sourceMap: true,
};

if (process.env.TARGET === 'commonjs') {
  config.dest = 'lib/index.js';
  config.format = 'cjs';
}

if (process.env.TARGET === 'es') {
  config.dest = 'es/index.js';
  config.format = 'es';
}

if (process.env.TARGET === 'umd') {
  config.moduleName = 'lightyPluginLegacy';
  config.dest = process.env.NODE_ENV === 'production'
    ? 'dist/lighty-plugin-legacy.min.js'
    : 'dist/lighty-plugin-legacy.js';
  config.format = 'umd';

  if (process.env.NODE_ENV === 'production') {
    config.plugins.push(uglify());
  }
}

export default config;

import buble from 'rollup-plugin-buble';
import uglify from 'rollup-plugin-uglify';

const config = {
  entry: 'src/index.js',
  plugins: [buble()],
  sourceMap: true,
};

if (process.env.TARGET === 'commonjs') {
  config.dest = 'lib/index.js';
  config.format = 'cjs';
}

if (process.env.TARGET === 'es') {
  config.dest = 'es/index.js';
  config.format = 'es';
}

if (process.env.TARGET === 'umd') {
  config.moduleName = 'lightyPluginLegacy';
  config.dest = process.env.NODE_ENV === 'production'
    ? 'dist/lighty-plugin-legacy.min.js'
    : 'dist/lighty-plugin-legacy.js';
  config.format = 'umd';
  config.globals = {
    jquery: 'jQuery',
  };

  if (process.env.NODE_ENV === 'production') {
    config.plugins.push(uglify());
  }
}

export default config;

Add global `jquery` dependency for build UMD module


var icons = {%s};

Object.defineProperty(icons, "get", {
  enumerate: false,
  value: function(targetName) {
    if (icons[targetName]) {
      return icons[targetName];
    } else {
      var normalizedName = targetName.toLowerCase();
      for (var iconName in icons) {
        var icon = icons[iconName];
        if ((icon.title && icon.title.toLowerCase() === normalizedName)
         || (icon.slug && icon.slug === normalizedName)) {
           return icon;
        }
      }
    }
  }
});

module.exports = icons;

var icons = {%s};

Object.defineProperty(icons, "get", {
  enumerable: false,
  value: function(targetName) {
    if (icons[targetName]) {
      return icons[targetName];
    } else {
      var normalizedName = targetName.toLowerCase();
      for (var iconName in icons) {
        var icon = icons[iconName];
        if ((icon.title && icon.title.toLowerCase() === normalizedName)
         || (icon.slug && icon.slug === normalizedName)) {
           return icon;
        }
      }
    }
  }
});

module.exports = icons;

Fix name of "enumerable" property in Object.defineProperty


(function ($) {

var FIELDS = {
    'centerpage': 'referenced_cp',
    'channel': 'query',
    'topicpage': 'referenced_topicpage',
    'query': 'raw_query'
};

var show_matching_field = function(container, current_type) {
    $(['referenced_cp', 'query', 'referenced_topicpage', 'raw_query']).each(
        function(i, field) {
            var method = field == FIELDS[current_type] ? 'show' : 'hide';
            var target = $('.fieldname-' + field, container).closest('fieldset');
            target[method]();
    });
};

$(document).bind('fragment-ready', function(event) {
    var type_select = $('.fieldname-automatic_type select', event.__target);
    if (! type_select.length) {
        return;
    }
    show_matching_field(event.__target, type_select.val());
    type_select.on(
        'change', function() {
            show_matching_field(event.__target, $(this).val());
    });
});

}(jQuery));

(function ($) {

var FIELDS = {
    'centerpage': 'referenced_cp',
    'channel': 'query',
    'topicpage': 'referenced_topicpage',
    'query': 'raw_query',
    'elasticsearch-query': 'elasticsearch_raw_query',
};

var show_matching_field = function(container, current_type) {
    $(Object.keys(FIELDS)).each(
        function(i, key) {
            var field = FIELDS[key];
            var method = field == FIELDS[current_type] ? 'show' : 'hide';
            var target = $('.fieldname-' + field, container).closest('fieldset');
            target[method]();
    });
};

$(document).bind('fragment-ready', function(event) {
    var type_select = $('.fieldname-automatic_type select', event.__target);
    if (! type_select.length) {
        return;
    }
    show_matching_field(event.__target, type_select.val());
    type_select.on(
        'change', function() {
            show_matching_field(event.__target, $(this).val());
    });
});

}(jQuery));

Hide elasticsearch fields of elasticsearch is not selected as query type.


var File = require('vinyl');
var ansiHTML = require('ansi-html');

var template = '';

/**
 * Given an error, generate an HTML page that represents the error.
 * @param {Error} error parse or generation error
 * @returns {Object} vinyl file object
 */
function errorPage(error) {
  var errorText = error.toString();
  if (error.codeFrame) {
    errorText += '
' + ansiHTML(error.codeFrame) + '
';
  }
  return new File({
    path: 'index.html',
    contents: new Buffer(template + errorText)
  });
}

module.exports = errorPage;

var File = require('vinyl');
var ansiHTML = require('ansi-html');

var template = '';

ansiHTML.setColors({
  reset: ['fff', '800'],
  black: 'aaa', // String
  red: '9ff',
  green: 'f9f',
  yellow: '99f',
  blue: 'ff9',
  magenta: 'f99',
  cyan: '9f9',
  lightgrey: 'ccc',
  darkgrey: 'aaa'
});

/**
 * Given an error, generate an HTML page that represents the error.
 * @param {Error} error parse or generation error
 * @returns {Object} vinyl file object
 */
function errorPage(error) {
  var errorText = error.toString();
  if (error.codeFrame) {
    errorText += '
' + ansiHTML(error.codeFrame) + '
';
  }
  return new File({
    path: 'index.html',
    contents: new Buffer(template + errorText)
  });
}

module.exports = errorPage;

Use setColor to produce more readable colors


;

import angular from 'angular';

function genComponentConf() {
    let template = `

What is your need?

    `;

    class Controller {
        constructor() {
            //this.testVar = 42;
        }
        back() { window.history.back() }
    }

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        template: template,
        bindToController: true, //scope-bindings -> ctrl
        scope: { }
    }
}

export default angular.module('won.owner.components.createNeedTitleBar', [])
    .directive('wonCreateNeedTitleBar', genComponentConf)
    .name;

;

import angular from 'angular';

function genComponentConf() {
    let template = `

Hey, everyone!

    `;

    class Controller {
        constructor() {
            //this.testVar = 42;
        }
        back() { window.history.back() }
    }

    return {
        restrict: 'E',
        controller: Controller,
        controllerAs: 'self',
        template: template,
        bindToController: true, //scope-bindings -> ctrl
        scope: { }
    }
}

export default angular.module('won.owner.components.createNeedTitleBar', [])
    .directive('wonCreateNeedTitleBar', genComponentConf)
    .name;

Change the create need title


var fs = require('fs');
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString());

exports.VERSION = pkg.version;

exports.DEFAULT_PORT = 8080;
exports.DEFAULT_RUNNER_PORT = 1337;

// log levels
exports.LOG_DISABLE = -1;
exports.LOG_ERROR   =  1;
exports.LOG_WARN    =  2;
exports.LOG_INFO    =  3;
exports.LOG_DEBUG   =  4;

exports.EXIT_CODE_0 = '\037EXIT0';

var fs = require('fs');
var pkg = JSON.parse(fs.readFileSync(__dirname + '/../package.json').toString());

exports.VERSION = pkg.version;

exports.DEFAULT_PORT = 8080;
exports.DEFAULT_RUNNER_PORT = 9100;

// log levels
exports.LOG_DISABLE = -1;
exports.LOG_ERROR   =  1;
exports.LOG_WARN    =  2;
exports.LOG_INFO    =  3;
exports.LOG_DEBUG   =  4;

exports.EXIT_CODE_0 = '\037EXIT0';

Change default runner port to 9100 (travis uses 1337)


/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'fi',
    dictionary: {},
    format: {
        days: [
            'Sunnuntai', 'Maanantai', 'Tiistai', 'Keskiviikko',
            'Torstai', 'Perjantai', 'Lauantai'
        ],
        shortDays: ['Su', 'Ma', 'Ti', 'Ke', 'To', 'Pe', 'Su'],
        months: [
            'Tammikuu', 'Helmikuu', 'Maaliskuu', 'Huhtikuu', 'Toukokuu', 'Kesäkuu',
            'Heinäkuu', 'Elokuu', 'Syyskuu', 'Lokakuu', 'Marraskuu', 'Joulukuu'
        ],
        shortMonths: [
            'Tammi', 'Helmi', 'Maalis', 'Huhti', 'Touko', 'Kesä',
            'Heinä', 'Elo', 'Syys', 'Loka', 'Marras', 'Joulu'
        ],
        date: '%d.%m.%Y'
    }
};

/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

'use strict';

module.exports = {
    moduleType: 'locale',
    name: 'fi',
    dictionary: {},
    format: {
        days: [
            'sunnuntai', 'maanantai', 'tiistai', 'keskiviikko',
            'torstai', 'perjantai', 'lauantai'
        ],
        shortDays: ['su', 'ma', 'ti', 'ke', 'to', 'pe', 'la'],
        months: [
            'tammikuu', 'helmikuu', 'maaliskuu', 'huhtikuu', 'toukokuu', 'kesäkuu',
            'heinäkuu', 'elokuu', 'syyskuu', 'lokakuu', 'marraskuu', 'joulukuu'
        ],
        shortMonths: [
            'tammi', 'helmi', 'maalis', 'huhti', 'touko', 'kesä',
            'heinä', 'elo', 'syys', 'loka', 'marras', 'joulu'
        ],
        date: '%d.%m.%Y'
    }
};

Make corrections to Finnish locale translations


var p = require('path');
var cp = require('child_process');

var fileExec = p.resolve(__dirname + '/../bin/file');
var fileFlags = ['--magic-file', p.resolve(__dirname + '/../share/magic.mgc'), '--brief', '--mime-type'];

var fileWrapper = function (path, cb) {
	var flags = JSON.parse(JSON.stringify(fileFlags));
	flags.push(path);
	cp.execFile(fileExec, flags, function (err, stdout) {
		stdout = stdout.trim();
		if (err) {
			if (stdout) {
				err.message = stdout;
			}
			cb(err);
		} else {
			cb(null, stdout);
		}
	});
};
exports.fileWrapper = fileWrapper;

var p = require('path');
var cp = require('child_process');

var fileExec = p.resolve(__dirname + '/../bin/file');
var fileFlags = ['--magic-file', p.resolve(__dirname + '/../share/magic.mgc'), '--brief', '--mime-type'];

var fileWrapper = function (path, cb) {
	cp.execFile(fileExec, fileFlags.concat(Array.isArray(path) ? path : [path]), function (err, stdout) {
		stdout = stdout.trim();
		if (err) {
			if (stdout)
				err.message = stdout;
			cb(err);
		} else
			cb(null, Array.isArray(path) ? stdout.split('\n') : stdout);
	});
};
exports.fileWrapper = fileWrapper;

Support arrays of paths, with the callback getting an array of mime-types.


// @flow

import {version} from '../package.json'
import {Platform} from 'react-native'

const aaoVersion = version || 'unknown'
const platformString = Platform.OS == 'ios' ? 'iOS' : 'Android' || 'unknown'
const platformVersion = Platform.Version || 'unknown'

export const AAO_USER_AGENT = `AllAboutOlaf/${aaoVersion} (${platformString}/${platformVersion})`

// @flow

import {version} from '../package.json'
import {Platform} from 'react-native'

const aaoVersion = version || 'unknown'
const platformString =
  Platform.OS == 'ios'
    ? 'iOS'
    : Platform.OS == 'android' ? 'Android' : 'unknown'
const platformVersion = Platform.Version || 'unknown'

export const AAO_USER_AGENT = `AllAboutOlaf/${aaoVersion} (${platformString}/${platformVersion})`

Fix ternary logic to actually allow for "unknown" platforms


/*
 * Extends L.Marker to include two extra methods: clusterHide and clusterShow.
 *
 * They work as setOpacity(0) and setOpacity(1) respectively, but
 * they will remember the marker's opacity when hiding and showing it again.
 *
 */

L.Marker.include({

  clusterHide: function(){
    this.options.opacityWhenUnclustered = this.options.opacity || 1;
    return this.setOpacity(0);
  },

  clusterShow: function(){
    var ret = this.setOpacity(this.options.opacity || this.options.opacityWhenUnclustered);
    delete this.options.opacityWhenUnclustered;
    return ret;
  }

});

/*
* Extends L.Marker to include two extra methods: clusterHide and clusterShow.
*
* They work as setOpacity(0) and setOpacity(1) respectively, but
* they will remember the marker's opacity when hiding and showing it again.
*
*/

L.Marker.include({

	clusterHide: function () {
		this.options.opacityWhenUnclustered = this.options.opacity || 1;
		return this.setOpacity(0);
	},

	clusterShow: function () {
		var ret = this.setOpacity(this.options.opacity || this.options.opacityWhenUnclustered);
		delete this.options.opacityWhenUnclustered;
		return ret;
	}

});

Fix indentation to make Jake and TravisCI happy.


/**
 * Created with JetBrains WebStorm.
 * User: vincent.peybernes
 * Date: 25/06/13
 * Time: 16:31
 * To change this template use File | Settings | File Templates.
 */

// Get the stream input node console
var stdin = process.stdin;

// Flush the stream input buffer
stdin.resume();

// Set encoding for the input stream to UTF8
stdin.setEncoding('UTF-8');

// Listen the new command pass through console on the enter pressed key
stdin.on('data', function(key){

    // Parse the command line
    parseCommand(key);
});

var parseCommand = function(key){

    // Remove the carryage return character
    key.replace("\n", "");

    // Split the command line to get the command key and the arguments
    var split = key.split(" ");

    // Get the command key and remove it from the split array. So the split array are the arguments
    var command = split.shift();
}

/**
 * Created with JetBrains WebStorm.
 * User: vincent.peybernes
 * Date: 25/06/13
 * Time: 16:31
 * To change this template use File | Settings | File Templates.
 */
var EventEmitter = require('events').EventEmitter;
var emitter = new EventEmitter();

// Get the stream input node console
var stdin = process.stdin;

// Flush the stream input buffer
stdin.resume();

// Set encoding for the input stream to UTF8
stdin.setEncoding('UTF-8');

// Listen the new command pass through console on the enter pressed key
stdin.on('data', function(key){

    // Parse the command line
    var params = parseCommand(key);

    // Process the command
    processCommand(params);
});

var parseCommand = function(key){

    // Remove the carryage return character
    key = key.replace("\n", "");

    // Split the command line to get the command key and the arguments
    var split = key.split(" ");

    return split;
}

var processCommand = function(params){

    // Get the command key
    var command = params.shift();

    // Create an emitter and broadcast the command
    emitter.emit(command, params);
}

var addCommand = function(name, action){

    // Listen the command
    emitter.on(name, function(){

        // Call the callback with the global context and the arguments array
        action.apply(global, arguments);
    });
}

module.exports = {
    addCommand: addCommand
};

Add the process command and the addCommand


/**
 * Module Description
 *
 * @author Author Name
 * @date 2013-01-01
 */

require([
	// Require the modules
	'modules/module'
], function (module) {
	'use strict';
});

/**
 * Module Description
 *
 * @author Author Name
 * @date 2013-01-01
 */

require([
	// Require the modules
	'modules/module'
], function (module) {
	'use strict';

	console.log(module);
});

Use module variable in JS example module to fix JSHint