const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  entry: {
    main: __dirname + "/src/InfiniteAnyHeight.jsx",
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
    library: "InfiniteAnyHeight",
    libraryTarget: "umd",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
    })
  ],
}

const HtmlWebPackPlugin = require("html-webpack-plugin")

const mainFile = "InfiniteAnyHeight.jsx"

module.exports = {
  entry: {
    main: __dirname + "/src/" + mainFile,
  },

  output: {
    filename: "[name].js",
    path: __dirname + "/dist",
    library: mainFile.substring (0, mainFile.indexOf(".")),
    libraryTarget: "umd",
  },

  devtool: "source-map",

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: [/node_modules/],
        use: {
          loader: "babel-loader",
        }
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: { minimize: true },
          }
        ]
      },
    ],
  },

  plugins: [
    new HtmlWebPackPlugin({
      template: "./src/index.html",
      filename: "./index.html",
    })
  ],
}

Use main file name as umd library name


const path = require('path')

// commonjs module
module.exports = {
  context: __dirname,
  entry: './js/ClientApp.js',
  devtool: 'eval',
  output: {
    path: path.join(__dirname, '/public'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.json']
  },
  stats: {
    colors: true,
    reasons: true,
    chunks: true
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader'
      }
    ]
  }
}

const path = require('path')

// commonjs module
module.exports = {
  context: __dirname,
  entry: './js/ClientApp.js',
  devtool: 'eval',
  output: {
    path: path.join(__dirname, '/public'),
    filename: 'bundle.js'
  },
  resolve: {
    extensions: ['.js', '.json']
  },
  stats: {
    colors: true,
    reasons: true,
    chunks: true
  },
  module: {
    rules: [
      {
        include: path.resolve(__dirname, 'js'),
        test: /\.js$/,
        loader: 'babel-loader'
      }
    ]
  }
}

Configure babel to only include files in the js directory.


const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/js/app.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    },
    devtool: 'inline-source-map',
    devServer: {
        contentBase: '.'
    },
    module: {
        rules: [
            {
                test: /\.s(a|c)ss$/,
                use: [{
                    loader: "style-loader" // creates style nodes from JS strings
                }, {
                    loader: "css-loader" // translates CSS into CommonJS
                }, {
                    loader: "sass-loader" // compiles Sass to CSS
                }],
            },
            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin
                // loader: "url?limit=10000"
                use: "url-loader"
            },
            {
                test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
                use: 'file-loader'
            }
        ]
    }
}

if (process.env.NODE_ENV !== 'production') {
    module.exports.plugins = (module.exports.plugins || []).concat([
        new HtmlWebpackPlugin({
            template: './src/index.html'
        })
    ])
}

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry: './src/js/app.js',
    output: {
        path: __dirname + '/dist',
        filename: 'bundle.js'
    },
    devtool: 'inline-source-map',
    devServer: {
        contentBase: '.'
    },
    module: {
        rules: [
            {
                test: /\.s(a|c)ss$/,
                use: [{
                    loader: "style-loader" // creates style nodes from JS strings
                }, {
                    loader: "css-loader" // translates CSS into CommonJS
                }, {
                    loader: "sass-loader" // compiles Sass to CSS
                }],
            },
            {
                test: /\.woff2?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
                // Limiting the size of the woff fonts breaks font-awesome ONLY for the extract text plugin
                // loader: "url?limit=10000"
                use: "url-loader"
            },
            {
                test: /\.(ttf|eot|svg)(\?[\s\S]+)?$/,
                use: 'file-loader'
            }
        ]
    }
}

if (process.env.NODE_ENV !== 'production') {
    module.exports.plugins = (module.exports.plugins || []).concat([
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        new HtmlWebpackPlugin({
            filename: 'about.html',
            template: './src/about.html'
        })
    ])
}

Add About page to Webpack Dev server.


var all = {
    // define openshift runtime environment
    server: {
        port : process.env.OPENSHIFT_NODEJS_PORT || 8080,
        host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
    },

    // define mongodb runtime environment
    mongodb: {
        uri :   process.env.MONGOLAB_URI ||
                process.env.OPENSHIFT_MONGODB_DB_URL+process.env.OPENSHIFT_APP_NAME ||
                'mongodb://localhost/devnews-dev'
    },

    // Should we populate the DB with sample data?
    seedDB: false
};

// default to a 'localhost' configuration:
all.mongodb = {
    uri: 'mongodb://localhost/devnews-dev'
};

// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
    all.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
    all.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}

module.exports = all;

var all = {
    // define openshift runtime environment
    server: {
        port : process.env.OPENSHIFT_NODEJS_PORT || 8080,
        host : process.env.OPENSHIFT_NODEJS_IP || '127.0.0.1'
    },

    // Should we populate the DB with sample data?
    seedDB: false
};

// default to a 'localhost' configuration:
all.mongodb = {
    uri: 'mongodb://localhost/devnews-dev'
};

// if OPENSHIFT env variables are present, use the available connection info:
if (process.env.MONGOLAB_URI) {
    all.mongodb.uri = process.env.MONGOLAB_URI;
} else if(process.env.OPENSHIFT_MONGODB_DB_PASSWORD) {
    all.mongodb.uri = 'mongodb://' + process.env.OPENSHIFT_MONGODB_DB_USERNAME + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PASSWORD + '@' +
    process.env.OPENSHIFT_MONGODB_DB_HOST + ':' +
    process.env.OPENSHIFT_MONGODB_DB_PORT + '/' +
    process.env.OPENSHIFT_APP_NAME;
}

module.exports = all;

Remove duplicate mongoldb env setting


import { sortByKey } from '../utils/model_utils';
import { RECEIVE_ARTICLES, SORT_ARTICLES } from '../constants';

const initialState = {
  articles: [],
  limit: 500,
  limitReached: false,
  sortKey: 'character_sum'
};

const SORT_DESCENDING = {
  rating_num: true,
  title: true,
  character_sum: true,
  view_count: true
};

const isLimitReached = (revs, limit) => {
  return (revs.length < limit);
};

export default function articles(state = initialState, action) {
  switch (action.type) {
    case RECEIVE_ARTICLES:
      return {
        articles: action.data.course.articles,
        limit: action.limit,
        limitReached: isLimitReached(action.data.course.articles, action.limit)
      };
    case SORT_ARTICLES: {
      const newState = { ...state };
      const sorted = sortByKey(newState.articles, action.key, state.sortKey, SORT_DESCENDING[action.key]);
      newState.users = sorted.newModels;
      newState.sortKey = sorted.newKey;
      return newState;
    }
    default:
      return state;
  }
}

import { sortByKey } from '../utils/model_utils';
import { RECEIVE_ARTICLES, SORT_ARTICLES } from '../constants';

const initialState = {
  articles: [],
  limit: 500,
  limitReached: false,
  sortKey: 'character_sum'
};

const SORT_DESCENDING = {
  character_sum: true,
  view_count: true
};

const isLimitReached = (revs, limit) => {
  return (revs.length < limit);
};

export default function articles(state = initialState, action) {
  switch (action.type) {
    case RECEIVE_ARTICLES:
      return {
        articles: action.data.course.articles,
        limit: action.limit,
        limitReached: isLimitReached(action.data.course.articles, action.limit)
      };
    case SORT_ARTICLES: {
      const newState = { ...state };
      const sorted = sortByKey(newState.articles, action.key, state.sortKey, SORT_DESCENDING[action.key]);
      newState.users = sorted.newModels;
      newState.sortKey = sorted.newKey;
      return newState;
    }
    default:
      return state;
  }
}

Align with current sort behavior


define([
  'extensions/collections/matrix'
],
function (MatrixCollection) {
  var VisitorsRealtimeCollection = MatrixCollection.extend({

    apiName: "realtime",

    queryParams: function () {
      return {
        sort_by: "_timestamp:descending",
        limit: this.options.numTwoMinPeriodsToQuery || 722
      };
    },

    updateInterval: 120 * 1000,

    initialize: function (models, options) {
      MatrixCollection.prototype.initialize.apply(this, arguments);

      if (isClient) {
        clearInterval(this.timer);
        this.timer = setInterval(
          _.bind(this.fetch, this), this.updateInterval
        );
      }
    },

    parse: function (response) {

      return {
        id: 'realtime',
        title: 'Realtime',
        values: response.data.reverse()
      };

    },

    fetch: function (options) {
      options = _.extend({
        headers: {
          "cache-control": "max-age=120"
        }
      }, options);
      MatrixCollection.prototype.fetch.call(this, options);
    }
  });

  return VisitorsRealtimeCollection;
});

define([
  'extensions/collections/matrix'
],
function (MatrixCollection) {
  var VisitorsRealtimeCollection = MatrixCollection.extend({

    apiName: "realtime",

    queryParams: function () {
      return {
        sort_by: "_timestamp:descending",
        limit: this.options.numTwoMinPeriodsToQuery || (((60/2) * 24) + 2)
      };
    },

    updateInterval: 120 * 1000,

    initialize: function (models, options) {
      MatrixCollection.prototype.initialize.apply(this, arguments);

      if (isClient) {
        clearInterval(this.timer);
        this.timer = setInterval(
          _.bind(this.fetch, this), this.updateInterval
        );
      }
    },

    parse: function (response) {

      return {
        id: 'realtime',
        title: 'Realtime',
        values: response.data.reverse()
      };

    },

    fetch: function (options) {
      options = _.extend({
        headers: {
          "cache-control": "max-age=120"
        }
      }, options);
      MatrixCollection.prototype.fetch.call(this, options);
    }
  });

  return VisitorsRealtimeCollection;
});

Improve readability of hard-coded number


