<commit_before>import * as path from 'path';
import {childProcess, fs} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
import {AwaitableObservable} from 'esnext-async';

export default class {
  constructor(basePath) {
    this.basePath = path.resolve(basePath);
  }

  async create() {
    await fse.mkdirs(this.basePath);
  }

  async exec(command, params) {
    try {
      const {stdout} = await childProcess.execFile(command, params, {
        cwd: this.path()
      });
      return stdout.trim();
    } catch ({stderr}) {
      throw new Error(stderr.trim());
    }
  }

  execJs(code) {
    return new Promise((resolve, reject) => {
      const child = childProcess.spawn('dist-es6-run');
      child.stdin.write(code);
      child.stdin.end();

      let stdoutOutput = '';
      child.stdout.on('data', (output) => {
        stdoutOutput += output;
      });

      let stderrOutput = '';
      child.stderr.on('data', (output) => {
        stderrOutput += output;
      });

      child.on('close', (code) => {
        if (code === 0) {
          resolve(stdoutOutput.trim());
        } else {
          reject(stderrOutput.trim());
        }
      });
    });
  }

  path(...components) {
    return path.resolve(this.basePath, ...components);
  }

  async remove() {
    await fse.remove(this.path());
  }

  spawn(command, params) {
    const child = childProcess.spawn(command, params, {cwd: this.path()});
    return new AwaitableObservable((observer) => {
      child.stdout.on('data', (data) => {
        observer.next(data.toString());
      });
      child.stderr.on('data', (data) => {
        observer.next(data.toString());
      });
    });
  }

  async write(files) {
    for (const [filePath, fileContents] of Object.entries(files)) {
      const absoluteFilePath = this.path(filePath);

      await fse.ensureFile(absoluteFilePath);

      if (typeof fileContents === 'object') {
        await fse.writeJson(absoluteFilePath, fileContents);
      } else {
        const reindentedFileContents = fileContents
          .split('\n')
          .filter((line, index, array) =>
            index !== 0 && index !== array.length - 1 || line.trim() !== '')
          .reduce(({indentation, contents}, line) => {
            const whitespaceToRemove = Number.isInteger(indentation) ?
              indentation :
              line.match(/^\s*/)[0].length;
            return {
              indentation: whitespaceToRemove,
              contents: `${contents}${line.slice(whitespaceToRemove)}\n`
            };
          }, {contents: ''}).contents;
        await fs.writeFile(absoluteFilePath, reindentedFileContents);
      }
    }
  }
}
<commit_msg>Fix linting error<commit_after>import * as path from 'path';
import {childProcess, fs} from 'node-promise-es6';
import * as fse from 'fs-extra-promise-es6';
import {AwaitableObservable} from 'esnext-async';

export default class {
  constructor(basePath) {
    this.basePath = path.resolve(basePath);
  }

  async create() {
    await fse.mkdirs(this.basePath);
  }

  async exec(command, params) {
    try {
      const {stdout} = await childProcess.execFile(command, params, {
        cwd: this.path()
      });
      return stdout.trim();
    } catch ({stderr}) {
      throw new Error(stderr.trim());
    }
  }

  execJs(code) {
    return new Promise((resolve, reject) => {
      const child = childProcess.spawn('dist-es6-run');
      child.stdin.write(code);
      child.stdin.end();

      let stdoutOutput = '';
      child.stdout.on('data', (output) => {
        stdoutOutput += output;
      });

      let stderrOutput = '';
      child.stderr.on('data', (output) => {
        stderrOutput += output;
      });

      child.on('close', (exitCode) => {
        if (exitCode === 0) {
          resolve(stdoutOutput.trim());
        } else {
          reject(stderrOutput.trim());
        }
      });
    });
  }

  path(...components) {
    return path.resolve(this.basePath, ...components);
  }

  async remove() {
    await fse.remove(this.path());
  }

  spawn(command, params) {
    const child = childProcess.spawn(command, params, {cwd: this.path()});
    return new AwaitableObservable((observer) => {
      child.stdout.on('data', (data) => {
        observer.next(data.toString());
      });
      child.stderr.on('data', (data) => {
        observer.next(data.toString());
      });
    });
  }

  async write(files) {
    for (const [filePath, fileContents] of Object.entries(files)) {
      const absoluteFilePath = this.path(filePath);

      await fse.ensureFile(absoluteFilePath);

      if (typeof fileContents === 'object') {
        await fse.writeJson(absoluteFilePath, fileContents);
      } else {
        const reindentedFileContents = fileContents
          .split('\n')
          .filter((line, index, array) =>
            index !== 0 && index !== array.length - 1 || line.trim() !== '')
          .reduce(({indentation, contents}, line) => {
            const whitespaceToRemove = Number.isInteger(indentation) ?
              indentation :
              line.match(/^\s*/)[0].length;
            return {
              indentation: whitespaceToRemove,
              contents: `${contents}${line.slice(whitespaceToRemove)}\n`
            };
          }, {contents: ''}).contents;
        await fs.writeFile(absoluteFilePath, reindentedFileContents);
      }
    }
  }
}
<|endoftext|>


<commit_before>export {
  linear as easeLinear
} from "./linear";

export {
  quadInOut as easeQuad,
  quadIn as easeQuadIn,
  quadOut as easeQuadOut,
  quadInOut as easeQuadInOut
} from "./quad";

export {
  cubicInOut as easeCubic,
  cubicIn as easeCubicIn,
  cubicOut as easeCubicOut,
  cubicInOut as easeCubicInOut
} from "./cubic";

export {
  polyInOut as easePoly,
  polyIn as easePolyIn,
  polyOut as easePolyOut,
  polyInOut as easePolyInOut
} from "./poly";

export {
  sinInOut as easeSin,
  sinIn as easeSinIn,
  sinOut as easeSinOut,
  sinInOut as easeSinInOut
} from "./sin";

export {
  expInOut as easeExp,
  expIn as easeExpIn,
  expOut as easeExpOut,
  expInOut as easeExpInOut
} from "./exp";

export {
  circleInOut as easeCircle,
  circleIn as easeCircleIn,
  circleOut as easeCircleOut,
  circleInOut as easeCircleInOut
} from "./circle";

export {
  bounceOut as easeBounce,
  bounceIn as easeBounceIn,
  bounceOut as easeBounceOut,
  bounceInOut as easeBounceInOut
} from "./bounce";

export {
  backInOut as easeBack,
  backIn as easeBackIn,
  backOut as easeBackOut,
  backInOut as easeBackInOut
} from "./back";

export {
  elasticOut as easeElastic,
  elasticIn as easeElasticIn,
  elasticOut as easeElasticOut,
  elasticInOut as easeElasticInOut
} from "./elastic";
<commit_msg>Use exact paths in imports. d3/d3#3265<commit_after>export {
  linear as easeLinear
} from "./linear.js";

export {
  quadInOut as easeQuad,
  quadIn as easeQuadIn,
  quadOut as easeQuadOut,
  quadInOut as easeQuadInOut
} from "./quad.js";

export {
  cubicInOut as easeCubic,
  cubicIn as easeCubicIn,
  cubicOut as easeCubicOut,
  cubicInOut as easeCubicInOut
} from "./cubic.js";

export {
  polyInOut as easePoly,
  polyIn as easePolyIn,
  polyOut as easePolyOut,
  polyInOut as easePolyInOut
} from "./poly.js";

export {
  sinInOut as easeSin,
  sinIn as easeSinIn,
  sinOut as easeSinOut,
  sinInOut as easeSinInOut
} from "./sin.js";

export {
  expInOut as easeExp,
  expIn as easeExpIn,
  expOut as easeExpOut,
  expInOut as easeExpInOut
} from "./exp.js";

export {
  circleInOut as easeCircle,
  circleIn as easeCircleIn,
  circleOut as easeCircleOut,
  circleInOut as easeCircleInOut
} from "./circle.js";

export {
  bounceOut as easeBounce,
  bounceIn as easeBounceIn,
  bounceOut as easeBounceOut,
  bounceInOut as easeBounceInOut
} from "./bounce.js";

export {
  backInOut as easeBack,
  backIn as easeBackIn,
  backOut as easeBackOut,
  backInOut as easeBackInOut
} from "./back.js";

export {
  elasticOut as easeElastic,
  elasticIn as easeElasticIn,
  elasticOut as easeElasticOut,
  elasticInOut as easeElasticInOut
} from "./elastic.js";
<|endoftext|>


<commit_before>var Compressor = require('./compressor');
var Decompressor = require('./decompressor');

var lzbase62 = {
  /**
   * Compress data to a base 62(0-9a-zA-Z) encoded string
   *
   * @param {string|Buffer} data Input data
   * @param {Object=} [options] Options
   * @return {string} Compressed data
   */
  compress: function(data, options) {
    return new Compressor(options).compress(data);
  },
  /**
   * Decompress data from a base 62(0-9a-zA-Z) encoded string
   *
   * @param {string} data Input data
   * @param {Object=} [options] Options
   * @return {string} Decompressed data
   */
  decompress: function(data, options) {
    return new Decompressor(options).decompress(data);
  }
};

module.exports = lzbase62;
<commit_msg>Add `version` property<commit_after>var Compressor = require('./compressor');
var Decompressor = require('./decompressor');

exports.version = require('../package.json').version;

/**
 * Compress data to a base 62(0-9a-zA-Z) encoded string
 *
 * @param {string|Buffer} data Input data
 * @param {Object=} [options] Options
 * @return {string} Compressed data
 */
exports.compress = function(data, options) {
  return new Compressor(options).compress(data);
};

/**
 * Decompress data from a base 62(0-9a-zA-Z) encoded string
 *
 * @param {string} data Input data
 * @param {Object=} [options] Options
 * @return {string} Decompressed data
 */
exports.decompress = function(data, options) {
  return new Decompressor(options).decompress(data);
};
<|endoftext|>


<commit_before>import SVG from 'svg.js'
import { daysInMonth } from './helper'

const gcg = {
  id: 'gcg',
  font: {
    family: 'Helvetica',
    size: 9
  },
  limit: 52,
  padding: 2,
  boxSize: 8
}

const GCGraph = id => {
  var element = document.createElement('div')
  element.innerHTML = 'Summary'
  element.id = id

  return element
}