module.exports = [
  {
    collection: 'entries',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { time: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { geom: '2dsphere' },
    options: {},
  },
  {
    collection: 'locations',
    spec: { layer: 1 },
    options: {},
  },
  {
    // Text index
    collection: 'locations',
    spec: {
      text1: 'text',  // primary
      text2: 'text',  // secondary
    },
    options: {
      weights: {
        text1: 3,
        text2: 1,
      },
      name: 'TextIndex',
    },
  },
  {
    collection: 'users',
    spec: { email: 1 },
    options: { unique: true },
  },
  {
    collection: 'users',
    spec: { name: 1 },
    options: { unique: true },
  },
];

module.exports = [
  {
    collection: 'entries',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { time: 1 },
    options: {},
  },
  {
    collection: 'events',
    spec: { locationId: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { geom: '2dsphere' },
    options: {},
  },
  {
    collection: 'locations',
    spec: { layer: 1 },
    options: {},
  },
  {
    collection: 'locations',
    spec: { status: 1, type: 1 },
    options: {},
  },
  {
    // Text index
    collection: 'locations',
    spec: {
      text1: 'text',  // primary
      text2: 'text',  // secondary
    },
    options: {
      weights: {
        text1: 3,
        text2: 1,
      },
      name: 'TextIndex',
    },
  },
  {
    collection: 'users',
    spec: { email: 1 },
    options: { unique: true },
  },
  {
    collection: 'users',
    spec: { name: 1 },
    options: { unique: true },
  },
];

Create a compound index for status and type


// Originally found in JinsuNogi.

// Description:
// Automatically confirms the "You cannot switch to another channel while in conversation with an NPC." error message when attempting to change channels in NPC conversation.

// Walkthrough:
// IDA unicode string view -> code.interface.msg.etc.no_channelmove_npctalk
// xrefs
// Should be in a switch statement where you can see other denail strings being
// referenced.
// Change the first jz in this function to skip all the checks.

var firstJz = scan('0F 84 ?? ?? ?? ?? 89 5D F0 89 5D FC 8B 8E');

patch(firstJz, [0x90, 0xE9]);

// Originally found in JinsuNogi.

// Description:
// Automatically confirms the "You cannot switch to another channel while in conversation with an NPC." error message when attempting to change channels in NPC conversation.

// Walkthrough:
// IDA unicode string view -> code.interface.msg.etc.no_channelmove_npctalk
// xrefs
// Should be in a switch statement where you can see other denail strings being
// referenced.
// Change the first jz in this function to skip all the checks.

var firstJz = scan('0F 84 ? ? ? ? 89 5D F0 89 5D FC 8B CE');

patch(firstJz, [0x90, 0xE9]);

Fix for the latest update.


'use strict';

var app = angular.module('2048App', ['Game', 'Grid']);

// Game Controller
app.controller('GameController', ['GameManager', 'GridManager', function(GameManager, GridManager) {
  this.game = GameManager;
  this.grid = GridManager;
}]);

'use strict';

var app = angular.module('2048App', ['Game', 'Grid']);

// Game Controller
app.controller('GameController', ['GameManager', 'GridManager', function(GameManager, GridManager) {
  this.game = GameManager;
  this.grid = GridManager;

  this.newGame = function() {
    this.game.newGame();
  };

  this.newGame();
}]);

Create newGame method within GameController.


"use strict";

const SqsConsumer = require('aws-sdk-ext').sqs.SqsConsumer,
  // SqsConsumer = require('../../lib').sqs.SqsConsumer,
  winston = require('winston'),
  promisify = require('es6-promisify'),
  config = require('config'),
  utils = require('aws-sdk-ext').utils;

class SqsConsumerExample extends SqsConsumer {
  handle(msgBody) {
    winston.info(`SqsExample::${this.name}:: Handled message: ${JSON.stringify(msgBody)}`);
  }
}

/**
 * Create consumer
 *
 * @type {SqsConsumerExample}
 */
const consumer = new SqsConsumerExample({
  name: 'sqs-consumer-example', // This is name of consumer and not queue name
  conf: { }, // Override conf/default.yaml settings here
  sqs: null // If not specified, it will automatically be created.
});

consumer.on('running', () => {
  winston.info("SqsExample:: Sending test message");
  return consumer.sendMessage({"id": 1, "test": "test"}, {"secretKey": "Secret Value"})
    .catch(err => {
      winston.error(err);
      throw err;
  });
});

consumer.on('stopped', () => {
  winston.info(`SqsExample::${consumer.name}:: Consumer stopped`);
});

consumer.start();
// We stop the consumer after 20s.
// In actual application, you can stop the queue on SIGINT
utils.wait(20000).then(() => consumer.stop());

"use strict";

const SqsConsumer = require('aws-sdk-ext').sqs.SqsConsumer,
  // SqsConsumer = require('../../lib').sqs.SqsConsumer,
  winston = require('winston'),
  promisify = require('es6-promisify'),
  config = require('config'),
  utils = require('aws-sdk-ext').utils;

class SqsConsumerExample extends SqsConsumer {
  handle(msgBody) {
    winston.info(`SqsExample::${this.name}:: Handled message: ${JSON.stringify(msgBody)}`);
  }
}

/**
 * Create consumer
 *
 * @type {SqsConsumerExample}
 */
const consumer = new SqsConsumerExample({
  name: 'sqs-consumer-example', // This is name of consumer and not queue name
  conf: { }, // Override conf/default.yaml settings here
  sqs: null // If not specified, it will automatically be created.
});

consumer.on('running', () => {
  winston.info("SqsExample:: Sending test message");
  return consumer.sendMessage({"id": 1, "test": "test"} /*, {"secretKey": "Secret Value"} */)
    .catch(err => {
      winston.error(err);
      throw err;
  });
});

consumer.on('stopped', () => {
  winston.info(`SqsExample::${consumer.name}:: Consumer stopped`);
});

consumer.start();
// We stop the consumer after 20s.
// In actual application, you can stop the queue on SIGINT
utils.wait(20000).then(() => consumer.stop());

Comment out encryption by default ine xample


/*global
	$
*/
$(document).ready(function () {

	'use strict';

	var $grid = $('.grid'),
		$textItems = $grid.find('.grid-item');

	$grid = $('.grid').masonry({
        itemSelector: '.grid-item'
    });

    $grid.imagesLoaded().progress(function (imgLoad, image) {
        var $gridItem = $(image.img).parents('.grid-item');
        $gridItem.fadeIn().removeClass('loading');
        if (image.isLoaded) {
            $gridItem.addClass('loaded');
        } else {
            $gridItem.addClass('unloaded');
        }
        $grid.masonry('layout');
    });
});

/*global
	$
*/
$(document).ready(function () {

	'use strict';

	var $grid = $('.grid'),
		$textItems = $grid.find('.grid-item');

	$grid = $('.grid').masonry({
        itemSelector: '.grid-item'
    });

    $grid.imagesLoaded().progress(function (imgLoad, image) {
        var $gridItem = $(image.img).parents('.grid-item');
        $gridItem.fadeIn('fast').removeClass('loading');
        if (image.isLoaded) {
            $gridItem.addClass('loaded');
        } else {
            $gridItem.addClass('unloaded');
        }
        $grid.masonry('layout');
    });
});

Change thumbnail load animation (Fade in fast)


module.exports = {
  entry: './src/app.js',
  output: {
    path: __dirname,
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: { presets: [ 'es2015', 'react' ] }
      }
    ]
  }
};

module.exports = {
  entry: './src/app.js',
  output: {
    path: __dirname,
    filename: './public/js/simplenotes.js'
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel',
        query: { presets: [ 'es2015', 'react' ] }
      }
    ]
  }
};

Move generated JS to public folder


import Shape from 'kittik-shape-basic';

/**
 * Implements rectangle shape with text support.
 *
 * @since 1.0.0
 * @version 1.0.0
 */
export default class Rectangle extends Shape {
  render(cursor) {
    let text = this.getText();
    let width = this.getWidth();
    let height = this.getHeight();
    let {x: x1, y: y1} = this.getPosition();
    let {x2, y2} = {x2: width + x1 - 1, y2: height + y1 - 1};
    let background = this.getBackground();
    let foreground = this.getForeground();

    cursor.fill({x1, y1, x2, y2, background, foreground});
    cursor.setPosition(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);

    return this;
  }
}

import Shape from 'kittik-shape-basic';

/**
 * Implements rectangle shape with text support.
 *
 * @since 1.0.0
 * @version 1.0.0
 */
export default class Rectangle extends Shape {
  fill(cursor, options = {}) {
    let {x, y, width, height, symbol = ' ', background, foreground} = options;
    let filler = symbol.repeat(width + 1);

    if (typeof background !== 'undefined') cursor.background(background);
    if (typeof foreground !== 'undefined') cursor.foreground(foreground);

    cursor.moveTo(x, y);

    while (y <= height + y) {
      cursor.write(filler);
      cursor.moveTo(x, ++y);
    }

    return this;
  }

  render(cursor) {
    let text = this.getText();
    let width = this.getWidth();
    let height = this.getHeight();
    let {x: x1, y: y1} = this.getPosition();
    let {x2, y2} = {x2: width + x1 - 1, y2: height + y1 - 1};
    let background = this.getBackground();
    let foreground = this.getForeground();

    this.fill(cursor, {x1, y1, x2, y2, background, foreground});
    cursor.setPosition(x1 + (width / 2 - text.length / 2), y1 + (height / 2)).write(text);

    return this;
  }
}

Move fill method from Cursor to Shape


const Testcase = require('./Testcase');

class Testsuite {
  constructor (id, result) {
    this.testsuite = [{
      _attr: {
        id,
        name: result.testFilePath,
        errors: 0,
        package: result.testFilePath,
        hostname: 'localhost',
        tests: (result.numPendingTests + result.numFailingTests + result.numPassingTests),
        failures: result.numFailingTests,
        time: (result.perfStats.end - result.perfStats.start) / 1000,
        timestamp: new Date(result.perfStats.start).toISOString().slice(0, -5)
      }
    }];

    this.testsuite.push({ properties: [] });
    result.testResults
      .filter(result => (result.status !== 'pending'))
      .forEach(result => this.testsuite.push(new Testcase(result)));
    this.testsuite.push({ 'system-out': {} });
    this.testsuite.push({ 'system-err': {} });
  }
}

module.exports = Testsuite;

const Testcase = require('./Testcase');

class Testsuite {
  constructor (id, result) {
    let testcases = result.testResults
      .filter(result => (result.status !== 'pending'))
      .map(result => new Testcase(result));

    let suite = {
      _attr: {
        id,
        name: result.testFilePath,
        errors: 0,
        package: result.testFilePath,
        hostname: 'localhost',
        tests: (result.numPendingTests + result.numFailingTests + result.numPassingTests),
        failures: result.numFailingTests,
        time: (result.perfStats.end - result.perfStats.start) / 1000,
        timestamp: new Date(result.perfStats.start).toISOString().slice(0, -5)
      }
    };

    this.testsuite = [suite, { properties: [] }]
      .concat(
        testcases,
        { 'system-out': {} },
        { 'system-err': {} }
      );
  }
}

module.exports = Testsuite;

Remove imperative code in favor of declarative statements for building testsuite


/*

 Run this deamon process alongside gatewayd:

     GATEWAYD_PATH=/path/to/gatewayd pm2 start deposits-manager.js

 The `gatewayd` object accesses the database models via the process
 environment to record crptyo coin addresses and transactions in
 gatewayd for processing and sending onward.

*/

const gatewayd = require(process.env.GATEWAYD_PATH);
const blockchain = require('blockchain-account-monitor');
const ExternalAccount = gatewayd.data.models.externalAccounts;
const ExternalTransaction = gatewayd.data.models.externalTransactions;

const monitor = new BlockchainAccountMonitor({
  blockchainClient:  new BlockchainClient(
    gatewayd.config.get('DOGECOIND')
  ),
  onBlock: function(block, next) {
    block.forEach(function(transaction) {
      ExternalAccount.findOrCreate({
        where: {
          uid: transaction.address,
          name: 'dogecoin'
        }
      })
      .then(function(externalAccount) {
        return ExternalTransaction.create({
          uid: transaction.hash,
          amount: transaction.amount,
          currency: 'DOG',
          external_account_id: externalAccount.id
        })
      })
      .then(function() {
        gatewayd.config.set('LAST_BLOCK_HASH', transaction.blockhash);
        next();
      })
      .error(function(error) {
        gatewayd.config.set('LAST_BLOCK_HASH', transaction.blockhash);
        next();
      });
    });
  },
  timeout: 5000
});

monitor.lastBlockHash = config.get('LAST_BLOCK_HASH');

monitor.start();

Monitor blockchain and record transactions in gatewayd.


/*global define*/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory)
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory()
  } else {
    // Browser globals (root is window)
    root.SubclassError = factory()
  }
}(this, function () {
  var ErrorInheritor = function () {}
  function SubclassError (name, BaseError, props) {
    if (name === undefined) throw new Error('Name of subclass must be provided as first argument.')
    if (!(BaseError instanceof Function)) {
      props = BaseError
      BaseError = Error
    }
    ErrorInheritor.prototype = BaseError.prototype
    var e = function (message) {
      this.message = message

      // stack "hack"
      var goodStack = (new Error()).stack.split('\n')
      goodStack.splice(1, 1)
      goodStack[0] = name
      if (message) goodStack[0] += ': ' + message
      this.stack = goodStack.join('\n')
    }
    e.prototype = new ErrorInheritor()
    e.prototype.constructor = e
    e.prototype.name = name
    for (var prop in props) {
      e.prototype[prop] = props[prop]
    }
    return e
  }

  return SubclassError
}))

/*global define*/
(function (root, factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define([], factory)
  } else if (typeof exports === 'object') {
    // Node. Does not work with strict CommonJS, but
    // only CommonJS-like environments that support module.exports,
    // like Node.
    module.exports = factory()
  } else {
    // Browser globals (root is window)
    root.SubclassError = factory()
  }
}(this, function () {
  var ErrorInheritor = function () {}
  function SubclassError (name, BaseError, props) {
    if (name === undefined) throw new Error('Name of subclass must be provided as first argument.')
    if (!(BaseError instanceof Function)) {
      props = BaseError
      BaseError = Error
    }
    ErrorInheritor.prototype = BaseError.prototype
    var e = function (message) {
      if (message) this.message = message

      // stack "hack"
      var goodStack = (new Error()).stack.split('\n')
      goodStack.splice(1, 1)
      goodStack[0] = name
      if (message) goodStack[0] += ': ' + message
      this.stack = goodStack.join('\n')
    }
    e.prototype = new ErrorInheritor()
    e.prototype.constructor = e
    e.prototype.name = name
    for (var prop in props) {
      e.prototype[prop] = props[prop]
    }
    return e
  }

  return SubclassError
}))

Allow `message` to be inherited from prototype


configuration = {
  node_name: "default",  // ensure this is unique in your cluster
  redis: {
    ip: '127.0.0.1',
    port: 6379,
    db: 1
  },
  servers: [
    { type: 'tcp', ip: '127.0.0.1', port: 8080 },
    { type: 'ws',  ip: '127.0.0.1', port: 8081 }
  ],
  extensions: [
    {
      name: "basic",
      type: "node",
      module: "../lib/ext/basic"
    },
    {
      name: "metadata",
      type: "node",
      module: "../lib/ext/metadata"
    },
    {
      name: "pubsub",
      type: "node",
      module: "../lib/ext/pubsub",
      options: { db: 1 }
    }
  ],
  max_clients: 50000,
  max_request_size: 50240,
  max_queued_requests: 100
};

configuration = {
  node_name: "default",  // ensure this is unique in your cluster
  redis: {
    ip: '127.0.0.1',
    port: 6379,
    db: 1
  },
  servers: [
    { type: 'tcp', ip: '127.0.0.1', port: 8080 },
    { type: 'ws',  ip: '127.0.0.1', port: 8081 }
  ],
  extensions: [
    {
      name: "basic",
      type: "node",
      module: "../lib/ext/basic"
    },
    {
      name: "metadata",
      type: "node",
      module: "../lib/ext/metadata"
    },
    {
      name: "pubsub",
      type: "node",
      module: "../lib/ext/pubsub",
      options: { db: 1 }
    },
    {
      name: "nickname",
      type: "node",
      module: "../lib/ext/nickname",
    }
  ],
  max_clients: 50000,
  max_request_size: 50240,
  max_queued_requests: 100
};

Enable nickname extension by default


'use strict';

require('mocha-given')
var chai       = require('chai')
var expect     = chai.expect
var context    = describe
var catchError = require('catch-error')
var sinon      = require('sinon')
var sinonChai  = require('sinon-chai')
chai.use(sinonChai)

var gjLayerControllerFactory = require('../lib/geojsonLayerController')

class Map {}
class KeyController {}
var dataServiceFactory = () => {
  return {}
}
var popupPresenterFactory = () => {
  return {}
}
var stylePresenterFactory = () => {
  return {}
}
var filterFactory = () => {
  return {}
}

describe('geojsonLayerController', () => {
  describe('creating a geojsonLayerController', () => {
    var config, gjLayerController

    Given('some config', () => {
      config = {
        map: new Map(),
        keyController: new KeyController(),
        dataServiceFactory: dataServiceFactory,
        popupPresenterFactory: popupPresenterFactory,
        stylePresenterFactory: stylePresenterFactory,
        filterFactory: filterFactory
      }
    })
    When('the module is called with config', () => {
      gjLayerController = gjLayerControllerFactory(config)
    })
    Then('the module should be an object', () => {
      expect(gjLayerController).to.be.an('object')
    })
  })
})

Add basic test for geojsonLayerController


// @flow
import getComputedStyle from './getComputedStyle';

export default (element: Element): boolean =>
  getComputedStyle(element).display.startsWith('table');

// @flow
import getNodeName from './getNodeName';

export default (element: Element): boolean =>
  ['table', 'td', 'th'].includes(getNodeName(element));

Revert "fix: detect CSS tables"


module.exports = (function () {
    'use strict';

    // Require dependencies
    var u = require('utils/index'),
        iterate = require('_iterator');

    /**
     * Applies CSS styles to DOM element(s).
     * @param {object} styles Object literal holding CSS style properties.
     * @return {*}
     */
    return function css(styles) {
        /**
         * @private
         * @param {object} element The HTML element to add the syyles on.
         */
        function applyStyles(element) {
            Object.keys(styles).forEach(function (key) {
                element.style[key] = styles[key];
            });
        }

        iterate(this, function (el) {
            u.is.element(el) && applyStyles(el);
        });

        return this;
    };
}());

module.exports = (function () {
    'use strict';

    // Require dependencies
    var u = require('utils/index'),
        iterate = require('_iterator');

    /**
     * Applies CSS styles to DOM element(s).
     * @param {object} styles Object literal holding CSS style properties.
     * @return {object} The DOMQuery object
     */
    return function css(styles) {
        /**
         * @private
         * @param {object} element The HTML element to add the styles on.
         */
        function applyStyles(element) {
            u.is.plainObject(styles) && Object.keys(styles).forEach(function (key) {
                element.style[key] = styles[key];
            });
        }

        iterate(this, function (el) {
            u.is.element(el) && applyStyles(el);
        });

        return this;
    };
}());

Check if argument provided is a plin object


// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

$.extend(cur_frm.cscript, {
	onload: function() {
		if(cur_frm.doc.__onload && cur_frm.doc.__onload.quotation_series) {
			cur_frm.fields_dict.quotation_series.df.options = cur_frm.doc.__onload.quotation_series;
		}
	},
	refresh: function(){
		toggle_mandatory(cur_frm)
	},
	enable_checkout: function(){
		toggle_mandatory(cur_frm)
	}
});

function toggle_mandatory (cur_frm){
	cur_frm.toggle_reqd("payment_gateway_account", false);
	if(cur_frm.doc.enabled && cur_frm.doc.enable_checkout) {
		cur_frm.toggle_reqd("payment_gateway_account", true);
	}
}

// Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt

$.extend(cur_frm.cscript, {
	onload: function() {
		if(cur_frm.doc.__onload && cur_frm.doc.__onload.quotation_series) {
			cur_frm.fields_dict.quotation_series.df.options = cur_frm.doc.__onload.quotation_series;
			cur_frm.refresh_field("quotation_series");
		}
	},
	refresh: function(){
		toggle_mandatory(cur_frm)
	},
	enable_checkout: function(){
		toggle_mandatory(cur_frm)
	}
});

function toggle_mandatory (cur_frm){
	cur_frm.toggle_reqd("payment_gateway_account", false);
	if(cur_frm.doc.enabled && cur_frm.doc.enable_checkout) {
		cur_frm.toggle_reqd("payment_gateway_account", true);
	}
}

Refresh quotation_series field to show series


'use strict';

/**
 * @ngdoc overview
 * @name pattyApp
 * @description
 * # pattyApp
 *
 * Main module of the application.
 */
angular
  .module('pattyApp', [
    'ngAnimate',
    'ngSanitize',
    'ngTouch',
    'ui.bootstrap',
    'pattyApp.searchbox',
    'pattyApp.minimap',
    'pattyApp.pointcloud'
  ])
  .config(function() {

  }).run(function(SitesService, DrivemapService) {
    DrivemapService.load();
    SitesService.load();
  });

angular.module('pattyApp.templates', []);
angular.module('pattyApp.utils', ['pattyApp.templates']);
angular.module('pattyApp.core', ['pattyApp.utils'])
  .factory('proj4', function($window) {
    return $window.proj4;
  });
angular.module('pattyApp.minimap', ['pattyApp.core'])
  .factory('ol', function($window) {
    return $window.ol;
  });
angular.module('pattyApp.pointcloud', ['pattyApp.core'])
  .factory('THREE', function($window) {
    return $window.THREE;
  })
  .factory('POCLoader', function($window) {
    return $window.POCLoader;
  })
  .factory('Potree', function($window) {
    return $window.Potree;
  });
angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']);

// The app

/* global proj4:false, ol:false, THREE:false, POCLoader:false, Potree:false */
(function() {
  'use strict';

  /**
   * @ngdoc overview
   * @name pattyApp
   * @description
   * # pattyApp
   *
   * Main module of the application.
   */
  angular
    .module('pattyApp', [
      'ngAnimate',
      'ngSanitize',
      'ngTouch',
      'ui.bootstrap',
      'pattyApp.searchbox',
      'pattyApp.minimap',
      'pattyApp.pointcloud'
    ])
    .config(function() {

    }).run(function(SitesService, DrivemapService) {
      DrivemapService.load();
      SitesService.load();
    });

  angular.module('pattyApp.templates', []);
  angular.module('pattyApp.utils', ['pattyApp.templates']);
  angular.module('pattyApp.core', ['pattyApp.utils'])
    .constant('proj4', proj4);
  angular.module('pattyApp.minimap', ['pattyApp.core'])
    .constant('ol', ol);
  angular.module('pattyApp.pointcloud', ['pattyApp.core'])
    .constant('THREE', THREE)
    .constant('POCLoader', POCLoader)
    .constant('Potree', Potree);
  angular.module('pattyApp.searchbox', ['pattyApp.core', 'pattyApp.pointcloud']);
})();

Create an Angular Constant for vendor libraries' global variables.


var _ = require('underscore'),
    Backbone = require('backbone'),
    ControlBones;

ControlBones = function(options) {
   var self = this;

   // Copy all options to object
   _.each(options, function(value, key) {
      self[key] = value;
   });
};

ControlBones.prototype = {
   classes: ''
};

/**
 * This is called to render the view using
 * the latest data from the model.
 */