const drawGCGraph = ({ id, font, boxSize, boxes, limit, padding }) => {
  // Canvas
  const draw = SVG(id).size('100%', '100%')

  // Global
  const boxSizePadding = boxSize + padding
  let offsetX = 0
  const offsetY = 26

  // Days
  const dayOffsetX = offsetX
  const dayOffsetY = offsetY
  let dayY = boxSizePadding
  const drawDays = ['Mon', 'Wed', 'Fri']
  drawDays.map((day, index) => {
    let text = draw.text(day)
    text.font(font).move(dayOffsetX, dayOffsetY + dayY)
    dayY += boxSizePadding * 2
  })
  offsetX += 26

  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = new Date().getMonth()

  // Months
  const monthOffsetX = offsetX
  const monthOffsetY = 10
  const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  const months = monthNames.map((name, i) => ({ name, days: daysInMonth(i, currentYear) }))

  const slideMonths = months.slice(currentMonth, 12).concat(months.slice(0, currentMonth))

  let monthIndex = 0
  let daysInMonthSum = 0
  slideMonths.map(month => {
    const monthX = Math.floor(daysInMonthSum / 7) * boxSizePadding
    let text = draw.text(slideMonths[monthIndex].name)
    text.font(font).move(monthOffsetX + monthX, monthOffsetY)

    // next
    monthIndex++
    daysInMonthSum += month.days
  })

  // Boxes
  const boxOffsetX = offsetX
  const boxOffsetY = offsetY
  let index = 0
  boxes.map(box => {
    // move
    const i = boxOffsetX + boxSizePadding * (index % limit)
    const j = boxOffsetY + boxSizePadding * Math.floor(index / limit)

    // shape
    draw.rect(boxSize, boxSize).move(i, j).fill(box.color)

    // next
    index++
  })
}

document.body.appendChild(GCGraph(gcg.id))
const MAX_DAY = 364
let boxes = new Array(MAX_DAY)
for (let i = 0; i < MAX_DAY; i++) {
  boxes.push({
    color: ['red', 'green', 'blue'][Math.floor(Math.random() * 3)]
  })
}

drawGCGraph(
  Object.assign(gcg, {
    boxes
  })
)
<commit_msg>refactor(graph): Use index<commit_after>import SVG from 'svg.js'
import { daysInMonth } from './helper'

const gcg = {
  id: 'gcg',
  font: {
    family: 'Helvetica',
    size: 9
  },
  limit: 52,
  padding: 2,
  boxSize: 8
}

const GCGraph = id => {
  var element = document.createElement('div')
  element.innerHTML = 'Summary'
  element.id = id

  return element
}

const drawGCGraph = ({ id, font, boxSize, boxes, limit, padding }) => {
  // Canvas
  const draw = SVG(id).size('100%', '100%')

  // Global
  const boxSizePadding = boxSize + padding
  let offsetX = 0
  const offsetY = 26

  // Days
  const dayOffsetX = offsetX
  const dayOffsetY = offsetY
  let dayY = boxSizePadding
  const drawDays = ['Mon', 'Wed', 'Fri']
  drawDays.map((day, index) => {
    let text = draw.text(day)
    text.font(font).move(dayOffsetX, dayOffsetY + dayY)
    dayY += boxSizePadding * 2
  })
  offsetX += 26

  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = new Date().getMonth()

  // Months
  const monthOffsetX = offsetX
  const monthOffsetY = 10
  const monthNames = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  const months = monthNames.map((name, i) => ({ name, days: daysInMonth(i, currentYear) }))

  const slideMonths = months.slice(currentMonth, 12).concat(months.slice(0, currentMonth))

  let daysInMonthSum = 0
  slideMonths.map((month, index) => {
    const monthX = Math.floor(daysInMonthSum / 7) * boxSizePadding
    let text = draw.text(slideMonths[index].name)
    text.font(font).move(monthOffsetX + monthX, monthOffsetY)

    // next
    daysInMonthSum += month.days
  })

  // Boxes
  const boxOffsetX = offsetX
  const boxOffsetY = offsetY
  boxes.map((box, index) => {
    if (index < 300) console.log(index)
    // move
    const i = boxOffsetX + boxSizePadding * (index % limit)
    const j = boxOffsetY + boxSizePadding * Math.floor(index / limit)

    // shape
    draw.rect(boxSize, boxSize).move(i, j).fill(box.color)
  })
}

document.body.appendChild(GCGraph(gcg.id))
const MAX_DAY = 364
let boxes = []
for (let i = 0; i < MAX_DAY; i++) {
  boxes.push({
    color: ['red', 'green', 'blue'][Math.floor(Math.random() * 3)]
  })
}

drawGCGraph(
  Object.assign(gcg, {
    boxes
  })
)
<|endoftext|>