ControlBones.prototype.render = function() {
   // noop
};

   /**
    * @return Backbone.Model
    */
ControlBones.prototype._createSummaryModel = function() {
      return new Backbone.Model({
         'header': this.title,
         'classes': this.classes
      });
   };

// Benefit from Backbone.Events
_.extend(ControlBones.prototype, Backbone.Events);

ControlBones.extend = function(prototypeAdditions) {
   var parent = this,
       child;

   child = function(){
      return parent.apply(this, arguments);
   };

   _.extend(child, parent);
   _.extend(child.prototype, parent.prototype);

   if (prototypeAdditions) {
      _.extend(child.prototype, prototypeAdditions);
   }

   return child;
};

module.exports = ControlBones;

var _ = require('underscore'),
    Backbone = require('backbone'),
    ControlBones;

ControlBones = function(options) {
   var self = this;

   // Copy all options to object
   _.each(options, function(value, key) {
      self[key] = value;
   });
};

ControlBones.prototype = {
   classes: ''
};

/**
 * This is called to render the view using
 * the latest data from the model.
 */
ControlBones.prototype.render = function() {
   // noop
};

   /**
    * @return Backbone.Model
    */
ControlBones.prototype._createSummaryModel = function() {
      return new Backbone.Model({
         'header': this.title,
         'classes': this.classes
      });
   };

// Benefit from Backbone.Events
_.extend(ControlBones.prototype, Backbone.Events);

// Snag the extend function from Backbone.Model
ControlBones.extend = Backbone.Model.extend;

module.exports = ControlBones;

Remove custom extend to use the one from Backbone


var Fraction = require('../src/fractions');
var Variable = require('../src/variables');

describe("A variable", function() {
    var x = new Variable("x");

    it("is initalized with a variable name", function() {
        expect(x.variable).toEqual("x");
    });

    it("is initialized with a degree of 1", function() {
        expect(x.degree).toEqual(1);
    });

    it("should throw an error if initialized with an integer", function() {
        expect(function(){new Variable(5)}).toThrow("InvalidArgument");
    });

    it("should throw an error if initialized with a float", function() {
        expect(function(){new Variable(5.1)}).toThrow("InvalidArgument");
    });
});

describe("Variable printing to string", function() {
    var x = new Variable("x");

    it("should print just the variable when the degree is 1", function() {
        expect(x.print()).toEqual("x");
    });

    it("should print the degree if it's greater than 1", function() {
        x.degree = 2;
        expect(x.print()).toEqual("x^2");
    });

    it("should print an empty string if the degree is 0", function() {
        x.degree = 0;
        expect(x.print()).toEqual("");
    })
});

var Fraction = require('../src/fractions');
var Variable = require('../src/variables');

describe("A variable", function() {
    var x = new Variable("x");

    it("is initalized with a variable name", function() {
        expect(x.variable).toEqual("x");
    });

    it("is initialized with a degree of 1", function() {
        expect(x.degree).toEqual(1);
    });

    it("should throw an error if initialized with an integer", function() {
        expect(function(){new Variable(5)}).toThrow("InvalidArgument");
    });

    it("should throw an error if initialized with a float", function() {
        expect(function(){new Variable(5.1)}).toThrow("InvalidArgument");
    });
});

describe("Variable printing to string", function() {
    var x = new Variable("x");

    it("should print just the variable when the degree is 1", function() {
        expect(x.print()).toEqual("x");
    });

    it("should print the degree if it's greater than 1", function() {
        x.degree = 2;
        expect(x.print()).toEqual("x^2");
    });

    it("should print an empty string if the degree is 0", function() {
        x.degree = 0;
        expect(x.print()).toEqual("");
    });
});

describe("Variable printing to tex", function() {
    var x = new Variable("x");

    it("should print just the variable when the degree is 1", function() {
        expect(x.tex()).toEqual("x");
    });

    it("should print the degree if it's greater than 1", function() {
        x.degree = 2;
        expect(x.tex()).toEqual("x^{2}");
    });

    it("should print an empty string if the degree is 0", function() {
        x.degree = 0;
        expect(x.tex()).toEqual("");
    });
});

Add tests for printing Variables to tex


/*
* This file is part of the easy framework.
*
* (c) Julien Sergent <sergent.julien@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

module.exports.entityManager = require( 'easy/test/entitymanager.mock' )
module.exports.request = require( 'easy/test/request.mock' )
module.exports.response = require( 'easy/test/response.mock' )
module.exports.fakeAsync = require( 'easy/test/fakeAsync.mock' )
module.exports.directory = require( 'easy/test/directory.mock' )
module.exports.logger = require( 'easy/test/logger.mock' )
module.exports.logWriter = require( 'easy/test/logwriter.mock' )
module.exports.logFileManager = require( 'easy/test/logfilemanager.mock' )
module.exports.tokenManager = require( 'easy/test/tokenmanager.mock' )
module.exports.authorization = require( 'easy/test/authorization.mock' )

/*
* This file is part of the easy framework.
*
* (c) Julien Sergent <sergent.julien@icloud.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

module.exports.entityManager = require( 'easy/mocks/entitymanager.mock' )
module.exports.request = require( 'easy/mocks/request.mock' )
module.exports.response = require( 'easy/mocks/response.mock' )
module.exports.fakeAsync = require( 'easy/mocks/fakeAsync.mock' )
module.exports.directory = require( 'easy/mocks/directory.mock' )
module.exports.logger = require( 'easy/mocks/logger.mock' )
module.exports.logWriter = require( 'easy/mocks/logwriter.mock' )
module.exports.logFileManager = require( 'easy/mocks/logfilemanager.mock' )
module.exports.tokenManager = require( 'easy/mocks/tokenmanager.mock' )
module.exports.authorization = require( 'easy/mocks/authorization.mock' )

Rename test directory path into mocks


define([
    'aux/prepend'
], function (prepend) {
    describe('Check if the node element is added to the parent', function () {
        var ele = document.createElement('div'),
            parent = document.createElement('div');

        it('Should call insertBefore and return the firstChild', function () {
            prepend(parent, ele);

            expect(parent.firstChild).toBe(ele);
        });
    });
});

define([
    'aux/create-element',
    'aux/get-elements-by-class',
    'aux/has-class',
    'aux/prepend'
], function (createElement, getElementsByClass, hasClass, prepend) {
    describe('Check if the node element is added to the parent', function () {
        var ele,
            doc,
            childEle,
            customDocument,
            params;

        beforeEach(function () {

            customDocument = {
                createElement: function () {
                    return true;
                }
            };
            doc = top.document;
            childEle = createElement('div');
            params = {
                attr: {
                    'id': 'div-main'
                },
                css: {
                    border: '1px solid black',
                    backgroundColor: 'red'
                },
                cssNames: ['legen', 'wait-for-it', 'dary'],
                innerHTML: '

',
                nodes: [
                    {
                        tag: 'div',
                        cssNames: 'family-guy',
                        nodes: {
                            tag: 'span',
                            cssNames: 'peter'
                        }
                    }
                ],
                children: [
                    childEle
                ]
            };
            ele = createElement('div', params, doc);
        });

        it('Should check if the parentNode has the class', function () {
            var eleOne = getElementsByClass(ele, 'futurama');

            expect(eleOne.length).toBe(1);
            expect(hasClass(eleOne[0].parentNode, 'legen')).toBeTruthy();
        });

        it('Should call insertBefore and return the firstChild', function () {

            var eleOne = getElementsByClass(ele, 'futurama'),
                parent = eleOne[0].parentNode,
                eleChild = createElement('div');

            prepend(parent, eleChild);

            expect(parent.firstChild).toBe(eleChild);
        });
    });
});

Prepend tests changed and new added


import {equal} from 'assert'
import namespacedDisplayName from './namespacedDisplayName'

describe('namespacedDisplayName', () => {
  it('sets a namespaced displayName', () => {
    const Component = function () {}
    const namespace = 'foo'
    const name = 'bar'
    equal(namespacedDisplayName(namespace)(name)(Component).displayName, `${namespace}.${name}`)
  })
})

import {equal} from 'assert'
import namespacedDisplayName from './namespacedDisplayName'

describe('namespacedDisplayName', () => {
  it('sets a namespaced displayName', () => {
    const Component = function () {}
    const namespace = 'foo'
    const name = 'bar'

    equal(
      namespacedDisplayName(namespace)(name)(Component).displayName,
      `${namespace}.${name}`
    )
  })
})

Make namespacedDisplayName test look nicer


'use strict';

var Test = require('tape');
var Path = require('path');
var Fs = require('fs');

process.env.CODE_MANAGER_HOST = 'http://localhost:3000';
process.env.FRAMEWORK_LOCAL_DEPENDENCIES_SOURCE_FOLDER = Path.join(__dirname, '..', 'public');

var Builder = require('./../lib/builder');
var Assistant = require('./../../../local/assistant/lib/assistant');

Test('builder', function(t) {
    t.plan(3);
    t.ok(Builder, 'exports');
    t.ok(new Builder(), 'instance');

    var baseDir = Path.join(__dirname, 'fixtures');
    var subDir = Path.join('a');
    var buildResult = Fs.readFileSync(Path.join(__dirname, 'fixtures', '__data', 'a-build.js'), {encoding:'utf8'});

    var assistant = new Assistant({
        builderOptions: {
            doSkipAssetSaveStep: true,
            doSkipBundleSaveStep: true,
            localComponentsSourceFolder: baseDir
        }
    });

    assistant.buildSingle(baseDir, subDir, function(err, result) {
        if (err) {
            console.error(err);
        }
        else {
            t.equals(result.bundleString, buildResult, 'freshly generated bundle string matches a previously generated build result');
            // console.log(result.bundleString);
        }
    });
});

'use strict';

var Test = require('tape');
var Path = require('path');
var Fs = require('fs');

process.env.CODE_MANAGER_HOST = 'http://localhost:3000';
process.env.FRAMEWORK_LOCAL_DEPENDENCIES_SOURCE_FOLDER = Path.join(__dirname, '..', 'public');

// This removes any previously built versions from the local file system so we
// don't end up creating a bundle that draws from non-fixture components.
// This DUMB HACK almost certainly warrants a factoring-out
if (Fs.existsSync(process.env.FRAMEWORK_LOCAL_DEPENDENCIES_SOURCE_FOLDER)) {
    Fs.rmdirSync(process.env.FRAMEWORK_LOCAL_DEPENDENCIES_SOURCE_FOLDER);
}

var Builder = require('./../lib/builder');
var Assistant = require('./../../../local/assistant/lib/assistant');

Test('builder', function(t) {
    t.plan(3);
    t.ok(Builder, 'exports');
    t.ok(new Builder(), 'instance');

    var baseDir = Path.join(__dirname, 'fixtures');
    var subDir = Path.join('a');
    var buildResult = Fs.readFileSync(Path.join(__dirname, 'fixtures', '__data', 'a-build.js'), {encoding:'utf8'});

    var assistant = new Assistant({
        builderOptions: {
            doSkipAssetSaveStep: true,
            doSkipBundleSaveStep: true,
            localComponentsSourceFolder: baseDir
        }
    });

    assistant.buildSingle(baseDir, subDir, function(err, result) {
        if (err) {
            console.error(err);
        }
        else {
            t.equals(result.bundleString, buildResult, 'freshly generated bundle string matches a previously generated build result');
            // console.log(result.bundleString);
        }
    });
});

Remove previously built version before running the test


const OrderLib = artifacts.require("OrderLib");
const MarketContractOraclize = artifacts.require("MarketContractOraclize");
const utility = require('./utility.js');

contract('OrderLib', function(accounts) {
    var orderLib;
    it("Orders are signed correctly", async function() {
        orderLib = await OrderLib.deployed();
        var timeStamp = ((new Date()).getTime() / 1000) + 60*5; // order expires 5 minute from now.
        var orderAddresses = [accounts[0], accounts[1], accounts[2]];
        var unsignedOrderValues = [0, 0, 33025, timeStamp, 0];
        var orderQty = 5;   // user is attempting to buy 5
        var orderHash = await orderLib.createOrderHash.call(
            MarketContractOraclize.address,
            orderAddresses,
            unsignedOrderValues,
            orderQty
        );
        var orderSignature = utility.signMessage(web3, accounts[0], orderHash)
        assert.isTrue(await orderLib.isValidSignature.call(
            accounts[0],
            orderHash,
            orderSignature[0],
            orderSignature[1],
            orderSignature[2]),
            "Order hash doesn't match signer"
        );
        assert.isTrue(!await orderLib.isValidSignature.call(
            accounts[1],
            orderHash,
            orderSignature[0],
            orderSignature[1],
            orderSignature[2]),
            "Order hash matches a non signer"
        );
    });
});

const OrderLib = artifacts.require("OrderLib");
const MarketContractOraclize = artifacts.require("MarketContractOraclize");
const utility = require('./utility.js');

contract('OrderLib', function(accounts) {
    var orderLib;
    it("Orders are signed correctly", async function() {
        orderLib = await OrderLib.deployed();
        var timeStamp = ((new Date()).getTime() / 1000) + 60*5; // order expires 5 minute from now.
        var orderAddresses = [accounts[0], accounts[1], accounts[2]];
        var unsignedOrderValues = [0, 0, 33025, timeStamp, 0];
        var orderQty = 5;   // user is attempting to buy 5
        var orderHash = await orderLib.createOrderHash.call(
            MarketContractOraclize.address,
            orderAddresses,
            unsignedOrderValues,
            orderQty
        );
        var orderSignature = utility.signMessage(web3, accounts[0], orderHash)
        assert.isTrue(await orderLib.isValidSignature.call(
            accounts[0],
            orderHash,
            orderSignature[0],
            orderSignature[1],
            orderSignature[2]),
            "Order hash doesn't match signer"
        );
        assert.isTrue(await orderLib.isValidSignature.call(
            accounts[1],
            orderHash,
            orderSignature[0],
            orderSignature[1],
            orderSignature[2]),
            "Order hash matches a non signer"
        );
    });
});

Test travis fails with wrong test


'use strict';

var request = require('supertest')
var should = require('should')
var keys = require('../keys.js')
var providerGoogleContact = require('../lib/provider-google-contact/index.js');

describe("Retrieve code", function () {
  it("should list contacts", function (done) {

    var token = new providerGoogleContact.models.Token({googleTokens: {access_token: keys.ACCESS_TOKEN}});

    token.save(function(err) {
      if(err) {
        throw new Error(err);
      }

      providerGoogleContact.handlers.retrieve(function() {}, function(accounts) {
        accounts.should.have.lengthOf(1);
        should.exist(accounts[0][0]);
        accounts[0][0].should.have.property('name');
        done();
      });
    })
  });
});

'use strict';

var request = require('supertest')
var should = require('should')
var keys = require('../keys.js')
var providerGoogleContact = require('../lib/provider-google-contact/index.js');

describe("Retrieve code", function () {
  it("should list contacts", function (done) {
    providerGoogleContact.handlers.retrieve(keys.ACCESS_TOKEN, function(users) {
      should.exist(users[0]);
      users[0].should.have.property('name');
      done();
    });
  });
});

Refactor test for new architecture


/* eslint-disable */

var webpack = require('webpack');

module.exports = {
	output: {
		filename: 'index.js',
		libraryTarget: 'umd',
		library: 'ReactCheckboxTree',
	},
	externals: {
		react: 'React',
	},
	module: {
		loaders: [
			{
				test: /\.js?$/,
				exclude: /(node_modules|bower_components|vender_modules)/,
				loader: 'babel',
				query: {
					presets: ['react', 'es2015', 'stage-0']
				},
			},
		],
	},
};

/* eslint-disable */

module.exports = {
	output: {
		filename: 'index.js',
		libraryTarget: 'umd',
		library: 'ReactCheckboxTree',
	},
	module: {
		loaders: [
			{
				test: /\.js?$/,
				exclude: /(node_modules|bower_components|vender_modules)/,
				loader: 'babel',
				query: {
					presets: ['react', 'es2015', 'stage-0']
				},
			},
		],
	},
};

Fix some build issues when React is not included


module.exports = {
  extends: [
    'airbnb-base',
    './common.js'
  ],

  parser: 'babel-eslint',

  plugins: [
    'babel',
    'import',
  ],

  rules: {
    'func-names': 0,
    curly: ['error', 'all']
  },
};

module.exports = {
  extends: [
    'airbnb-base'
  ],

  parser: 'babel-eslint',

  plugins: [
    'babel',
    'import',
  ],

  rules: {
    'func-names': 0,
    curly: ['error', 'all']
  },
};

Fix import file not exists in project.


module.exports = {
  // extending prettier fucks up my vim...
  extends: ['airbnb-base'],
  parser: 'typescript-eslint-parser',
  plugins: ['typescript', 'import'],
  rules: {
    'class-methods-use-this': 0,
    'comma-dangle': [
      'error',
      {
        arrays: 'only-multiline',
        objects: 'only-multiline',
        imports: 'only-multiline',
        exports: 'only-multiline',
        functions: 'ignore',
      },
    ],
    'no-underscore-dangle': 0,
    'no-mixed-operators': 0,
    'func-names': 0,

    // prettier things
    'arrow-parens': 0,
    'space-before-function-paren': 0,

    'import/extensions': 0,
  },

  settings: {
    'import/parsers': {
      'typescript-eslint-parser': ['.ts', '.tsx'],
    },
  },
};

module.exports = {
  // extending prettier fucks up my vim...
  extends: ['airbnb-base'],
  parser: 'typescript-eslint-parser',
  plugins: ['typescript', 'import'],
  rules: {
    'class-methods-use-this': 0,
    'comma-dangle': [
      'error',
      {
        arrays: 'only-multiline',
        objects: 'only-multiline',
        imports: 'only-multiline',
        exports: 'only-multiline',
        functions: 'ignore',
      },
    ],
    'no-underscore-dangle': 0,
    'no-mixed-operators': 0,
    'func-names': 0,

    // prettier things
    'arrow-parens': 0,
    'space-before-function-paren': 0,

    'import/extensions': 0,
    'import/prefer-default-export': 0,
  },

  settings: {
    'import/resolver': { node: { extensions: ['.js', '.jsx', '.ts'] } },
    'import/parsers': {
      'typescript-eslint-parser': ['.ts', '.tsx'],
    },
  },
};

Fix some eslint import rules


Application.Directives.directive("showTemplateDetails", showTemplateDetailsDirective);
function showTemplateDetailsDirective() {
    return {
        restrict: "E",
        replace: true,
        scope: {
            template: "=template",
        },
        controller: "showTemplateDetailsDirectiveController",
        templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html"
    };
}
Application.Controllers.controller("showTemplateDetailsDirectiveController",
    ["$scope", showTemplateDetailsDirectiveController]);

function showTemplateDetailsDirectiveController($scope) {
}

Application.Directives.directive("showTemplateDetails",
                                 ["RecursionHelper", showTemplateDetailsDirective]);
function showTemplateDetailsDirective(RecursionHelper) {
    return {
        restrict: "E",
        replace: true,
        scope: {
            template: "=template",
        },
        controller: "showTemplateDetailsDirectiveController",
        templateUrl: "application/core/projects/project/provenance/wizard/show-template-details.html",
        compile: function(element) {
            return RecursionHelper.compile(element, function(scope, iElement, iAttrs, controller, transcludeFn) {
            });
        }
    };
}
Application.Controllers.controller("showTemplateDetailsDirectiveController",
                                   ["$scope", showTemplateDetailsDirectiveController]);

function showTemplateDetailsDirectiveController($scope) {
}

Allow directive to be called recursively.


import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

Ember.MODEL_FACTORY_INJECTIONS = false;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;

import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';

// Set to false to fix polymorphic relationships
Ember.MODEL_FACTORY_INJECTIONS = false;

var App = Ember.Application.extend({
  modulePrefix: config.modulePrefix,
  podModulePrefix: config.podModulePrefix,
  Resolver: Resolver
});

loadInitializers(App, config.modulePrefix);

export default App;

Add comment for polymorphic fix


module.exports = function(config) {
    var configuration = {
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            'lib/*.js',
            '*.js',
            'test/*-spec.js'
        ],
        exclude: [
            'background.js',
            'main.js'
        ],
        preprocessors: {
        },
        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: false,
        concurrency: Infinity,
        plugins: [
            'karma-jasmine',
            'karma-mocha-reporter',
            'karma-chrome-launcher'
        ]
    };
    config.set(configuration);
};

module.exports = function(config) {
    var configuration = {
        basePath: '',
        frameworks: ['jasmine'],
        files: [
            'lib/*.js',
            'src/**/*.js',
            'test/*-spec.js'
        ],
        exclude: [
            'src/backend/background/background.js',
            'src/frontend/main.js'
        ],
        preprocessors: {
        },
        reporters: ['mocha'],
        port: 9876,
        colors: true,
        logLevel: config.LOG_INFO,
        autoWatch: true,
        browsers: ['Chrome'],
        singleRun: false,
        concurrency: Infinity,
        plugins: [
            'karma-jasmine',
            'karma-mocha-reporter',
            'karma-chrome-launcher'
        ]
    };
    config.set(configuration);
};

Fix tests path for Karma