<commit_before>(function (window, io, $, _, Backbone, location, app) {
    "use strict";

    var ID = "id",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        //For now, we are assuming that socket.io is hosted locally.
        return "";
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                new Date()
            ];

        _.each(args, function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(url, {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "match origin protocol": true,
                "force new connection":true
            }));
        }
        catch (e) {
            setTimeout(function () {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function () {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function () {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function (socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb,
                    device = window.device || {};

                cb = undefined;

                socket.emit("middle-initialize", {
                    id:app.middle.id,
                    uuid:device.uuid,
                    name:device.name,
                    platform:device.platform,
                    version:device.version,
                    cordova:device.cordova
                });

                app.log = function () {
                    return log(socket, "info", arguments);
                };
                app.debug = function () {
                    return log(socket, "debug", arguments);
                };
                app.error = function () {
                    return log(socket, "error", arguments);
                };

                app.log("middle connected");

                return _cb && _cb(socket);
            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        if (app.middle.disable) {
            return next();
        }

        app.store("middle", function (store) {
            store.get(ID, function (id) {
                app.middle.id = (id && id.id) || app.utils.uuid();

                if (!id) {
                    store.save(ID, app.middle.id);
                }

                return openSocket(function (socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };
                    app.middle.emit = emitter(socket);

                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["jolira-app"]);
<commit_msg>adding stop/start features<commit_after>(function (window, io, $, _, Backbone, location, app) {
    "use strict";

    var ID = "id",
        watchedEvents = {};

    app.middle = app.middle || {};

    function getServerURL() {
        //For now, we are assuming that socket.io is hosted locally.
        return "";
    }

    function convert(arg) {
        try {
            return JSON.stringify(arg);
        }
        catch (e) {
            var simpified = {};

            _.each(arg, function (entry, key) {
                if (entry !== window) {
                    simpified[key] = entry;
                }
            });

            return convert(simpified);
        }
    }

    function log(socket, level, _args) {
        var args = Array.prototype.slice.call(_args),
            params = [
                "log",
                level,
                new Date()
            ];

        _.each(args, function (arg) {
            var param = convert(arg);

            params.push(param);
        });

        return socket.emit.apply(socket, params);
    }

    function emitter(socket) {
        return function () {
            return socket.emit.apply(socket, arguments);
        };
    }

    function connect(url, cb) {
        try {
            return cb(io.connect(url, {
                "reconnection limit":4001, // four second max delay
                "max reconnection attempts":Infinity,
                "match origin protocol": true,
                "force new connection":true
            }));
        }
        catch (e) {
            setTimeout(function () {
                connect(url, cb);
            }, 500);

            return app.error("io.connect exception", e);
        }
    }

    function openSocket(cb) {
        var tryAgain = function () {
                if (cb) {
                    app.log("middle trying to connect again");
                    setTimeout(function () {
                        openSocket(cb);
                    }, 500);
                }
            },
            app_log = app.log,
            app_debug = app.debug,
            app_error = app.error,
            url = getServerURL();

        return connect(url, function (socket) {
            socket.on('error', function (err) {
                app.error("middle socket error", err);
                tryAgain();
            });
            socket.on('connecting', function () {
                return app.log("middle connecting");
            });
            socket.on('connect_failed', function (err) {
                app.error("connect_failed", err);
                tryAgain();
            });
            socket.on('reconnect', function () {
                return app.log("middle reconnect");
            });
            socket.on('reconnecting', function () {
                return app.log("middle reconnecting");
            });
            socket.on('connect', function () {
                app.middle.connected = true;

                var _cb = cb,
                    device = window.device || {};

                cb = undefined;

                socket.emit("middle-initialize", {
                    id:app.middle.id,
                    uuid:device.uuid,
                    name:device.name,
                    platform:device.platform,
                    version:device.version,
                    cordova:device.cordova
                });

                app.log = function () {
                    return log(socket, "info", arguments);
                };
                app.debug = function () {
                    return log(socket, "debug", arguments);
                };
                app.error = function () {
                    return log(socket, "error", arguments);
                };

                app.log("middle connected");

                return _cb && _cb(socket);
            });
            socket.on('disconnect', function () {
                app.middle.connected = false;

                app.log = app_log;
                app.debug = app_debug;
                app.error = app_error;
                app.middle.trigger("disconnect", app.middle.id);

                return app.log("disconnected", app.middle.id);
            });
        });
    }

    app.starter.$(function (next) {
        if (app.middle.disable) {
            return next();
        }

        app.store("middle", function (store) {
            store.get(ID, function (id) {
                app.middle.id = (id && id.id) || app.utils.uuid();

                if (!id) {
                    store.save(ID, app.middle.id);
                }

                var bindSocketListeners = function(socket) {
                    app.middle.bind = app.middle.on = app.middle.on || function (event, callback, context) {
                        var events = event.split(/\s+/);

                        _.each(events, function (event) {
                            if (!watchedEvents[event]) {
                                watchedEvents[event] = true;
                                socket.on(event, function () {
                                    var args = Array.prototype.slice.call(arguments);

                                    args.unshift(event);

                                    return app.middle.trigger.apply(app.middle, args);
                                });
                            }
                        });

                        Backbone.Events.on.call(app.middle, event, callback, context);
                    };
                    app.middle.unbind = app.middle.off = app.middle.off || function () {
                        Backbone.Events.off.apply(app.middle, arguments);
                    };
                    app.middle.trigger = app.middle.trigger = app.middle.trigger || function () {
                        Backbone.Events.trigger.apply(app.middle, arguments);
                    };

                    app.middle.stop = function() {
                        console.log("disconnect");
                        socket.disconnect();
                    };

                    app.middle.restart = function() {
                        console.log("restart");
                        if(socket) {
                            socket.connect();
                        } else {
                            openSocket(function (socket) {
                                bindSocketListeners(socket);
                            });
                        }
                    };

                    app.middle.emit = emitter(socket);
                };

                return openSocket(function (socket) {
                    bindSocketListeners(socket);
                    return next();
                });
            });
        });
    });
})(window, window.io, $, _, Backbone, window.location, window["jolira-app"]);
<|endoftext|>


<commit_before>const defaultBeforeFetch = ({ action }) => Promise.resolve({ action });
const defaultAfterFetch = ({ action, result }) => Promise.resolve({ action, result });
const rejectHandler = ({ action, error }) => Promise.reject({ action, error });

function hasOwn(obj, ...properties) {
  return properties.every(p => obj.hasOwnProperty(p));
}

function noop() {}

/**
 * Create a fetch middleware
 *
 * @param {object} options     Options for creating fetch middleware
 *   @param  {function} beforeFetch Injection point before sending request, it should return a Promise
 *   @param  {function} afterFetch  Injection point after receive response, it should return a Promise
 *   @param  {function} onReject    Injection point when anything goes wrong, it should return a Promise
 * @param {bool}   promiseMode Enable promise mode, will not check action have certain keys
 * @return {function}
 */
export default function createFetchMiddleware(options = {}, promiseMode = false) {
  const { beforeFetch = defaultBeforeFetch, afterFetch = defaultAfterFetch, onReject = rejectHandler } = options;
  return () => (next = noop) => action => {
    if (!promiseMode && (!action.url || !action.types)) {
      return next(action);
    }

    if (promiseMode && !action.url) {
      throw new Error('[fetch-middleware] Missing required key: `url`');
    }

    const [loadingType, successType, failureType] = action.types;

    if (loadingType) {
      try {
        next({
          ...action,
          type: loadingType,
        });
      } catch (err) {
        console.error(`[fetch-middleware] Uncaught error while dispatching \`${loadingType}\`\n`, err.stack);
      }
    }

    let beforeFetchResult;
    try {
      beforeFetchResult = beforeFetch({ action });
    } catch (err) {
      throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
    }

    if (!(beforeFetchResult instanceof Promise)) {
      throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:',
                          beforeFetchResult);
    }

    return beforeFetchResult
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action')) {
        console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .then(
      ({ action }) => {
        const { url, types, ...options } = action; // eslint-disable-line
        return fetch(url, options).then(
          result => {
            return Promise.resolve({
              action,
              result,
            });
          },
          err => {
            return Promise.reject({
              action,
              error: err,
            });
          }
        );
      }
    )
    .then(
      ({ action, result }) => {
        let afterFetchResult;
        try {
          afterFetchResult = afterFetch({ action, result });
        } catch (err) {
          console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
        }

        if (!(afterFetchResult instanceof Promise)) {
          console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
          return Promise.reject();
        }

        return afterFetchResult;
      }
    )
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action', 'result')) {
        console.error('[fetch-middleware] `afterFetch` should resolve an object ' +
                      'containing `action` and `result` key, instead got',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .catch(err => {
      if (err instanceof Error || typeof err !== 'object' || !hasOwn(err, 'action', 'error')) {
        return onReject({
          action,
          error: err,
        });
      }

      return onReject(err);
    })
    .then(
      ({ action, result }) => {
        try {
          next({
            ...action,
            payload: result,
            type: successType,
          });
        } catch (err) {
          console.error(`[fetch-middleware] Uncaught error while dispatching \`${successType}\`\n`, err.stack);
        }

        return Promise.resolve(result);
      }
    )
    .catch(
      ({ action, error }) => {
        if (failureType) {
          try {
            next({
              ...action,
              type: failureType,
              error,
            });
          } catch (err) {
            console.error(`[fetch-middleware] Uncaught error while dispatching \`${failureType}\`\n`, err.stack);
          }
        } else {
          // only reject when no `failureType` is provided, which means errors
          // are probably not handled in reducer
          return Promise.reject(error);
        }
      }
    );
  };
}

export { applyFetchMiddleware } from './applyFetchMiddleware';
<commit_msg>fix: solid promise mode<commit_after>const defaultBeforeFetch = ({ action }) => Promise.resolve({ action });
const defaultAfterFetch = ({ action, result }) => Promise.resolve({ action, result });
const rejectHandler = ({ action, error }) => Promise.reject({ action, error });

function hasOwn(obj, ...properties) {
  return properties.every(p => obj.hasOwnProperty(p));
}

function noop() {}

/**
 * Create a fetch middleware
 *
 * @param {object} options     Options for creating fetch middleware
 *   @param  {function} beforeFetch Injection point before sending request, it should return a Promise
 *   @param  {function} afterFetch  Injection point after receive response, it should return a Promise
 *   @param  {function} onReject    Injection point when anything goes wrong, it should return a Promise
 * @param {bool}   promiseMode Enable promise mode, will not check action have certain keys
 * @return {function}
 */
export default function createFetchMiddleware(options = {}, promiseMode = false) {
  const { beforeFetch = defaultBeforeFetch, afterFetch = defaultAfterFetch, onReject = rejectHandler } = options;
  return () => (next = noop) => action => {
    if (!promiseMode && (!action.url || !action.types)) {
      return next(action);
    }

    if (promiseMode && !action.url) {
      throw new Error('[fetch-middleware] Missing required key: `url`');
    }

    let loadingType;
    let successType;
    let failureType;

    if (!promiseMode) {
      [loadingType, successType, failureType] = action.types;
    }

    if (loadingType) {
      try {
        next({
          ...action,
          type: loadingType,
        });
      } catch (err) {
        console.error(`[fetch-middleware] Uncaught error while dispatching \`${loadingType}\`\n`, err.stack);
      }
    }

    let beforeFetchResult;
    try {
      beforeFetchResult = beforeFetch({ action });
    } catch (err) {
      throw new Error('[fetch-middleware] Uncaught error in `beforeFetch` middleware', err.stack);
    }

    if (!(beforeFetchResult instanceof Promise)) {
      throw new TypeError('[fetch-middleware] `beforeFetch` middleware returned a non-Promise object, instead got:',
                          beforeFetchResult);
    }

    return beforeFetchResult
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action')) {
        console.error('[fetch-middleware] `beforeFetch` should resolve an object containing `action` key, instead got:',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .then(
      ({ action }) => {
        const { url, types, ...options } = action; // eslint-disable-line
        return fetch(url, options).then(
          result => {
            return Promise.resolve({
              action,
              result,
            });
          },
          err => {
            return Promise.reject({
              action,
              error: err,
            });
          }
        );
      }
    )
    .then(
      ({ action, result }) => {
        let afterFetchResult;
        try {
          afterFetchResult = afterFetch({ action, result });
        } catch (err) {
          console.error('[fetch-middleware] Uncaught error in `afterFetch` middleware\n', err.stack);
        }

        if (!(afterFetchResult instanceof Promise)) {
          console.error('[fetch-middleware] `afterFetch` middleware returned a non-Promise object');
          return Promise.reject();
        }

        return afterFetchResult;
      }
    )
    .then(args => {
      if (!args || typeof args !== 'object' || !hasOwn(args, 'action', 'result')) {
        console.error('[fetch-middleware] `afterFetch` should resolve an object ' +
                      'containing `action` and `result` key, instead got',
                      args);
        return Promise.reject(args);
      }
      return args;
    })
    .catch(err => {
      if (err instanceof Error || typeof err !== 'object' || !hasOwn(err, 'action', 'error')) {
        return onReject({
          action,
          error: err,
        });
      }

      return onReject(err);
    })
    .then(
      ({ action, result }) => {
        try {
          next({
            ...action,
            payload: result,
            type: successType,
          });
        } catch (err) {
          console.error(`[fetch-middleware] Uncaught error while dispatching \`${successType}\`\n`, err.stack);
        }

        return Promise.resolve(result);
      }
    )
    .catch(
      ({ action, error }) => {
        if (failureType) {
          try {
            next({
              ...action,
              type: failureType,
              error,
            });
          } catch (err) {
            console.error(`[fetch-middleware] Uncaught error while dispatching \`${failureType}\`\n`, err.stack);
          }
        } else {
          // only reject when no `failureType` is provided, which means errors
          // are probably not handled in reducer
          return Promise.reject(error);
        }
      }
    );
  };
}

export { applyFetchMiddleware } from './applyFetchMiddleware';
<|endoftext|>


<commit_before>(function( $ ) {
  var exports = window.ShinyServer = window.ShinyServer || {};
  $(function() {
    if (typeof(Shiny) != "undefined") {
      (function() {
        var supports_html5_storage = exports.supports_html5_storage = function() {
          return true;
          try {
            return 'localStorage' in window && window['localStorage'] !== null;
          } catch (e) {
            return false;
          }
        }

        var availableOptions = ['websocket', 'xdr-streaming', 'xhr-streaming',
            'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling',
            'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling'];

        var store = null;
        var whitelist = [];

        if (supports_html5_storage()){
          store = window.localStorage;
          whitelistStr = store["shiny.whitelist"];
          if (!whitelistStr || whitelistStr === ""){
            whitelist = availableOptions;
          } else{
            whitelist = JSON.parse(whitelistStr);
          }
        }

        if (!whitelist){
          whitelist = availableOptions;
        }

        var networkSelector = $('
' +
          '
'+
          '
Select Network Methods
' +
          '

' +
          '
'+(supports_html5_storage()?'':"These network settings can only be configured in browsers that support HTML5 Storage. Please update your browser.")+'
' +
          '
' +
            '<button onclick="ShinyServer.enableAll()">Reset</button>' +
            '<button onclick="ShinyServer.toggleNetworkSelector();" style="margin-left: 1em;" id="netOptOK">OK</button>' +
          '
' +
          '

');
        $('body').append(networkSelector);

        var networkOptions = $('#networkOptions', networkSelector);

        $.each(availableOptions, function(index, val){
          var checked = ($.inArray(val, whitelist) >= 0);
          var opt = $('<input type="checkbox" id="ss-net-opt-'+val+'" name="checkbox" value="'+index+'" '+
            (ShinyServer.supports_html5_storage()?'':'disabled="disabled"')+
            '> '+val+'').appendTo(networkOptions);
          var checkbox = $('input', opt);
          checkbox.change(function(evt){
            ShinyServer.setOption(val, $(evt.target).prop('checked'));
          });
          if (checked){
            checkbox.prop('checked', true);
          }
        });

        var networkSelectorVisible = false;
        networkSelector.hide();

        $(document).keydown(function(event){
          if (event.shiftKey && event.ctrlKey && event.altKey && event.keyCode == 65){
            ShinyServer.toggleNetworkSelector();
          }
        });

        var toggleNetworkSelector = exports.toggleNetworkSelector = function(){
          if (networkSelectorVisible){
            // hide
            networkSelectorVisible = false;
            networkSelector.hide(200);
          } else{
            // show
            networkSelectorVisible = true;
            networkSelector.show(200);
          }
        }

        var enableAll = exports.enableAll = function(){
          $('input', networkOptions).each(function(index, val){
            $(val).prop('checked', true)
          });
          // Enable each protocol internally
          $.each(availableOptions, function(index, val){
            setOption(val, true);
          });
        }

        /**
         * Doesn't update the DOM, just updates our internal model.
         */
        var setOption = exports.setOption = function(option, enabled){
          $("#network-prot-warning").html("Updated settings will be applied when you refresh your browser or load a new Shiny application.");
          if (enabled && $.inArray(option, whitelist) === -1){
            whitelist.push(option);
          }
          if (!enabled && $.inArray(option, whitelist >= 0)){
            // Don't remove if it's the last one, and recheck
            if (whitelist.length === 1){
              $("#network-prot-warning").html("You must leave at least one method selected.");
              $("#ss-net-opt-" + option).prop('checked', true);
            } else{
              whitelist.splice($.inArray(option, whitelist), 1);
            }
          }
          store["shiny.whitelist"] = JSON.stringify(whitelist);
        }

        Shiny.createSocket = function() {
          return new SockJS(location.pathname + "__sockjs__/",null,{protocols_whitelist: whitelist});
        };
        Shiny.oncustommessage = function(message) {
          if (typeof message === "string") alert(message); // Legacy format
          if (message.alert) alert(message.alert);
          if (message.console && console.log) console.log(message.console);
        };

      })();
    }
  });
})(jQuery);<commit_msg>Restore IE8 compatibility.<commit_after>(function( $ ) {
  var exports = window.ShinyServer = window.ShinyServer || {};
  $(function() {
    if (typeof(Shiny) != "undefined") {
      (function() {
        var supports_html5_storage = exports.supports_html5_storage = function() {
          return true;
          try {
            return 'localStorage' in window && window['localStorage'] !== null;
          } catch (e) {
            return false;
          }
        }

        var availableOptions = ['websocket', 'xdr-streaming', 'xhr-streaming',
            'iframe-eventsource', 'iframe-htmlfile', 'xdr-polling',
            'xhr-polling', 'iframe-xhr-polling', 'jsonp-polling'];

        var store = null;
        var whitelist = [];

        if (supports_html5_storage()){
          store = window.localStorage;
          whitelistStr = store["shiny.whitelist"];
          if (!whitelistStr || whitelistStr === ""){
            whitelist = availableOptions;
          } else{
            whitelist = JSON.parse(whitelistStr);
          }
        }

        if (!whitelist){
          whitelist = availableOptions;
        }

        var networkSelector = $('
' +
          '
'+
          '
Select Network Methods
' +
          '

' +
          '
'+(supports_html5_storage()?'':"These network settings can only be configured in browsers that support HTML5 Storage. Please update your browser.")+'
' +
          '
' +
            '<input type="button" value="Reset" onclick="ShinyServer.enableAll()"></input>' +
            '<input type="button" value="OK" onclick="ShinyServer.toggleNetworkSelector();" style="margin-left: 1em;" id="netOptOK"></input>' +
          '
' +
          '

');
        $('body').append(networkSelector);

        var networkOptions = $('#networkOptions', networkSelector);

        $.each(availableOptions, function(index, val){
          var checked = ($.inArray(val, whitelist) >= 0);
          var opt = $('<input type="checkbox" id="ss-net-opt-'+val+'" name="checkbox" value="'+index+'" '+
            (ShinyServer.supports_html5_storage()?'':'disabled="disabled"')+
            '> '+val+'').appendTo(networkOptions);
          var checkbox = $('input', opt);
          checkbox.change(function(evt){
            ShinyServer.setOption(val, $(evt.target).prop('checked'));
          });
          if (checked){
            checkbox.prop('checked', true);
          }
        });

        var networkSelectorVisible = false;
        networkSelector.hide();

        $(document).keydown(function(event){
          if (event.shiftKey && event.ctrlKey && event.altKey && event.keyCode == 65){
            ShinyServer.toggleNetworkSelector();
          }
        });

        var toggleNetworkSelector = exports.toggleNetworkSelector = function(){
          if (networkSelectorVisible){
            // hide
            networkSelectorVisible = false;
            networkSelector.hide(200);
          } else{
            // show
            networkSelectorVisible = true;
            networkSelector.show(200);
          }
        }

        var enableAll = exports.enableAll = function(){
          $('input', networkOptions).each(function(index, val){
            $(val).prop('checked', true)
          });
          // Enable each protocol internally
          $.each(availableOptions, function(index, val){
            setOption(val, true);
          });
        }

        /**
         * Doesn't update the DOM, just updates our internal model.
         */
        var setOption = exports.setOption = function(option, enabled){
          $("#network-prot-warning").html("Updated settings will be applied when you refresh your browser or load a new Shiny application.");
          if (enabled && $.inArray(option, whitelist) === -1){
            whitelist.push(option);
          }
          if (!enabled && $.inArray(option, whitelist >= 0)){
            // Don't remove if it's the last one, and recheck
            if (whitelist.length === 1){
              $("#network-prot-warning").html("You must leave at least one method selected.");
              $("#ss-net-opt-" + option).prop('checked', true);
            } else{
              whitelist.splice($.inArray(option, whitelist), 1);
            }
          }
          store["shiny.whitelist"] = JSON.stringify(whitelist);
        }

        Shiny.createSocket = function() {
          return new SockJS(location.pathname + "__sockjs__/",null,{protocols_whitelist: whitelist});
        };
        Shiny.oncustommessage = function(message) {
          if (typeof message === "string") alert(message); // Legacy format
          if (message.alert) alert(message.alert);
          if (message.console && console.log) console.log(message.console);
        };

      })();
    }
  });
})(jQuery);<|endoftext|>


<commit_before>angular.module('ngSimpleUpload', [])
    .directive('ngSimpleUpload', [function () {
        return {
            scope: {
                webApiUrl: '@',
                callbackFn: '=',
                buttonId: '@'
            },
            link: function (scope, element, attrs) {
                // if button id value exists
                if (scope.buttonId) {
                    $('#' + scope.buttonId).on('click', function () {
                        // retrieves files from file input
                        var files = element[0].files;
                        // will not fire until file(s) are selected
                        if (files.length == 0) {
                            console.log('No files detected.');
                            return false;
                        }

                        Upload(files);

                        // removes file(s) from input
                        $(this).val('');
                    });
                }
                else {
                    // original code, trigger upload on change
                    element.on('change', function (evt) {
                        var files = evt.__files_ || (evt.target && evt.target.files);

                        Upload(files);
                    });
                }

                function Upload(files) {
                    var fd = new FormData();
                    angular.forEach(files, function (v, k) {
                        fd.append('file', files[k]);
                    });

                    return $.ajax({
                        type: 'POST',
                        url: scope.webApiUrl,
                        data: fd,
                        async: true,
                        cache: false,
                        contentType: false,
                        processData: false
                    }).done(function (d) {
                        // callback function in the controller
                        scope.callbackFn(d);
                    }).fail(function (x) {
                        console.log(x);
                    });
                }
            }
        }
    }]);
<commit_msg>Update ng-simple-upload.js<commit_after>angular.module('ngSimpleUpload', [])
    .directive('ngSimpleUpload', [function () {
        return {
            scope: {
                webApiUrl: '@',
                callbackFn: '=',
                buttonId: '@'
            },
            link: function (scope, element, attrs) {
                // if button id value exists
                if (scope.buttonId) {
                    $('#' + scope.buttonId).on('click', function () {
                        // retrieves files from file input
                        var files = element[0].files;
                        // will not fire until file(s) are selected
                        if (files.length == 0) {
                            console.log('No files detected.');
                            return false;
                        }

                        Upload(files);
                    });
                }
                else {
                    // original code, trigger upload on change
                    element.on('change', function (evt) {
                        var files = evt.__files_ || (evt.target && evt.target.files);

                        Upload(files);

                        // removes file(s) from input
                        $(this).val('');
                    });
                }

                function Upload(files) {
                    var fd = new FormData();
                    angular.forEach(files, function (v, k) {
                        fd.append('file', files[k]);
                    });

                    return $.ajax({
                        type: 'POST',
                        url: scope.webApiUrl,
                        data: fd,
                        async: true,
                        cache: false,
                        contentType: false,
                        processData: false
                    }).done(function (d) {
                        // callback function in the controller
                        scope.callbackFn(d);
                    }).fail(function (x) {
                        console.log(x);
                    });
                }
            }
        }
    }]);
<|endoftext|>


<commit_before>
/*jslint bitwise: true, nomen: true, plusplus: true, white: true, continue: true */
/*global _AP: false,  window: false,  document: false, performance: false, console: false, alert: false, postMessage: false, setTimeout: false */

var
trackIndex,
channelIndex,

allTrks,
trkIndex,
currentTrk,

// currentTrk.moments
moments,
momentIndex,
currentMoment,
nMoments,

// runtime variables
pressureOption,
pitchWheelOption,
modWheelOption,
stopChord,
stopNow,
fadeLength,
letSound,
velocityFactor,
sharedVelocity,
overrideVelocity,
speedFactor,

pitchWheelDeviation,

/****************************************/
// Aug. 2015
eventHandler = function(e)
{
	"use strict";

	var msg = e.data;

	// Keyboard1 sends:
	// worker.postMessage({ action: "init", trackIndex: i, channelIndex: outputTrackMidiChannels[i] });
	function init(msg)
	{
		console.assert(msg.trackIndex !== undefined && msg.trackIndex >= 0 && msg.trackIndex < 16);
		console.assert(msg.channelIndex !== undefined && msg.channelIndex >= 0 && msg.channelIndex < 16);

		trackIndex = msg.trackIndex;
		channelIndex = msg.channelIndex;

		allTrks = [];
		trkIndex = 0;
		//currentTrk = 0; initialised in start (from trkIndex)

		// currentTrk.moments
		// moments; initialized in pushTrk()
		momentIndex = 0;
		currentMoment = null;
		// nMoments; initialized in start (= currentTrk.moments.length)

		// runtime variables
		stopChord = false;
		stopNow = false;
		fadeLength = -1;
		letSound = false;
		velocityFactor = 1;
		sharedVelocity = 0;
		overrideVelocity = 0;
		speedFactor = 1;
		pitchWheelDeviation = 2; // 2 semitones up, and 2 semitones down
	}

	/****************************************/
	// Seq constructor sends:
	// worker.postMessage({ action: "pushTrk", msPosition: msPosition, moments: moments, options: options });
	// Set a new trk object's attributes to msPosition, moments and options,
	// then add it to the allTrks array maintaining the allTrks array in order of msPosition.
	// The options attribute is always a defined object, but it need not have any attributes.
	function pushTrk(msg)
	{
		var insertAtIndex,
			msPosition = msg.msPosition,
			moments = msg.moments,
			options = msg.options,
			trk = {};

		function messageIsNoteOff(message)
		{
			var data0, rval = false;

			data0 = message.data[0];
			if(((data0 >= 0x90 && data0 <= 0x9F) && message.data[1] === 0) // NoteOn, velocity 0
			|| (data0 >= 0x80 && data0 <= 0x8F)) // NoteOff
			{
				rval = true;
			}

			return rval;
		}

		function removeNoteOffMessages(moment)
		{
			var i, newMessages = [], oldMessages = moment.messages;

			for(i = 0; i < oldMessages.length; ++i)
			{
				if(!messageIsNoteOff(oldMessages[i]))
				{
					newMessages.push(oldMessages[i]);
				}
			}
			moment.messages = newMessages;
		}

		// Removes all noteOff messages from the final moment that contains any.
		function removeFinalNoteOffMessages(moments)
		{
			var	i, lastNoteOffMomentIndex = moments.length; // an impossible value

			function momentContainsNoteOffMessage(moment)
			{
				var i, messages = moment.messages, rval = false;

				for(i = 0; i < messages.length; ++i)
				{
					if(messageIsNoteOff(messages[i]))
					{
						rval = true;
						break;
					}
				}
				return rval;
			}

			for(i = moments.length - 1; i > 0; --i)
			{
				if(momentContainsNoteOffMessage(moments[i]))
				{
					lastNoteOffMomentIndex = i;
					break;
				}
			}

			if(lastNoteOffMomentIndex < moments.length)
			{
				removeNoteOffMessages(moments[lastNoteOffMomentIndex]);
			}
		}

		function removeAllNoteOffMessages(moments)
		{
			var i;

			for(i = 0; i < moments.length; ++i)
			{
				removeNoteOffMessages(moments[i]);
			}
		}

		function findInsertionIndex(currentTrks, msPosition)
		{
			var i, nTrks = currentTrks.length, insIndex = nTrks;

			if(nTrks > 0 && currentTrks[nTrks - 1].msPosition > msPosition)
			{
				if(currentTrks[0].msPosition < msPosition)
				{
					for(i = nTrks - 1; i >= 1; --i)
					{
						console.assert(currentTrks[i].msPosition !== msPosition,
							"Error in TrackWorker.pushTrk(): Attempt to push a trk at an existing position!");
						if((currentTrks[i - 1].msPosition < msPosition) && (currentTrks[i].msPosition > msPosition))
						{
							insIndex = i;
							break;
						}
					}
				}
				else
				{
					insIndex = 0;
				}
			}

			return insIndex;
		}

		console.assert(options !== undefined, "Error: options must be a defined object here (but it need not have any attributes).");

		if(options.pedal) // if undefined, do nothing
		{
			switch(options.pedal)
			{
				case "holdLast":
					removeFinalNoteOffMessages(moments);
					letSound = true;
					break;
				case "holdAll":
					removeAllNoteOffMessages(moments);
					letSound = true;
					break;
				case "holdAllStop":
					removeAllNoteOffMessages(moments);
					letSound = false;
					break;
				default:
					console.assert(false, "TrackWorker.pushTrk(): illegal option -- " + options.pedal);
					break;
			}
		}

		insertAtIndex = findInsertionIndex(allTrks, msPosition);

		trk.msPosition = msPosition;
		trk.moments = moments;
		trk.previousMsPosInSeq = 0;

		if(options.speed === undefined)
		{
			options.speed = 1; // default speed is as written in the score.
		}
		trk.options = options;

		allTrks.splice(insertAtIndex, 0, trk);
	}

	// Seq.prototype.start calls:
	// worker.postMessage({ action: "start", velocity: performedVelocity });
	// Note that NoteOffs call this function with velocity set to 0,
	// and that in this case trk speed and velocity options are ignored.
	function start(msg)
	{
		var performedVelocity, minVelocity;

		function _start()
		{
			// Used by tick and start.
			// Returns null when there are no more moments, or global stopNow is true, or (stopChord is true and we have reached the next midiObject).
			function nextMoment()
			{
				var nextMomt = null;
				if(momentIndex < moments.length && stopNow === false)
				{
					nextMomt = moments[momentIndex++];
					if(stopChord && momentIndex > 1 && (nextMomt.chordStart !== undefined || nextMomt.RestStart !== undefined))
					{
						nextMomt = null; // stop at this chord or rest
					}
				}
				return nextMomt; // null stops tick().
			}

			// Used by tick and _start.
			function tick()
			{
				var delay;

				function sendMessages(moment)
				{
					var
					messages = moment.messages,
					i, nMessages = messages.length,
					newVelocity, uint8Array;

					for(i = 0; i < nMessages; ++i)
					{
						uint8Array = messages[i].data;
						if(uint8Array[0] >= 0x90 && uint8Array[0] <= 0x9F)
						{
							// a NoteOn
							newVelocity = uint8Array[2];
							if(velocityFactor !== 1)
							{
								newVelocity *= velocityFactor;
							}
							else if(sharedVelocity > 0)
							{
								newVelocity = (newVelocity / 2) + sharedVelocity;
							}
							else if(overrideVelocity > 0)
							{
								newVelocity = overrideVelocity;
							}

							if(fadeLength > 0)
							{
								newVelocity = (newVelocity * (nMoments + 1 - momentIndex) / fadeLength); // scale the velocity
							}

							newVelocity = (newVelocity > 127) ? 127 : newVelocity | 0; // | 0 truncates to an int
							uint8Array[2] = newVelocity;
							//console.log("Changed velocity = " + newVelocity);
						}
						postMessage({ action: "midiMessage", midiMessage: uint8Array });
					}
				}

				function getDelay(moment)
				{
					var
					delay = (moment.msPositionInSeq - currentTrk.previousMsPosInSeq) / speedFactor;
					currentTrk.previousMsPosInSeq = moment.msPositionInSeq;

					return delay;
				}

				function trkCompleted(letSound)
				{
					if(trkIndex < (allTrks.length - 1))
					{
						postMessage({ action: "trkCompleted", channelIndex: channelIndex, letSound: letSound });
					}
					else
					{
						postMessage({ action: "workerCompleted", trackIndex: trackIndex, channelIndex: channelIndex, letSound: letSound });
					}
				}

				if(currentMoment === null || stopNow === true)
				{
					trkCompleted(letSound);
					return;
				}

				delay = getDelay(currentMoment);

				while(delay <= 0)
				{
					if(stopNow === true)
					{
						trkCompleted(letSound);
						return;
					}
					if(currentMoment.messages.length > 0) // rest moments can be empty
					{
						sendMessages(currentMoment);
					}

					currentMoment = nextMoment();

					if(currentMoment === null || stopNow === true)
					{
						trkCompleted(letSound);
						return;
					}

					delay = getDelay(currentMoment);
				}

				setTimeout(tick, delay);  // schedules the next tick.
			}

			if(trkIndex < allTrks.length)
			{
				currentMoment = nextMoment();
				if(currentMoment === null)
				{
					return;
				}
				tick();
			}
		}

		// This function returns an integer in range [minVelocity..127].
		// I have found, by experiment, that my E-MU keyboard never seems to send a velocity less than 20,
		// so this function first spreads the incoming range [20..127] to [0..127], then sets all velocities
		// less than minVelocity to minVelocity.
		function getCorrectedVelocity(velocity, minVelocity)
		{
			velocity = (velocity > 20) ? velocity - 20 : 0;
			velocity = Math.round(velocity * 1.1869); // 1.1869 is approximately 127 / 107;
			velocity = (velocity > minVelocity) ? velocity : minVelocity;
			velocity = (velocity < 127) ? velocity : 127;
			return velocity;
		}

		// Note that the returned velocityFactor is not an integer.
		function getVelocityFactor(velocity, minVelocity)
		{
			var velocityFactor;

			velocity = getCorrectedVelocity(velocity, minVelocity);
			velocityFactor = velocity / 64;

			return velocityFactor;
		}

		// The returned sharedVelocity is an integer.
		function getSharedVelocity(velocity, minVelocity)
		{
			var sharedVelocity;

			velocity = getCorrectedVelocity(velocity, minVelocity);
			sharedVelocity = Math.round(velocity / 2);

			return sharedVelocity;
		}

		if(trkIndex < allTrks.length)
		{
			stopChord = false;
			stopNow = false;

			if(currentTrk !== undefined && currentTrk.isRunning === true)
			{
				currentTrk.isRunning = false;
				trkIndex++;
			}

			currentTrk = allTrks[trkIndex];
			currentTrk.isRunning = true;

			moments = currentTrk.moments;
			nMoments = moments.length;
			momentIndex = 0;

			if(msg.velocity > 0)
			{
				if(currentTrk.options.velocity)
				{
					velocityFactor = 1;
					sharedVelocity = 0;
					overrideVelocity = 0;
					performedVelocity = msg.velocity;
					minVelocity = currentTrk.options.minVelocity; // is defined if options.velocity is defined
					switch(currentTrk.options.velocity)
					{
						case "scaled":
							velocityFactor = getVelocityFactor(performedVelocity, minVelocity);
							break;
						case "shared":
							sharedVelocity = getSharedVelocity(performedVelocity, minVelocity);
							break;
						case "overridden":
							overrideVelocity = getCorrectedVelocity(performedVelocity, minVelocity);
							break;
						default:
							console.assert(false, "TrackWorker.doNoteOnVelocity(): illegal option -- " + currentTrk.options.velocity);
					}
				}

				speedFactor = currentTrk.options.speed;
			}

			_start();
		}
	}

	/****************************************/
	/* case "stop": */
	// Aug. 2015
	function stop()
	{
		var noteOffOption = currentTrk.options.noteOff;

		function setFade()
		{
			fadeLength = nMoments + 1 - momentIndex;
		}

		if(noteOffOption !== undefined)
		{
			switch(noteOffOption)
			{
				case "stopChord":
					stopChord = true; // stop playing the trk at the following midiChord or midiRest.
					break;
				case "stopNow":
					stopNow = true; // stop immediately, without playing the remainder of the current midiChord or midiRest.
					break;
				case "fade":
					setFade(); // fade the velocity to zero at the end of the trk
					break;
				default:
					throw (">>>>>>>>>> Illegal noteOff option: " + noteOffOption + " <<<<<<<<<<");
			}
		}
	}

	// begin eventHandler code

	switch(msg.action)
	{
		// called by Keyboard1 to initialize this worker (set up global variables etc.)
		case "init":
			init(msg);
			break;

		// called by Seq when loading this worker with trks
		case "pushTrk":
			pushTrk(msg);
			break;

		// called by Seq to start a trk playing.
		case "start":
			start(msg);
			break;

		// called by Keyboard1 to stop a playing trk.
		case "stop":
			stop();
			break;

		// called by Keyboard1 to change the speed at which the trk plays.
		case "changeSpeed":
			speedFactor = currentTrk.options.speed * msg.speedFactor;
			break;
	}
};

addEventListener("message", eventHandler);

<commit_msg>Added a check for undefined currentTrk<commit_after>
/*jslint bitwise: true, nomen: true, plusplus: true, white: true, continue: true */
/*global _AP: false,  window: false,  document: false, performance: false, console: false, alert: false, postMessage: false, setTimeout: false */

var
trackIndex,
channelIndex,

allTrks,
trkIndex,
currentTrk,

// currentTrk.moments
moments,
momentIndex,
currentMoment,
nMoments,

// runtime variables
pressureOption,
pitchWheelOption,
modWheelOption,
stopChord,
stopNow,
fadeLength,
letSound,
velocityFactor,
sharedVelocity,
overrideVelocity,
speedFactor,

pitchWheelDeviation,

/****************************************/
// Aug. 2015
eventHandler = function(e)
{
	"use strict";

	var msg = e.data;

	// Keyboard1 sends:
	// worker.postMessage({ action: "init", trackIndex: i, channelIndex: outputTrackMidiChannels[i] });
	function init(msg)
	{
		console.assert(msg.trackIndex !== undefined && msg.trackIndex >= 0 && msg.trackIndex < 16);
		console.assert(msg.channelIndex !== undefined && msg.channelIndex >= 0 && msg.channelIndex < 16);

		trackIndex = msg.trackIndex;
		channelIndex = msg.channelIndex;

		allTrks = [];
		trkIndex = 0;
		//currentTrk = 0; initialised in start (from trkIndex)

		// currentTrk.moments
		// moments; initialized in pushTrk()
		momentIndex = 0;
		currentMoment = null;
		// nMoments; initialized in start (= currentTrk.moments.length)

		// runtime variables
		stopChord = false;
		stopNow = false;
		fadeLength = -1;
		letSound = false;
		velocityFactor = 1;
		sharedVelocity = 0;
		overrideVelocity = 0;
		speedFactor = 1;
		pitchWheelDeviation = 2; // 2 semitones up, and 2 semitones down
	}

	/****************************************/
	// Seq constructor sends:
	// worker.postMessage({ action: "pushTrk", msPosition: msPosition, moments: moments, options: options });
	// Set a new trk object's attributes to msPosition, moments and options,
	// then add it to the allTrks array maintaining the allTrks array in order of msPosition.
	// The options attribute is always a defined object, but it need not have any attributes.
	function pushTrk(msg)
	{
		var insertAtIndex,
			msPosition = msg.msPosition,
			moments = msg.moments,
			options = msg.options,
			trk = {};

		function messageIsNoteOff(message)
		{
			var data0, rval = false;

			data0 = message.data[0];
			if(((data0 >= 0x90 && data0 <= 0x9F) && message.data[1] === 0) // NoteOn, velocity 0
			|| (data0 >= 0x80 && data0 <= 0x8F)) // NoteOff
			{
				rval = true;
			}

			return rval;
		}

		function removeNoteOffMessages(moment)
		{
			var i, newMessages = [], oldMessages = moment.messages;

			for(i = 0; i < oldMessages.length; ++i)
			{
				if(!messageIsNoteOff(oldMessages[i]))
				{
					newMessages.push(oldMessages[i]);
				}
			}
			moment.messages = newMessages;
		}

		// Removes all noteOff messages from the final moment that contains any.
		function removeFinalNoteOffMessages(moments)
		{
			var	i, lastNoteOffMomentIndex = moments.length; // an impossible value

			function momentContainsNoteOffMessage(moment)
			{
				var i, messages = moment.messages, rval = false;

				for(i = 0; i < messages.length; ++i)
				{
					if(messageIsNoteOff(messages[i]))
					{
						rval = true;
						break;
					}
				}
				return rval;
			}

			for(i = moments.length - 1; i > 0; --i)
			{
				if(momentContainsNoteOffMessage(moments[i]))
				{
					lastNoteOffMomentIndex = i;
					break;
				}
			}

			if(lastNoteOffMomentIndex < moments.length)
			{
				removeNoteOffMessages(moments[lastNoteOffMomentIndex]);
			}
		}

		function removeAllNoteOffMessages(moments)
		{
			var i;

			for(i = 0; i < moments.length; ++i)
			{
				removeNoteOffMessages(moments[i]);
			}
		}

		function findInsertionIndex(currentTrks, msPosition)
		{
			var i, nTrks = currentTrks.length, insIndex = nTrks;

			if(nTrks > 0 && currentTrks[nTrks - 1].msPosition > msPosition)
			{
				if(currentTrks[0].msPosition < msPosition)
				{
					for(i = nTrks - 1; i >= 1; --i)
					{
						console.assert(currentTrks[i].msPosition !== msPosition,
							"Error in TrackWorker.pushTrk(): Attempt to push a trk at an existing position!");
						if((currentTrks[i - 1].msPosition < msPosition) && (currentTrks[i].msPosition > msPosition))
						{
							insIndex = i;
							break;
						}
					}
				}
				else
				{
					insIndex = 0;
				}
			}

			return insIndex;
		}

		console.assert(options !== undefined, "Error: options must be a defined object here (but it need not have any attributes).");

		if(options.pedal) // if undefined, do nothing
		{
			switch(options.pedal)
			{
				case "holdLast":
					removeFinalNoteOffMessages(moments);
					letSound = true;
					break;
				case "holdAll":
					removeAllNoteOffMessages(moments);
					letSound = true;
					break;
				case "holdAllStop":
					removeAllNoteOffMessages(moments);
					letSound = false;
					break;
				default:
					console.assert(false, "TrackWorker.pushTrk(): illegal option -- " + options.pedal);
					break;
			}
		}

		insertAtIndex = findInsertionIndex(allTrks, msPosition);

		trk.msPosition = msPosition;
		trk.moments = moments;
		trk.previousMsPosInSeq = 0;

		if(options.speed === undefined)
		{
			options.speed = 1; // default speed is as written in the score.
		}
		trk.options = options;

		allTrks.splice(insertAtIndex, 0, trk);
	}

	// Seq.prototype.start calls:
	// worker.postMessage({ action: "start", velocity: performedVelocity });
	// Note that NoteOffs call this function with velocity set to 0,
	// and that in this case trk speed and velocity options are ignored.
	function start(msg)
	{
		var performedVelocity, minVelocity;

		function _start()
		{
			// Used by tick and start.
			// Returns null when there are no more moments, or global stopNow is true, or (stopChord is true and we have reached the next midiObject).
			function nextMoment()
			{
				var nextMomt = null;
				if(momentIndex < moments.length && stopNow === false)
				{
					nextMomt = moments[momentIndex++];
					if(stopChord && momentIndex > 1 && (nextMomt.chordStart !== undefined || nextMomt.RestStart !== undefined))
					{
						nextMomt = null; // stop at this chord or rest
					}
				}
				return nextMomt; // null stops tick().
			}

			// Used by tick and _start.
			function tick()
			{
				var delay;

				function sendMessages(moment)
				{
					var
					messages = moment.messages,
					i, nMessages = messages.length,
					newVelocity, uint8Array;

					for(i = 0; i < nMessages; ++i)
					{
						uint8Array = messages[i].data;
						if(uint8Array[0] >= 0x90 && uint8Array[0] <= 0x9F)
						{
							// a NoteOn
							newVelocity = uint8Array[2];
							if(velocityFactor !== 1)
							{
								newVelocity *= velocityFactor;
							}
							else if(sharedVelocity > 0)
							{
								newVelocity = (newVelocity / 2) + sharedVelocity;
							}
							else if(overrideVelocity > 0)
							{
								newVelocity = overrideVelocity;
							}

							if(fadeLength > 0)
							{
								newVelocity = (newVelocity * (nMoments + 1 - momentIndex) / fadeLength); // scale the velocity
							}

							newVelocity = (newVelocity > 127) ? 127 : newVelocity | 0; // | 0 truncates to an int
							uint8Array[2] = newVelocity;
							//console.log("Changed velocity = " + newVelocity);
						}
						postMessage({ action: "midiMessage", midiMessage: uint8Array });
					}
				}

				function getDelay(moment)
				{
					var
					delay = (moment.msPositionInSeq - currentTrk.previousMsPosInSeq) / speedFactor;
					currentTrk.previousMsPosInSeq = moment.msPositionInSeq;

					return delay;
				}

				function trkCompleted(letSound)
				{
					if(trkIndex < (allTrks.length - 1))
					{
						postMessage({ action: "trkCompleted", channelIndex: channelIndex, letSound: letSound });
					}
					else
					{
						postMessage({ action: "workerCompleted", trackIndex: trackIndex, channelIndex: channelIndex, letSound: letSound });
					}
				}

				if(currentMoment === null || stopNow === true)
				{
					trkCompleted(letSound);
					return;
				}

				delay = getDelay(currentMoment);

				while(delay <= 0)
				{
					if(stopNow === true)
					{
						trkCompleted(letSound);
						return;
					}
					if(currentMoment.messages.length > 0) // rest moments can be empty
					{
						sendMessages(currentMoment);
					}

					currentMoment = nextMoment();

					if(currentMoment === null || stopNow === true)
					{
						trkCompleted(letSound);
						return;
					}

					delay = getDelay(currentMoment);
				}

				setTimeout(tick, delay);  // schedules the next tick.
			}

			if(trkIndex < allTrks.length)
			{
				currentMoment = nextMoment();
				if(currentMoment === null)
				{
					return;
				}
				tick();
			}
		}

		// This function returns an integer in range [minVelocity..127].
		// I have found, by experiment, that my E-MU keyboard never seems to send a velocity less than 20,
		// so this function first spreads the incoming range [20..127] to [0..127], then sets all velocities
		// less than minVelocity to minVelocity.
		function getCorrectedVelocity(velocity, minVelocity)
		{
			velocity = (velocity > 20) ? velocity - 20 : 0;
			velocity = Math.round(velocity * 1.1869); // 1.1869 is approximately 127 / 107;
			velocity = (velocity > minVelocity) ? velocity : minVelocity;
			velocity = (velocity < 127) ? velocity : 127;
			return velocity;
		}

		// Note that the returned velocityFactor is not an integer.
		function getVelocityFactor(velocity, minVelocity)
		{
			var velocityFactor;

			velocity = getCorrectedVelocity(velocity, minVelocity);
			velocityFactor = velocity / 64;

			return velocityFactor;
		}

		// The returned sharedVelocity is an integer.
		function getSharedVelocity(velocity, minVelocity)
		{
			var sharedVelocity;

			velocity = getCorrectedVelocity(velocity, minVelocity);
			sharedVelocity = Math.round(velocity / 2);

			return sharedVelocity;
		}

		if(trkIndex < allTrks.length)
		{
			stopChord = false;
			stopNow = false;

			if(currentTrk !== undefined && currentTrk.isRunning === true)
			{
				currentTrk.isRunning = false;
				trkIndex++;
			}

			currentTrk = allTrks[trkIndex];
			currentTrk.isRunning = true;

			moments = currentTrk.moments;
			nMoments = moments.length;
			momentIndex = 0;

			if(msg.velocity > 0)
			{
				if(currentTrk.options.velocity)
				{
					velocityFactor = 1;
					sharedVelocity = 0;
					overrideVelocity = 0;
					performedVelocity = msg.velocity;
					minVelocity = currentTrk.options.minVelocity; // is defined if options.velocity is defined
					switch(currentTrk.options.velocity)
					{
						case "scaled":
							velocityFactor = getVelocityFactor(performedVelocity, minVelocity);
							break;
						case "shared":
							sharedVelocity = getSharedVelocity(performedVelocity, minVelocity);
							break;
						case "overridden":
							overrideVelocity = getCorrectedVelocity(performedVelocity, minVelocity);
							break;
						default:
							console.assert(false, "TrackWorker.doNoteOnVelocity(): illegal option -- " + currentTrk.options.velocity);
					}
				}

				speedFactor = currentTrk.options.speed;
			}

			_start();
		}
	}

	/****************************************/
	/* case "stop": */
	// Aug. 2015
	function stop()
	{
		var noteOffOption;

		function setFade()
		{
			fadeLength = nMoments + 1 - momentIndex;
		}

		if(currentTrk && currentTrk.options)
		{
			noteOffOption = currentTrk.options.noteOff;

			if(noteOffOption !== undefined)
			{
				switch(noteOffOption)
				{
					case "stopChord":
						stopChord = true; // stop playing the trk at the following midiChord or midiRest.
						break;
					case "stopNow":
						stopNow = true; // stop immediately, without playing the remainder of the current midiChord or midiRest.
						break;
					case "fade":
						setFade(); // fade the velocity to zero at the end of the trk
						break;
					default:
						throw (">>>>>>>>>> Illegal noteOff option: " + noteOffOption + " <<<<<<<<<<");
				}
			}
		}
	}

	// begin eventHandler code

	switch(msg.action)
	{
		// called by Keyboard1 to initialize this worker (set up global variables etc.)
		case "init":
			init(msg);
			break;

		// called by Seq when loading this worker with trks
		case "pushTrk":
			pushTrk(msg);
			break;

		// called by Seq to start a trk playing.
		case "start":
			start(msg);
			break;

		// called by Keyboard1 to stop a playing trk.
		case "stop":
			stop();
			break;

		// called by Keyboard1 to change the speed at which the trk plays.
		case "changeSpeed":
			speedFactor = currentTrk.options.speed * msg.speedFactor;
			break;
	}
};

addEventListener("message", eventHandler);

<|endoftext|>


<commit_before>import p2p from 'socket.io-p2p'
import io from 'socket.io-client'

import lodash from 'lodash'
import $ from 'jquery'
import Dropzone from 'dropzone'

import filereader from './filereader'
import downloader from './downloader'

export class Index {

  serverUrl = 'http://localhost'

  isUploader = true
  connectedToPeer = false

  token = null

  file = null
  previewImage = null
  uploading = false
  uploadComplete = false

  downloader = null

  constructor() {
    Dropzone.autoDiscover = false
    Dropzone.autoProcessQueue = false
    this.downloader = new downloader()
  }

  activate(params) {
    if(params.token) {
      this.isUploader = false
      this.token = params.token
    }
  }

  bind() {
    if(this.isUploader) {
      this.initDropzone()
    }

    this.socket = io(this.serverUrl + ':3000')

    this.socket.on('connect', () => {
      if(this.token) {
        this.socket.emit('set-token', this.token)
      }
    }.bind(this))

    this.socket.on('error', err => {
      console.error(err)
    }.bind(this))

    this.socket.on('set-token-ok', token => {
      this.token = token

      this.p2p = new p2p(this.socket)

      this.p2p.on('ready', function() {
        this.p2p.usePeerConnection = true
        this.p2p.emit('peer-obj', { peerId: peerId })
      }.bind(this))

      this.p2p.on('upgrade', data => {
        this.connectedToPeer = true

        if (this.file) {
          this.startUpload()
        }
      }.bind(this))

      this.p2p.on('error', err => {
        console.error(err)
        this.connectedToPeer = false
      }.bind(this))

      this.p2p.on('data', packet => {
        this.downloader.addChunk(packet.fileName, packet.fileSize, packet.data, packet.complete)
      }.bind(this))
    }.bind(this))
  }

  initDropzone() {
    var view = this

    setTimeout(() => {
      this.dropzone = new Dropzone("div#dropzone", {
        url: "/file/post",
        addedfile: file => {
          view.fileAdded(file)
        }.bind(this),
        thumbnail: (file, dataUrl) => {
          this.previewImage = dataUrl
        }.bind(this),
        uploadprogress: () => {},
        autoProcessQueue: false
      })
    }.bind(this), 0)
  }

  fileAdded(file) {
    $('#dropzone-text').html(file.name)
    this.fileName = file.name
    this.contentType = file.type
    this.file = file
    this.socket.emit('ask-token')
  }

  startUpload() {
    if(!this.file || !this.connectedToPeer) {
      return
    }

    this.uploading = true
    var fileName = this.fileName.split('\\').pop()

    this.reader = new filereader(this.file)
    this.reader.readFile(function(data, complete) {
      this.p2p.emit('data', {
        fileName: fileName,
        fileSize: this.reader.fileSize,
        data: data,
        complete: complete
      })

      if(complete) {
        this.uploadComplete = true
      }
    }.bind(this))
  }

}
<commit_msg>add STUN server<commit_after>import p2p from 'socket.io-p2p'
import io from 'socket.io-client'

import lodash from 'lodash'
import $ from 'jquery'
import Dropzone from 'dropzone'

import filereader from './filereader'
import downloader from './downloader'

export class Index {

  serverUrl = 'http://localhost'

  isUploader = true
  connectedToPeer = false

  token = null

  file = null
  previewImage = null
  uploading = false
  uploadComplete = false

  downloader = null

  constructor() {
    Dropzone.autoDiscover = false
    Dropzone.autoProcessQueue = false
    this.downloader = new downloader()
  }

  activate(params) {
    if(params.token) {
      this.isUploader = false
      this.token = params.token
    }
  }

  bind() {
    if(this.isUploader) {
      this.initDropzone()
    }

    this.socket = io(this.serverUrl + ':3000')

    this.socket.on('connect', () => {
      if(this.token) {
        this.socket.emit('set-token', this.token)
      }
    }.bind(this))

    this.socket.on('error', err => {
      console.error(err)
    }.bind(this))

    this.socket.on('set-token-ok', token => {
      this.token = token

      this.p2p = new p2p(this.socket, {
        peerOpts: {
          config: {
            iceServers: [
              { url: 'stun:stun.stunprotocol.org' }
            ]
          }
        }
      })

      this.p2p.on('ready', function() {
        this.p2p.usePeerConnection = true
        this.p2p.emit('peer-obj', { peerId: peerId })
      }.bind(this))

      this.p2p.on('upgrade', data => {
        this.connectedToPeer = true

        if (this.file) {
          this.startUpload()
        }
      }.bind(this))

      this.p2p.on('error', err => {
        console.error(err)
        this.connectedToPeer = false
      }.bind(this))

      this.p2p.on('data', packet => {
        this.downloader.addChunk(packet.fileName, packet.fileSize, packet.data, packet.complete)
      }.bind(this))
    }.bind(this))
  }

  initDropzone() {
    var view = this

    setTimeout(() => {
      this.dropzone = new Dropzone("div#dropzone", {
        url: "/file/post",
        addedfile: file => {
          view.fileAdded(file)
        }.bind(this),
        thumbnail: (file, dataUrl) => {
          this.previewImage = dataUrl
        }.bind(this),
        uploadprogress: () => {},
        autoProcessQueue: false
      })
    }.bind(this), 0)
  }

  fileAdded(file) {
    $('#dropzone-text').html(file.name)
    this.fileName = file.name
    this.contentType = file.type
    this.file = file
    this.socket.emit('ask-token')
  }

  startUpload() {
    if(!this.file || !this.connectedToPeer) {
      return
    }

    this.uploading = true
    var fileName = this.fileName.split('\\').pop()

    this.reader = new filereader(this.file)
    this.reader.readFile(function(data, complete) {
      this.p2p.emit('data', {
        fileName: fileName,
        fileSize: this.reader.fileSize,
        data: data,
        complete: complete
      })

      if(complete) {
        this.uploadComplete = true
      }
    }.bind(this))
  }

}
<|endoftext|>


<commit_before>'use strict';

/* Directives */
var directives = angular.module('tvPirateApp.directives', []);
directives.directive('episodes', ['Episodes', function(Episodes) {
    return {
        restrict: 'E',
        templateUrl: 'partials/episodes.html',
        link: function(scope) {
            scope.getEpisodes = function(show){
                Episodes.get({'show': show.id}, function success(res){
                    var episodes = _.filter(res.Episode, function(episode){
                       return _.has(episode, 'EpisodeName')
                           && episode.SeasonNumber > 0
                           && episode.EpisodeName !== 'TBA';
                    });
                    episodes = _.sortBy(episodes, function(episode){
                        return episode.FirstAired;
                    }).reverse();
                    show.episodes =  _.map(episodes, function(episode){
                            episode.SeasonNumber = 'S0'+episode.SeasonNumber;
                            episode.magnet = 'img/loading.gif';
                            episode.SeriesName = show.SeriesName;
                            return episode;
                        });
                });
            }

            scope.getPB = function(episode){
                episode.pbActive = true;
                PB.get({'keyword': episode.SeriesName + ' ' + episode.EpisodeName},
                    function success(res){
                        if (res && res.results && res.results.length > 0) {
                            episode.pb = res.results[0].magnetlink;
                            episode.magnet = 'img/icon-magnet.gif';
                        } else {
                            episode.pbActive = false;
                        }
                    }
                )
            }
        }
    }
  }]);
<commit_msg>#bugfix inject PB<commit_after>'use strict';

/* Directives */
var directives = angular.module('tvPirateApp.directives', []);
directives.directive('episodes', ['Episodes', 'PB', function(Episodes, PB) {
    return {
        restrict: 'E',
        templateUrl: 'partials/episodes.html',
        link: function(scope) {
            scope.getEpisodes = function(show){
                Episodes.get({'show': show.id}, function success(res){
                    var episodes = _.filter(res.Episode, function(episode){
                       return _.has(episode, 'EpisodeName')
                           && episode.SeasonNumber > 0
                           && episode.EpisodeName !== 'TBA';
                    });
                    episodes = _.sortBy(episodes, function(episode){
                        return episode.FirstAired;
                    }).reverse();
                    show.episodes =  _.map(episodes, function(episode){
                            episode.SeasonNumber = 'S0'+episode.SeasonNumber;
                            episode.magnet = 'img/loading.gif';
                            episode.SeriesName = show.SeriesName;
                            return episode;
                        });
                });
            }

            scope.getPB = function(episode){
                episode.pbActive = true;
                PB.get({'keyword': episode.SeriesName + ' ' + episode.EpisodeName},
                    function success(res){
                        if (res && res.results && res.results.length > 0) {
                            episode.pb = res.results[0].magnetlink;
                            episode.magnet = 'img/icon-magnet.gif';
                        } else {
                            episode.pbActive = false;
                        }
                    }
                )
            }
        }
    }
  }]);
<|endoftext|>


<commit_before>import {compile} from 'google-closure-compiler-js';
import logger from './logger';

export default function closure(flags = {}) {
    return {
        name: 'closure-compiler-js',
        transformBundle(code) {
            flags.createSourceMap = true;
            flags.processCommonJsModules = true;
            flags.jsCode = [{
                src: code
            }];
            const output = compile(flags);
            if (logger(flags, output)) {
                throw new Error(`compilation error, ${output.errors.length} error${output.errors.length===0 || output.errors.length>1?'s':''}`);
            }
            return {code: output.compiledCode, map: output.sourceMap};
        }
    };
}<commit_msg>Allow caller to set flags<commit_after>import {compile} from 'google-closure-compiler-js';
import logger from './logger';

export default function closure(flags = {}) {
    return {
        name: 'closure-compiler-js',
        transformBundle(code) {
            flags = Object.assign({
              createSourceMap: true,
              processCommonJsModules: true
            }, flags);
            flags.jsCode = [{
                src: code
            }];
            const output = compile(flags);
            if (logger(flags, output)) {
                throw new Error(`compilation error, ${output.errors.length} error${output.errors.length===0 || output.errors.length>1?'s':''}`);
            }
            return {code: output.compiledCode, map: output.sourceMap};
        }
    };
}
<|endoftext|>


<commit_before>(function(){
	var component = {
		fileName: 		"Game",
		classNames:		["Game"],
		requirements:	[],
		description:	"Game Class for RocketBoots",
		credits:		"By Luke Nickerson, 2016"
	};

	function Game (options) {
		if (typeof options === "string") {
			options = {name: options};
		} else {
			options = options || {};
		}
		this.name = options.name || "Game made with RocketBoots";
		this.version = options.version || "";

		this.init(options);
	}
	component.Game = Game;

	//======================================================= Game Functions ======

	Game.prototype.init = function(options){
		//console.log("Initializing Game");
		var g = this;

		g._addDefaultComponents(options);
		if (typeof options.instantiateComponents === "object") {
			g.instantiateComponents(options.instantiateComponents);
		}
		g._addStages(options);
		g._addDefaultStates();
		g.state._setupTransitionLinks();
		g.state.start("boot");
		return this;
	}

	// components should be an array of objects with one or two properties, like:
	// {"loop": "Loop", "options": { ...etc... }}
	// One property can be "options", while the other is a key-value pair for
	// the component's new property name and the associated component class.
	Game.prototype.instantiateComponents = function (components) {
		components.forEach(function(component){
			var options = undefined;
			var key;
			var compClass;
			if (typeof component.options !== "undefined") {
				options = component.options;
				delete component.options;
			}
			for (key in component) {
				compClass = component[key];
				console.log("Instantiating component class", compClass, "as", key, "with options", options);
				this._addComponent(key, compClass, options);
			}
		});
		return this;
	}

	Game.prototype._addDefaultComponents = function(options){
		this._addComponent("state", "StateMachine")
			//._addComponent("sounds", "SoundCannon")
			//._addComponent("images", "ImageOverseer")
			//._addComponent("state", "StateMachine")
			//._addComponent("looper", "Looper")
			//._addComponent("timeCount", "TimeCount")
			//._addComponent("incrementer", "Incrementer")
			//._addComponent("dice", "Dice")
			//._addComponent("keyboard", "Keyboard")
			//._addComponent("physics", "Physics")
			//._addComponent("entity", "Entity")
			//._addComponent("world", "World", options.world);
			// *** stage?
		return this;
	};

	Game.prototype._addComponent = function(gameCompName, componentClass, arg){
		if (RocketBoots.hasComponent(componentClass)) {
			//console.log("RB adding component", gameCompName, "to the game using class", componentClass, "and arguments:", arg);
			this[gameCompName] = new RocketBoots[componentClass](arg);
		} else {
			console.warn(componentClass, "not found as a RocketBoots component");
		}
		return this;
	};

	Game.prototype._addDefaultStates = function () {
		var g = this;
		// Setup default states (mostly menu controls)
		/*
		var startMenu = function(){
			//$('header, footer').show();
		};
		var endMenu = function(){
			//$('header, footer').hide();
		}
		*/
		g.state.addStates({
			"boot": { 		autoView: true },
			"preload": { 	autoView: true },
			/*
			"mainmenu": { 	autoView: true, start: startMenu, end: endMenu },
			"new": { 		autoView: true, start: startMenu, end: endMenu },
			"save": { 		autoView: true, start: startMenu, end: endMenu },
			"load": { 		autoView: true, start: startMenu, end: endMenu },
			"help": { 		autoView: true, start: startMenu, end: endMenu },
			"settings": { 	autoView: true, start: startMenu, end: endMenu },
			"credits": { 	autoView: true, start: startMenu, end: endMenu },
			"share": { 		autoView: true, start: startMenu, end: endMenu },
			*/
			"game": {}
		});
		/*
		g.state.add("game",{
			start : function(){
				$('header, footer').hide();
				this.$view.show();
			}, end : function(){
				$('header, footer').show();
				this.$view.hide();
			}
		});
		*/

		//g.state.get("game").$view.show();

		return g;
	};

	Game.prototype._addStages = function (options) {
		var g = this;
		var stageData;
		if (typeof RocketBoots.Stage !== "function") {
			return g;
		}
		if (typeof options.stages === 'object') {
			stageData = options.stages;
		} else if (typeof options.stage === 'object') {
			stageData = [options.stage];
		} else {
			return g;
		}
		if (stageData.length > 0) {
			g.stages = g.stages || [];
			$.each(stageData, function(i, stageOptions){
				g.stages[i] = new RocketBoots.Stage(stageOptions);
				if (typeof stageOptions.layerNames === 'object') {
					$.each(stageOptions.layerNames, function(x, layerName){
						g.stages[i].addLayer(layerName);
					});
				}
				g.stages[i].resize();
			});
			g.stage = g.stages[0];
		}
		return g;
	};

	// Install into RocketBoots if it exists
	if (typeof RocketBoots === "object") {
		RocketBoots.installComponent(component);
	} else { // Otherwise put the classes on the global window object
		for (var i = 0; i < component.classNames.length; i++) {
			window[component.classNames[i]] = component[component.classNames[i]];
		}
	}
})();<commit_msg>Refactoring of Game<commit_after>(function(){
	var component = {
		fileName: 		"Game",
		classNames:		["Game"],
		requirements:	[],
		description:	"Game Class for RocketBoots",
		credits:		"By Luke Nickerson, 2016"
	};

	function Game (options) {
		if (typeof options === "string") {
			options = {name: options};
		} else {
			options = options || {};
		}
		this.name = options.name || "Game made with RocketBoots";
		this.version = options.version || "";

		this.init(options);
	}
	component.Game = Game;

	Game.prototype.init = init;
	Game.prototype.instantiateComponents = instantiateComponents;
	Game.prototype.addComponent = addComponent;
	Game.prototype._addDefaultStates = _addDefaultStates;
	Game.prototype._addStages = _addStages;

	// Install into RocketBoots if it exists
	if (typeof RocketBoots === "object") {
		RocketBoots.installComponent(component);
	} else { // Otherwise put the classes on the global window object
		component.classNames.forEach(function(className){
			window[className] = component[className];
		});
	}

	return;

	//============================================ Hoisted Game Functions ======

	function init(options){
		//console.log("Initializing Game");
		var g = this;
		var defaultComponents = [{"state": "StateMachine"}];
		var useDefaultComponents = true;
		if (typeof options.defaultComponents !== "undefined") {
			useDefaultComponents = options.defaultComponents ? true : false;
			if (options.defaultComponents instanceof Array) {
				defaultComponents = options.defaultComponents;
			}
		}
		if (useDefaultComponents) {
			g.instantiateComponents(defaultComponents);
		}
		g._addDefaultComponents(options);
		if (typeof options.instantiateComponents === "object") {
			g.instantiateComponents(options.instantiateComponents);
		}
		g._addStages(options);
		g._addDefaultStates();
		g.state._setupTransitionLinks();
		g.state.start("boot");
		return this;
	}

	// `components` should be an array of objects with one or two properties,
	// like: {"loop": "Loop", "options": { ...etc... }}
	// One property can be "options", while the other is a key-value pair for
	// the component's new property name and the associated component class.
	function instantiateComponents(components) {
		var g = this;
		components.forEach(function(component){
			var options = undefined;
			var key;
			var compClass;
			if (typeof component.options !== "undefined") {
				options = component.options;
				delete component.options;
			}
			for (key in component) {
				compClass = component[key];
				console.log("Instantiating component class", compClass, "as", key, "with options", options);
				g.addComponent(key, compClass, options);
			}
		});
		return g;
	}

	function addComponent(gameCompName, componentClass, arg){
		var g = this;
		if (RocketBoots.hasComponent(componentClass)) {
			//console.log("RB adding component", gameCompName, "to the game using class", componentClass, "and arguments:", arg);
			g[gameCompName] = new RocketBoots[componentClass](arg);
		} else {
			console.warn(componentClass, "not found as a RocketBoots component");
		}
		return g;
	}

	function _addDefaultStates() {
		var g = this;
		// Setup default states (mostly menu controls)
		/*
		var startMenu = function(){
			//$('header, footer').show();
		};
		var endMenu = function(){
			//$('header, footer').hide();
		}
		*/
		g.state.addStates({
			"boot": { 		autoView: true },
			"preload": { 	autoView: true },
			/*
			"mainmenu": { 	autoView: true, start: startMenu, end: endMenu },
			"new": { 		autoView: true, start: startMenu, end: endMenu },
			"save": { 		autoView: true, start: startMenu, end: endMenu },
			"load": { 		autoView: true, start: startMenu, end: endMenu },
			"help": { 		autoView: true, start: startMenu, end: endMenu },
			"settings": { 	autoView: true, start: startMenu, end: endMenu },
			"credits": { 	autoView: true, start: startMenu, end: endMenu },
			"share": { 		autoView: true, start: startMenu, end: endMenu },
			*/
			"game": {}
		});
		/*
		g.state.add("game",{
			start : function(){
				$('header, footer').hide();
				this.$view.show();
			}, end : function(){
				$('header, footer').show();
				this.$view.hide();
			}
		});
		*/

		//g.state.get("game").$view.show();

		return g;
	}

	function _addStages(options) {
		var g = this;
		var stageData;
		if (typeof RocketBoots.Stage !== "function") {
			return g;
		}
		if (typeof options.stages === 'object') {
			stageData = options.stages;
		} else if (typeof options.stage === 'object') {
			stageData = [options.stage];
		} else {
			return g;
		}
		if (stageData.length > 0) {
			g.stages = g.stages || [];
			$.each(stageData, function(i, stageOptions){
				g.stages[i] = new RocketBoots.Stage(stageOptions);
				if (typeof stageOptions.layerNames === 'object') {
					$.each(stageOptions.layerNames, function(x, layerName){
						g.stages[i].addLayer(layerName);
					});
				}
				g.stages[i].resize();
			});
			g.stage = g.stages[0];
		}
		return g;
	}

})();<|endoftext|>


<commit_before>import React from 'react'
import ReactDom from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './components/App'

const render = (Component) => {
  ReactDom.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root'),
  )
}

render(App)

if (module.hot) {
  module.hot.accept('./components/App', () => {
    render(App)
  })
}

if (process.env.NODE_ENV === 'production') {
  // eslint-disable-next-line
  require('offline-plugin/runtime').install()
}
<commit_msg>Make eslint comment more specific<commit_after>import React from 'react'
import ReactDom from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './components/App'

const render = (Component) => {
  ReactDom.render(
    <AppContainer>
      <Component />
    </AppContainer>,
    document.getElementById('root'),
  )
}

render(App)

if (module.hot) {
  module.hot.accept('./components/App', () => {
    render(App)
  })
}

if (process.env.NODE_ENV === 'production') {
  // eslint-disable-next-line global-require
  require('offline-plugin/runtime').install()
}
<|endoftext|>