module.exports = config => {
  const browser = process.env.BROWSER || 'chrome';

  config.set({
    basePath: '',
    frameworks: ['browserify', 'jasmine'],
    files: [
      'https://static.opentok.com/v2/js/opentok.js',
      'test/**/*.js'
    ],
    preprocessors: {
      'src/**/*.js': ['babel', 'browserify'],
      'test/**/*.js': ['babel', 'browserify']
    },
    browserify: {
      debug: true,
      transform: [
        ['babelify']
      ],
      configure: bundle => {
        bundle.on('prebundle', () => {
          bundle.external('react/addons');
          bundle.external('react/lib/ReactContext');
          bundle.external('react/lib/ExecutionEnvironment');
        });
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: [browser[0].toUpperCase() + browser.substr(1)],
    singleRun: false
  });
};

module.exports = config => {
  const browser = process.env.BROWSER || 'chrome';

  config.set({
    basePath: '',
    frameworks: ['browserify', 'jasmine'],
    files: [
      'https://static.opentok.com/v2/js/opentok.js',
      'test/**/*.js'
    ],
    preprocessors: {
      'src/**/*.js': ['babel', 'browserify'],
      'test/**/*.js': ['babel', 'browserify']
    },
    browserify: {
      debug: true,
      transform: [
        ['babelify']
      ],
      configure: bundle => {
        bundle.on('prebundle', () => {
          bundle.external('react/addons');
          bundle.external('react/lib/ReactContext');
          bundle.external('react/lib/ExecutionEnvironment');
        });
      }
    },
    reporters: ['spec'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_DEBUG,
    autoWatch: true,
    browsers: [browser[0].toUpperCase() + browser.substr(1)],
    singleRun: false
  });
};

Use debug logs in karma


/* German translation for the jQuery Timepicker Addon */
/* Written by Marvin */
(function($) {
	$.timepicker.regional['de'] = {
		timeOnlyTitle: 'Zeit Wählen',
		timeText: 'Zeit',
		hourText: 'Stunde',
		minuteText: 'Minute',
		secondText: 'Sekunde',
		millisecText: 'Millisekunde',
		microsecText: 'Mikrosekunde',
		timezoneText: 'Zeitzone',
		currentText: 'Jetzt',
		closeText: 'Fertig',
		timeFormat: 'HH:mm',
		amNames: ['vorm.', 'AM', 'A'],
		pmNames: ['nachm.', 'PM', 'P'],
		isRTL: false
	};
	$.timepicker.setDefaults($.timepicker.regional['de']);
})(jQuery);

/* German translation for the jQuery Timepicker Addon */
/* Written by Marvin */
(function($) {
	$.timepicker.regional['de'] = {
		timeOnlyTitle: 'Zeit wählen',
		timeText: 'Zeit',
		hourText: 'Stunde',
		minuteText: 'Minute',
		secondText: 'Sekunde',
		millisecText: 'Millisekunde',
		microsecText: 'Mikrosekunde',
		timezoneText: 'Zeitzone',
		currentText: 'Jetzt',
		closeText: 'Fertig',
		timeFormat: 'HH:mm',
		amNames: ['vorm.', 'AM', 'A'],
		pmNames: ['nachm.', 'PM', 'P'],
		isRTL: false
	};
	$.timepicker.setDefaults($.timepicker.regional['de']);
})(jQuery);

Fix typo in German translation


Facebook = {};

// Request Facebook credentials for the user
//
// @param options {optional}
// @param credentialRequestCompleteCallback {Function} Callback function to call on
//   completion. Takes one argument, credentialToken on success, or Error on
//   error.
Facebook.requestCredential = function (options, credentialRequestCompleteCallback) {
  // support both (options, callback) and (callback).
  if (!credentialRequestCompleteCallback && typeof options === 'function') {
    credentialRequestCompleteCallback = options;
    options = {};
  }

  var config = ServiceConfiguration.configurations.findOne({service: 'facebook'});
  if (!config) {
    credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
    return;
  }

  var credentialToken = Random.id();
  var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
  var display = mobile ? 'touch' : 'popup';

  var scope = "email";
  if (options && options.requestPermissions)
    scope = options.requestPermissions.join(',');

  var loginUrl =
        'https://www.facebook.com/dialog/oauth?client_id=' + config.appId +
        '&redirect_uri=' + Meteor.absoluteUrl('_oauth/facebook?close') +
        '&display=' + display + '&scope=' + scope + '&state=' + credentialToken;

  Oauth.showPopup(
    loginUrl,
    _.bind(credentialRequestCompleteCallback, null, credentialToken)
  );
};

Facebook = {};

// Request Facebook credentials for the user
//
// @param options {optional}
// @param credentialRequestCompleteCallback {Function} Callback function to call on
//   completion. Takes one argument, credentialToken on success, or Error on
//   error.
Facebook.requestCredential = function (options, credentialRequestCompleteCallback) {
  // support both (options, callback) and (callback).
  if (!credentialRequestCompleteCallback && typeof options === 'function') {
    credentialRequestCompleteCallback = options;
    options = {};
  }

  var config = ServiceConfiguration.configurations.findOne({service: 'facebook'});
  if (!config) {
    credentialRequestCompleteCallback && credentialRequestCompleteCallback(new ServiceConfiguration.ConfigError("Service not configured"));
    return;
  }

  var credentialToken = Random.id();
  var mobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|Windows Phone/i.test(navigator.userAgent);
  var display = mobile ? 'touch' : 'popup';

  var scope = "email";
  if (options && options.requestPermissions)
    scope = options.requestPermissions.join(',');

  var loginUrl =
        'https://www.facebook.com/dialog/oauth?client_id=' + config.appId +
        '&redirect_uri=' + Meteor.absoluteUrl('_oauth/facebook?close') +
        '&display=' + display + '&scope=' + scope + '&state=' + credentialToken;

  Oauth.showPopup(
    loginUrl,
    _.bind(credentialRequestCompleteCallback, null, credentialToken)
  );
};

Add Windows Phone to mobile


const iris = require('../index');
const dock = require('./docks/http');
const handler = require('./handlers/handler1');
const inputHook = require('./hooks/hook1');
const outputHook = require('./hooks/hook2');

iris.config = {
    threads: 4,
    logLevel: 'silly',
    events: {
        dispatcher: true,
        docks: true
    },
    vantage: {
        enabled: false,
        port: 1337
    }
};

dock.config = {
    port: 5000,
    parser: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    encoder: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    maxMessageLength: 100
};

iris.flow('Flow 1', {
    tag: 'tag1',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

iris.flow('Flow 2', {
    tag: 'tag2',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

const iris = require('../index');
const dock = require('./docks/http');
const handler = require('./handlers/handler1');
const inputHook = require('./hooks/hook1');
const outputHook = require('./hooks/hook2');

iris.config = {
    threads: 4,
    logLevel: 'info',
    events: {
        dispatcher: true,
        docks: true
    },
    vantage: {
        enabled: false,
        port: 1337
    }
};

dock.config = {
    port: 5000,
    parser: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    encoder: {
        subtagSeparator: '|',
        dataSeparator: ','
    },
    maxMessageLength: 100
};

iris.flow('Flow 1', {
    tag: 'tag1',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

iris.flow('Flow 2', {
    tag: 'tag2',
    docks: [dock],
    handler: handler,
    inputHooks: [inputHook],
    outputHooks: [outputHook]
});

Set example logLevel to 'info'


'use strict';

/* lib/decode.js
 * Decode WebSocket message frames.
 * * */

module.exports = function(raw){
  if (!(raw instanceof Buffer))
    raw = new Buffer(raw);

  let message = [],
      data = {};

  // TODO: decode

  return Object.assign(new Buffer(message).toString(), data);
};

'use strict';

/* lib/decode.js
 * Decode WebSocket message frames.
 * * */

module.exports = function(raw){
  if (!(raw instanceof Buffer))
    raw = new Buffer(raw);

  let message = [],
      data = {};

  data.fin = !!(128 & raw[0]);
  data.rsv = [!!(64 & raw[0]), !!(32 & raw[0]), !!(16 & raw[0])];

  return Object.assign(new Buffer(message).toString(), data);
};

Add fin and rsv decoding


/*
  Used as an entry file to generate vendor/brace.min.js
*/
var brace = require('brace')

require('brace/mode/c_cpp')
require('brace/mode/javascript')
require('brace/mode/json')
require('brace/mode/html')
require('brace/mode/markdown')
require('brace/mode/python')
require('brace/mode/r')
require('brace/mode/ruby')
require('brace/mode/sh')
require('brace/theme/monokai')

module.exports = brace

/*
  Used as an entry file to generate vendor/brace.min.js
*/
var brace = require('brace')

//require('brace/mode/c_cpp')
require('brace/mode/javascript')
//require('brace/mode/json')
//require('brace/mode/html')
//require('brace/mode/markdown')
require('brace/mode/python')
require('brace/mode/r')
//require('brace/mode/ruby')
//require('brace/mode/sh')
require('brace/mode/sql')

require('brace/theme/monokai')

module.exports = brace

Add sql mode, comment out other unused ones


function fix (template) {
  if (!template.content && window.HTMLTemplateElement && window.HTMLTemplateElement.decorate) {
    window.HTMLTemplateElement.decorate(template);
  }
  return template;
};

function needFixImportNode () {
  // console.log('needFixImportNode?');
  if (document.__importNode) {
    // already fixed
    return false;
  }
  let template = document.createElement('template');
  template.innerHTML = '<template>i</template>';
  let imported = document.importNode(template.content, true);
  return imported.firstChild.content.firstChild.textContent !== 'i';
}

if (needFixImportNode()) {
  // console.log('fixed importNode');
  document.__importNode = document.importNode;
  document.importNode = function (node, deep) {
    if (!deep) {
      return document.__importNode(node, deep);
    }

    let sourceTpls = [].slice.call(node.querySelectorAll('template'));
    let imported = document.__importNode(node, deep);
    [].forEach.call(imported.querySelectorAll('template'), (child, i) => {
      child.innerHTML = sourceTpls[i].innerHTML;
    });

    return imported;
  };
}

export { fix };

function fix (template) {
  if (!template.content && window.HTMLTemplateElement && window.HTMLTemplateElement.decorate) {
    window.HTMLTemplateElement.decorate(template);
  }
  return template;
};

function needFixImportNode () {
  // console.log('needFixImportNode?');
  if (document.__importNode) {
    // already fixed
    return false;
  }
  let template = document.createElement('template');
  template.innerHTML = '<template>i</template>';
  let imported = document.importNode(template.content, true);
  return !imported.firstChild.content.firstChild || imported.firstChild.content.firstChild.textContent !== 'i';
}

if (needFixImportNode()) {
  // console.log('fixed importNode');
  document.__importNode = document.importNode;
  document.importNode = function (node, deep) {
    if (!deep) {
      return document.__importNode(node, deep);
    }

    let sourceTpls = [].slice.call(node.querySelectorAll('template'));
    let imported = document.__importNode(node, deep);
    [].forEach.call(imported.querySelectorAll('template'), (child, i) => {
      child.innerHTML = sourceTpls[i].innerHTML;
    });

    return imported;
  };
}

export { fix };

Fix function needFixImportNode to work with kitkat


const loaderUtils = require('loader-utils');

module.exports = (input) => {
  const { text } = loaderUtils.getOptions(this);

  return input + text;
};
module.exports.pitch = (
  remainingRequest, precedingRequest, input
) => {
  console.log(
    'remaining request', remainingRequest,
    'preceding request', precedingRequest,
    'input', input
  );

  return 'pitched';
};

const loaderUtils = require('loader-utils');

module.exports = function(input) {
  const { text } = loaderUtils.getOptions(this);

  return input + text;
};
module.exports.pitch = function(
  remainingRequest, precedingRequest, input
) {
  console.log(
    'remaining request', remainingRequest,
    'preceding request', precedingRequest,
    'input', input
  );

  return 'pitched';
};

Use regular functions for loaders due to binding


PinPoint.ItemsfromDomExtractor = function(targetName) {
  this.targetName = targetName;
}

// We'll need logic stating what className to use depending on sit:
// YouTube: "ytp-time-current"
// Vimeo: "box"
PinPoint.ItemsfromDomExtractor.prototype = {
  getTime : function(className) {
    var timeDivArray = document.getElementsbyClassName("ytp-time-current")
    var time = timeDivArray[0].innerHTML

  }
}

PinPoint.ItemsfromDomExtractor = function(targetName) {
  this.targetName = targetName;
}

// We'll need logic stating what className to use depending on sit:
// YouTube: "ytp-time-current"
// Vimeo: "box"

PinPoint.ItemsFromDomExtractor.prototype = {
  getTime : function(className) {
    var timeDivArray = document.getElementsbyClassName(className);
    var time = timeDivArray[0].innerHTML;
    return time;
  }
}

Add return value to ItemsFromDomExtractor and remove hard-coded className.


var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'gfycat.com',
    prepareImgLinks:function (callback) {
        $('a[href*="gfycat.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*gfycat.com\/(gifs\/)?(detail\/)?(\w+).*/, '$3');
            $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });
    }
});

var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
    name:'gfycat.com',
    prepareImgLinks:function (callback) {
        $('a[href*="gfycat.com/"]').one('mouseenter', function() {
            var link = $(this),
                gfyId = this.href.replace(/.*gfycat.com\/(..\/)?(gifs\/)?(detail\/)?(\w+).*/, '$4');
            $.get('https://gfycat.com/cajax/get/' + gfyId, function (data) {
                if (data && data.gfyItem) {
                    link.data().hoverZoomSrc = [options.zoomVideos ? data.gfyItem.webmUrl : data.gfyItem.gifUrl]
                    link.addClass('hoverZoomLink');
                    hoverZoom.displayPicFromElement(link);
                }
            });
        });
    }
});

Support for Lang in URL in Gfycat plugin


import DocumentArchive from './DocumentArchive'
import InMemoryDarBuffer from './InMemoryDarBuffer'

export default function loadArchive (rawArchive, config) {
  const archive = new DocumentArchive(
    // Note: this is a minimalistic Storage adapter with only `read()` implemented
    {
      read (_, cb) {
        cb(null, rawArchive)
      }
    },
    new InMemoryDarBuffer(),
    {},
    config
  )
  // Note: we are using a synchronous store here (in memory)
  // so this is actually synchronous
  archive.load(null, err => {
    if (err) {
      console.error(err)
    }
  })
  return archive
}

import DocumentArchive from './DocumentArchive'
import InMemoryDarBuffer from './InMemoryDarBuffer'

export default function loadArchive (rawArchive, config) {
  const archive = new DocumentArchive(
    // Note: this is a minimalistic Storage adapter with only `read()` implemented
    {
      read (_, cb) {
        cb(null, rawArchive)
      },
      write (_, __, cb) {
        cb()
      }
    },
    new InMemoryDarBuffer(),
    {},
    config
  )
  // Note: we are using a synchronous store here (in memory)
  // so this is actually synchronous
  archive.load(null, err => {
    if (err) {
      console.error(err)
    }
  })
  return archive
}

Add a writer to stub loaded archive.


var formManager = formManager || {};

var forms = {};

formManager.digestForms = function() {
    var key, form, formSelectorClass, targets;

    for (key in window.reforms) {
        form = window.reforms[key];
        forms[key] = form;
    }
};

formManager.getForm = function (name, opts) {
    var form = forms[name];
    opts = opts || {};
    var formKey = opts.key || "form-" + Date.now();
    var initial = opts.initial;
    var create = opts.create;
    var update = opts.update;
    var parent = opts.parent;
    return form;
};

formManager.digestForms();

module.exports = {
    getForm: formManager.getForm
};

var formManager = formManager || {};

var forms = {};

formManager.digestForms = function() {
    var key, form, formSelectorClass, targets;

    for (key in window.reforms) {
        form = window.reforms[key];
        forms[key] = form;
    }
};

formManager.getForm = function (name, opts) {
    var form = forms[name]
    //opts = opts || {};
    //var formKey = opts.key || "form-" + Date.now();
    //var initial = opts.initial;
    //var create = opts.create;
    //var update = opts.update;
    //var parent = opts.parent;
    //
    //if (opts.initial !== undefined) {
    //    var initial = JSON.parse(JSON.stringify(opts.initial)); // <-- Clone the initial
    //}

    if (form === undefined) {
        return form;
    }

    return JSON.parse(JSON.stringify(forms[name]));
};

formManager.digestForms();

module.exports = {
    getForm: formManager.getForm
};

Clone the form rather than edit the original


import React from 'react';
import { Link } from 'react-router';

const SignUpComplete = () => {
  return (

Signed up!

You can now <Link to='/login'>log in</Link> with your email address and passowrd.

  );
}

export default SignUpComplete;

import React from 'react';
import { Link } from 'react-router';

const SignUpComplete = () => {
  return (

Signed up!

You can now <Link to='/login'>log in</Link> with your email address and password.

  );
}

export default SignUpComplete;

Fix typo in notification about completing signup


(function(env) {
    env.ddg_spice_meta_cpan = function(api_result) {
        "use strict";

        if (!(api_result && api_result.author && api_result.version)) {
            return Spice.failed('meta_cpan');
        }
        var script = $('[src*="/js/spice/meta_cpan/"]')[0],
            source = $(script).attr("src"),
            query = decodeURIComponent(source.match(/meta_cpan\/([^\/]+)/)[1]),
            link = "search?q=" + encodeURIComponent(query),
            module_name = api_result.name;

        if (api_result.module && api_result.module.length > 0) {
            module_name = api_result.module[0].name;
            if (api_result.module[0].associated_pod) {
                link = "module/" + api_result.module[0].associated_pod;
            }
        }

        Spice.add({
            id: "meta_cpan",
            name: "Software",
            data: {
                title: module_name,
                subtitle: api_result.abstract,
                record_data: api_result,
                record_keys: ['author','version','description']
            },
            meta: {
                sourceName: "MetaCPAN",
                sourceUrl: 'https://metacpan.org/' + link
            },
            templates: {
                group: 'list',
                options: {
                    content: 'record',
                    moreAt: true
                }
            }
        });
    };
}(this));

(function(env) {
    env.ddg_spice_meta_cpan = function(api_result) {
        "use strict";

        if ( !api_result || api_result.hits.hits.length < 1 ) {
            return DDH.failed('meta_cpan');
        }

        Spice.add({
            id: "meta_cpan",
            name: "Software",
            data: {
                title: module_name,
                subtitle: api_result.abstract,
                record_data: api_result,
                record_keys: ['author','version','description']
            },
            meta: {
                sourceName: "MetaCPAN",
                sourceUrl: 'https://metacpan.org/' + link
            },
            templates: {
                group: 'list',
                options: {
                    content: 'record',
                    moreAt: true
                }
            }
        });
    };
}(this));

Remove old data retrieval, replace error condition


import Realm from 'realm';

export class NameNote extends Realm.Object {
  get data() {
    try {
      return JSON.parse(this._data);
    } catch {
      // swallow error, return a default
      return null;
    }
  }

  // Will throw if newValue is unable to be stringified
  set data(newValue) {
    this._data = JSON.stringify(newValue);
  }

  get patientEventID() {
    return this.patientEvent?.id;
  }

  toObject() {
    return {
      id: this.id,
      entryDate: this.entryDate.getTime(),
      data: this.data,
      nameID: this.name.id,
      patientEventID: this.patientEvent.id,
    };
  }
}

NameNote.schema = {
  name: 'NameNote',
  primaryKey: 'id',
  properties: {
    id: 'string',
    entryDate: { type: 'date', default: new Date() },
    _data: { type: 'string', optional: true },
    name: 'Name',
    patientEvent: 'PatientEvent',
  },
};

export default NameNote;

import Realm from 'realm';

export class NameNote extends Realm.Object {
  get data() {
    try {
      return JSON.parse(this._data);
    } catch {
      // swallow error, return a default
      return null;
    }
  }

  // Will throw if newValue is unable to be stringified
  set data(newValue) {
    this._data = JSON.stringify(newValue);
  }

  get patientEventID() {
    return this.patientEvent?.id;
  }

  toObject() {
    return {
      id: this.id,
      entryDate: this.entryDate.getTime(),
      data: this.data,
      nameID: this.name.id,
      patientEventID: this.patientEvent?.id,
    };
  }
}

NameNote.schema = {
  name: 'NameNote',
  primaryKey: 'id',
  properties: {
    id: 'string',
    entryDate: { type: 'date', default: new Date() },
    _data: { type: 'string', optional: true },
    name: 'Name',
    patientEvent: 'PatientEvent',
  },
};

export default NameNote;

Add crash prevention when a name not does not have a patient event


/* jslint node: true */
module.exports = function (grunt) {
  if (process.env.APPVEYOR_REPO_BRANCH !== 'master' || !process.env.APPVEYOR_REPO_TAG) {
    grunt.log.writeln('The release will only be created from a tag on the master branch.');
    return;
  }

  return {
    zip: {
      options: {
        archive: 'Exceptionless.UI.' + process.env.APPVEYOR_BUILD_VERSION + '.zip'
      },
      files: [
        {
          expand: true,
          cwd: 'dist/',
          src: ['**/*'],
          dest: './'
        }
      ]
    }
  };
};

/* jslint node: true */
module.exports = function () {
  return {
    zip: {
      options: {
        archive: 'Exceptionless.UI.' + process.env.APPVEYOR_BUILD_VERSION + '.zip'
      },
      files: [
        {
          expand: true,
          cwd: 'dist/',
          src: ['**/*'],
          dest: './'
        }
      ]
    }
  };
};

Create release artifacts on different branches


let React = require("react")
let {
  savedText,
  errorList,
  sizeClassNames,
  formGroupCx,
  label,
} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")

export default class extends React.Component {

  displayName = "Frig.friggingBootstrap.Text"

  static defaultProps = Object.assign(require("../default_props.js"))

  _inputHtml() {
    return Object.assign({}, this.props.inputHtml, {
      className: cx(this.props.className, "form-control"),
      valueLink: {
        value: this.props.valueLink.value || "",
      },
      rows: this.props.rows,
    })
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        div({className: "controls"},
          textarea(this._inputHtml()),
        ),
        savedText({
          saved: this.props.saved && this.props.modified,
        }),
        errorList(this.props.errors),
      ),
    )
  }

}

let React = require("react")
let {
  savedText,
  errorList,
  sizeClassNames,
  formGroupCx,
  label,
} = require("../util.js")
let {div, textarea} = React.DOM
let cx = require("classnames")

export default class extends React.Component {

  displayName = "Frig.friggingBootstrap.Text"

  static defaultProps = Object.assign(require("../default_props.js"))

  _inputHtml() {
    return Object.assign({}, this.props.inputHtml, {
      className: cx(this.props.className, "form-control"),
      valueLink: {
        value: this.props.valueLink.value || "",
        requestChange: this.props.valueLink.requestChange,
      },
      rows: this.props.rows,
    })
  }

  render() {
    return div({className: cx(sizeClassNames(this.props))},
      div({className: formGroupCx(this.props)},
        label(this.props),
        div({className: "controls"},
          textarea(this._inputHtml()),
        ),
        savedText({
          saved: this.props.saved && this.props.modified,
        }),
        errorList(this.props.errors),
      ),
    )
  }

}

Fix Text From Erroring When No requestChange


'use babel';
'use strict';

import CommandArray from './CommandArray';

export default class CommandRegistry extends Map
{
	constructor()
	{
		super();
	}

	// Complete registration of command and add to CommandRegistry storage
	register(command, key)
	{
		if (super.has(command.name)) throw new Error(`A command with the name "${command.name}" already exists.`);
		command.register();
		super.set(key, command);
	}

	commandArray()
	{
		return CommandArray.from(this);
	}
}

'use babel';
'use strict';

import CommandArray from './CommandArray';

export default class CommandRegistry extends Map
{
	constructor()
	{
		super();
	}

	// Complete registration of command and add to CommandRegistry storage
	register(command, key)
	{
		if (super.has(command.name)) throw new Error(`A command with the name "${command.name}" already exists.`);
		command.register();
		super.set(key, command);
		this.forEach(a =>
		{
			a.aliases.forEach(b =>
			{
				let duplicates = this.commandArray().filter(c => c.aliases.includes(b) && c !== a);
				if (duplicates.length > 0)
				{
					throw new Error(`Commands may not share aliases: ${duplicates[0].name}, ${a.name} (shared alias: ${b})`);
				}
			});
		});
	}

	commandArray()
	{
		return CommandArray.from(this);
	}
}

Add error on shared command aliases


import EditFormRoute from 'prototype-ember-cli-application/routes/edit-form';
import Model from 'prototype-ember-cli-application/models/employee';

export default EditFormRoute.extend({
    view: Model.Views.EmployeeeE,
    modelTypeKey: 'employee'
});

import EditFormRoute from 'prototype-ember-cli-application/routes/edit-form';
import Model from 'prototype-ember-cli-application/models/employee';

export default EditFormRoute.extend({
    view: Model.Views.EmployeeE,
    modelTypeKey: 'employee'
});

Fix Edit Form opening (fixed a typo)


var assert = require('assert');
var fs = require('fs');
var cgbiToPng = require('../index');
var tmp = require('tmp');

var filePath = './test/cgbi-image.png';
var tempFilePath = tmp.tmpNameSync();

describe('convert',function(){
    it('should convert cgbi to png',function(done){
        cgbiToPng(fs.createReadStream(filePath),function(err,imageStream){
            assert.ifError(err);
            assert.ok(imageStream);
            imageStream
                .pipe(fs.createWriteStream(tempFilePath))
                .on('error',done)
                .on('close',function(){
                    fs.unlink(tempFilePath);
                    done();
                })
        })
    })

    it('should convert cgbi to png (buffers)',function(){
        var cgbiBuffer = fs.readFileSync(filePath);
        var pngBuffer = cgbiToPng.revert(cgbiBuffer);
        assert.ok(pngBuffer);
        assert.notEqual(pngBuffer.toString(),cgbiBuffer.toString())
    })
})

var assert = require('assert');
var fs = require('fs');
var cgbiToPng = require('../index');
var tmp = require('tmp');

var filePath = './test/cgbi-image.png';
var PNGFilePath = './test/png-image.png';
var nonPNGFilePath = './test/index.js';
var tempFilePath = tmp.tmpNameSync();

describe('convert',function(){
    it('should convert cgbi to png',function(done){
        cgbiToPng(fs.createReadStream(filePath),function(err,imageStream){
            assert.ifError(err);
            assert.ok(imageStream);
            imageStream
                .pipe(fs.createWriteStream(tempFilePath))
                .on('error',done)
                .on('close',function(){
                    fs.unlink(tempFilePath);
                    done();
                })
        })
    })

    it('should convert cgbi to png (buffers)',function(){
        var cgbiBuffer = fs.readFileSync(filePath);
        var pngBuffer = cgbiToPng.revert(cgbiBuffer);
        assert.ok(pngBuffer);
        assert.notEqual(pngBuffer.toString(),cgbiBuffer.toString())
    })

    it('should leave png untouched',function(){
        var pngBuffer = fs.readFileSync(PNGFilePath);
        var pngBuffer2 = cgbiToPng.revert(pngBuffer);
        assert.ok(pngBuffer2);
        assert.equal(pngBuffer.toString(),pngBuffer2.toString())
    })

    it('should fail on non png files',function(){
        var nonPNGBuffer = fs.readFileSync(nonPNGFilePath);
        assert.throws(function(){
            cgbiToPng.revert(nonPNGBuffer);
        },'not a png file')
    })
})

Add test for non cgbi files


'use strict';

const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');

exports.expressCreateServer = (hookName, args, cb) => {
  // The Etherpad client side sends information about how a disconnect happened
  args.app.post('/ep/pad/connection-diagnostic-info', (req, res) => {
    new formidable.IncomingForm().parse(req, (err, fields, files) => {
      clientLogger.info(`DIAGNOSTIC-INFO: ${fields.diagnosticInfo}`);
      res.end('OK');
    });
  });

  // The Etherpad client side sends information about client side javscript errors
  args.app.post('/jserror', (req, res) => {
    new formidable.IncomingForm().parse(req, (err, fields, files) => {
      let data;
      try {
        data = JSON.parse(fields.errorInfo);
      } catch (e) {
        return res.end();
      }
      clientLogger.warn(`${data.msg} --`, data);
      res.end('OK');
    });
  });

  // Provide a possibility to query the latest available API version
  args.app.get('/api', (req, res) => {
    res.json({currentVersion: apiHandler.latestApiVersion});
  });

  return cb();
};

'use strict';

const log4js = require('log4js');
const clientLogger = log4js.getLogger('client');
const formidable = require('formidable');
const apiHandler = require('../../handler/APIHandler');

exports.expressCreateServer = (hookName, args, cb) => {
  // The Etherpad client side sends information about how a disconnect happened
  args.app.post('/ep/pad/connection-diagnostic-info', (req, res) => {
    new formidable.IncomingForm().parse(req, (err, fields, files) => {
      clientLogger.info(`DIAGNOSTIC-INFO: ${fields.diagnosticInfo}`);
      res.end('OK');
    });
  });

  const parseJserrorForm = async (req) => await new Promise((resolve, reject) => {
    const form = new formidable.IncomingForm();
    form.on('error', (err) => reject(err));
    form.parse(req, (err, fields) => err != null ? reject(err) : resolve(fields.errorInfo));
  });

  // The Etherpad client side sends information about client side javscript errors
  args.app.post('/jserror', (req, res, next) => {
    (async () => {
      const data = JSON.parse(await parseJserrorForm(req));
      clientLogger.warn(`${data.msg} --`, data);
      res.end('OK');
    })().catch((err) => next(err || new Error(err)));
  });

  // Provide a possibility to query the latest available API version
  args.app.get('/api', (req, res) => {
    res.json({currentVersion: apiHandler.latestApiVersion});
  });

  return cb();
};

Refactor to handle errors better


import { createBrowserHistory, createHashHistory } from 'history'

export default function configureHistory() {
  return window.matchMedia('(display-mode: standalone)').matches
    ? createHashHistory()
    : createBrowserHistory()
}

import { createBrowserHistory, createHashHistory } from 'history'

/**
 * When app is launched from home screen on Android - we need to use hash history.
 * @see https://ayastreb.me/react-router-in-home-screen-pwa/
 */
export default function configureHistory() {
  return window.matchMedia('(display-mode: standalone)').matches
    ? createHashHistory()
    : createBrowserHistory()
}

Add home screen issue note


export default function deprecationWarning(oldname, newname, link) {
  if (process.env.NODE_ENV !== 'production') {
    let message = `${oldname} is deprecated. Use ${newname} instead.`;
    console.warn(message);

    if (link) {
      console.warn(`You can read more about it here ${link}`);
    }
  }
}

function warn(message) {
  if (window.console && (typeof console.warn === 'function')) {
    console.warn(message);
  }
}

export default function deprecationWarning(oldname, newname, link) {
  if (process.env.NODE_ENV !== 'production') {
    let message = `${oldname} is deprecated. Use ${newname} instead.`;
    warn(message);

    if (link) {
      warn(`You can read more about it here ${link}`);
    }
  }
}

Check for console before using console.warn


const requireAll = require('require-all');
const express = require('express');
const controllers = requireAll(__dirname+'/../controllers/resources/');

var router = new express.Router();

Object.keys(controllers).forEach(function(resource) {
  router.get('/' + resource, controllers[resource].index);
  router.post('/' + resource, controllers[resource].create);
  router.get('/' + resource + '/:id', controllers[resource].show);
  router.put('/' + resource + '/:id', controllers[resource].update);
  router.delete('/' + resource + '/:id', controllers[resource].destroy);
});

module.exports = router;

const requireAll = require('require-all');
const express = require('express');
const controllers = requireAll(__dirname+'/../controllers/resources/');

var router = new express.Router();
console.log(Object.keys(controllers));

Object.keys(controllers).forEach(function(resource) {
  router.get('/' + resource, controllers[resource].index);
  router.post('/' + resource, controllers[resource].create);
  router.get('/' + resource + '/:id', controllers[resource].show);
  router.put('/' + resource + '/:id', controllers[resource].update);
  router.delete('/' + resource + '/:id', controllers[resource].destroy);
});

module.exports = router;

Rename controller files and use correct resource routes


import Storage from 'store2';

/**
 * @param {String} ns Local storage namespace
 * @param {String[]} persistMutations
 * @return {function(...[*]=)} Vuex plugin
 */
export default function persistFactory(ns, persistMutations) {
  const storage = Storage.namespace(ns);

  return function(store) {
    const load = () => {
      persistMutations.forEach(mutation => {
        if (storage.has(mutation)) {
          store.commit(mutation, storage(mutation));
        }
      });
    };

    window.addEventListener('focus', load);
    load();

    store.subscribe(mutation => {
      if (
        persistMutations.indexOf(mutation.type) >= 0 &&
        storage(mutation.type) !== mutation.payload
      ) {
        storage(mutation.type, mutation.payload);
      }
    });
  };
}

import Storage from 'store2';

/**
 * @param {String} ns Local storage namespace
 * @param {String[]} persistMutations
 * @return {function(...[*]=)} Vuex plugin
 */
export default function persistFactory(ns, persistMutations) {
  const storage = Storage.namespace(ns);

  return function(store) {
    const load = () => {
      persistMutations.forEach(mutation => {
        if (storage.has(mutation)) {
          const payloads = /^ADD/.test(mutation) ? storage(mutation) : [storage(mutation)];

          payloads.forEach(payload => store.commit(mutation, payload));
        }
      });
    };

    window.addEventListener('focus', load);
    load();

    store.subscribe(mutation => {
      if (persistMutations.indexOf(mutation.type) >= 0) {
        let oldValue = storage(mutation.type);

        // If ADD vs SET, then we'll keep a list of payloads
        if (/^ADD/.test(mutation.type)) {
          oldValue = oldValue || [];
          oldValue.push(mutation.payload);
          storage(mutation.type, oldValue);
        } else if (oldValue !== mutation.payload) {
          storage(mutation.type, mutation.payload);
        }
      }
    });
  };
}

Enable list support in state persist helper