<commit_before>const apiVersion = '1.0.0';
var Manager = require("dl-module").managers.sales.ProductionOrderManager;
var resultFormatter = require("../../../result-formatter");
var db = require("../../../db");
var JwtRouterFactory = require("../../jwt-router-factory");

var passport = require("../../../passports/jwt-passport");

var handlePdfRequest = function (request, response, next) {
    var user = request.user;
    var id = request.params.id;
    var manager;
    db.get()
        .then((db) => {
            manager = new Manager(db, user);
            return manager.getSingleByIdOrDefault(id);
        })
        .then((productionOrder) => {
            manager.pdf(productionOrder._id)
                .then((productionOrderDocBinary) => {
                    response.writeHead(200, {
                        "Content-Type": "application/pdf",
                        "Content-Disposition": `attachment; filename=${productionOrder.orderNo}.pdf`,
                        "Content-Length": productionOrderDocBinary.length
                    });
                    response.end(productionOrderDocBinary);
                })
                .catch((e) => {
                    var error = resultFormatter.fail(apiVersion, 400, e);
                    response.send(400, error);
                })
        })
}

function getRouter() {
    var router = JwtRouterFactory(Manager, {
        version: apiVersion,
        defaultOrder: {
            "_updatedDate": -1
        }
    });

    var getManager = (user) => {
        return db.get()
            .then((db) => {
                return Promise.resolve(new Manager(db, user));
            });
    };

    var route = router.routes["get"].find((route) => route.options.path === "/:id");
    var originalHandler = route.handlers[route.handlers.length - 1];
    route.handlers[route.handlers.length - 1] = function (request, response, next) {
        var isPDFRequest = (request.headers.accept || "").toString().indexOf("application/pdf") >= 0;
        if (isPDFRequest) {
            next()
        }
        else {
            originalHandler(request, response, next);
        }
    };
    route.handlers.push(handlePdfRequest);

    //Update is completed
    router.put("/update/is-completed", passport, (request, response, next) => {
        var user = request.user;
        var ids = request.body.data;

        getManager(user)
            .then((manager) => {
                return manager.updateIsCompleted(ids)
                    .then((id) => {
                        var result;
                        if (!id) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });

    //Update is requested
    router.put("/update/is-requested", passport, (request, response, next) => {
        var user = request.user;
        var ids = request.body.data;

        getManager(user)
            .then((manager) => {
                return manager.updateIsRequested(ids)
                    .then((id) => {
                        var result;
                        if (!id) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });

    //Update distributed quantity
    router.put("/update/distributed-quantity", passport, (request, response, next) => {
        var user = request.user;
        var data = request.body.data;

        getManager(user)
            .then((manager) => {
                return manager.updateDistributedQuantity(data)
                    .then((datum) => {
                        var result;
                        if (!datum) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });
    return router;
}

module.exports = getRouter;<commit_msg>Update when updating isRequested, isCompleted. and distributedQuantity<commit_after>const apiVersion = '1.0.0';
var Manager = require("dl-module").managers.sales.ProductionOrderManager;
var resultFormatter = require("../../../result-formatter");
var db = require("../../../db");
var JwtRouterFactory = require("../../jwt-router-factory");

var passport = require("../../../passports/jwt-passport");

var handlePdfRequest = function (request, response, next) {
    var user = request.user;
    var id = request.params.id;
    var manager;
    db.get()
        .then((db) => {
            manager = new Manager(db, user);
            return manager.getSingleByIdOrDefault(id);
        })
        .then((productionOrder) => {
            manager.pdf(productionOrder._id)
                .then((productionOrderDocBinary) => {
                    response.writeHead(200, {
                        "Content-Type": "application/pdf",
                        "Content-Disposition": `attachment; filename=${productionOrder.orderNo}.pdf`,
                        "Content-Length": productionOrderDocBinary.length
                    });
                    response.end(productionOrderDocBinary);
                })
                .catch((e) => {
                    var error = resultFormatter.fail(apiVersion, 400, e);
                    response.send(400, error);
                })
        })
}

function getRouter() {
    var router = JwtRouterFactory(Manager, {
        version: apiVersion,
        defaultOrder: {
            "_updatedDate": -1
        }
    });

    var getManager = (user) => {
        return db.get()
            .then((db) => {
                return Promise.resolve(new Manager(db, user));
            });
    };

    var route = router.routes["get"].find((route) => route.options.path === "/:id");
    var originalHandler = route.handlers[route.handlers.length - 1];
    route.handlers[route.handlers.length - 1] = function (request, response, next) {
        var isPDFRequest = (request.headers.accept || "").toString().indexOf("application/pdf") >= 0;
        if (isPDFRequest) {
            next()
        }
        else {
            originalHandler(request, response, next);
        }
    };
    route.handlers.push(handlePdfRequest);

    //Update is completed
    router.put("/update/is-completed", passport, (request, response, next) => {
        var user = request.user;
        var data = request.body;

        getManager(user)
            .then((manager) => {
                return manager.updateIsCompleted(data)
                    .then((id) => {
                        var result;
                        if (!id) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });

    //Update is requested
    router.put("/update/is-requested", passport, (request, response, next) => {
        var user = request.user;
        var data = request.body;

        getManager(user)
            .then((manager) => {
                return manager.updateIsRequested(data)
                    .then((id) => {
                        var result;
                        if (!id) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });

    //Update distributed quantity
    router.put("/update/distributed-quantity", passport, (request, response, next) => {
        var user = request.user;
        var data = request.body;

        getManager(user)
            .then((manager) => {
                return manager.updateDistributedQuantity(data)
                    .then((datum) => {
                        var result;
                        if (!datum) {
                            result = resultFormatter.fail(apiVersion, 404, new Error("data not found"));
                            return Promise.resolve(result);
                        }
                        else {
                            result = resultFormatter.ok(apiVersion, 204);
                            return Promise.resolve(result);
                        }
                    });
            })
            .then((result) => {
                response.send(result.statusCode, result);
            })
            .catch((e) => {
                var statusCode = 500;
                if (e.name === "ValidationError")
                    statusCode = 400;
                var error = resultFormatter.fail(apiVersion, statusCode, e);
                response.send(statusCode, error);
            });
    });
    return router;
}

module.exports = getRouter;<|endoftext|>


<commit_before>/*{
  "id":"gps",
	"scope":["server"],
	"desc":"interface for gps serial data"
}*/

var serial = require('serialport')
var through = require('through')

module.exports = GPS

var Parser = function () {

  function decimalDegrees (coordinate, direction) {
    var parts = coordinate.split('.');
    var sign = 1;
    var degrees;
    var minutes;
    var seconds;

    if (parts[0].length === 4) {
      degrees = parseInt(parts[0].substr(0, 2), 10);
      minutes = parseInt(parts[0].substr(2, 2), 10);
      seconds = parseFloat('0.' + parts[1]) * 60.0;

      if (direction.toLowerCase() === 's') {
        sign = -1;
      }
    } else if (parts[0].length === 5) {
      degrees = parseInt(parts[0].substr(0, 3), 10);
      minutes = parseInt(parts[0].substr(3, 2), 10);
      seconds = parseFloat('0.' + parts[1]) * 60.0;

      if (direction.toLowerCase() === 'w') {
        sign = -1;
      }
    }
    return sign * (degrees + minutes / 60.0 + seconds / 3600.0);
  }

  this.GPRMC = function (data, cb) { // gets called for GPRMC mssgs
    var o = {
      code:data[0],
      status:data[3],
      latitude:decimalDegrees(data[4], data[5]),
      longitude:decimalDegrees(parts[6], parts[7]),
      speedOverGroundInKnots:parseFloat(data[8]),
      courseOverGround:parseFloat(data[9])
    }
    cb(null,o)
  }
}

function Gps (opts) {
  var self = this
  var parser = new Parser

  if (!opts) {
    opts = {
      port:'/dev/ttyAMA0',
      baud:9600
    }
  }

  var serialStream = new serial.SerialPort(opts.port, {
    baudrate:opts.baud,
    parser:serial.parsers.readline('\n')
  })

  var s = through(function write (chunk) {
    var sentence = chunk.substring(1).split(',')
    var type = sentence[0]
    if (parser[type]) {
      parser[type](sentence, function handleData (e, json) {
        if (e) this.emit('error', e)
        if (!e) this.emit('data', json)
      })
    }
    if (!parser[type]) self.emit('error', 'NMEA sentence unknown')

  }, function end () {
    this.emit('end')
  })

  serialStream.pipe(s)

  return s
}
<commit_msg>removed excess stuff in gps<commit_after>/*{
  "id":"gps",
	"scope":["server"],
	"desc":"interface for gps serial data"
}*/

var serial = require('serialport')
var through = require('through')

module.exports = GPS

var Parser = function () {

  function decimalDegrees (coordinate, direction) {
    var parts = coordinate.split('.');
    var sign = 1;
    var degrees;
    var minutes;
    var seconds;

    if (parts[0].length === 4) {
      degrees = parseInt(parts[0].substr(0, 2), 10);
      minutes = parseInt(parts[0].substr(2, 2), 10);
      seconds = parseFloat('0.' + parts[1]) * 60.0;

      if (direction.toLowerCase() === 's') {
        sign = -1;
      }
    } else if (parts[0].length === 5) {
      degrees = parseInt(parts[0].substr(0, 3), 10);
      minutes = parseInt(parts[0].substr(3, 2), 10);
      seconds = parseFloat('0.' + parts[1]) * 60.0;

      if (direction.toLowerCase() === 'w') {
        sign = -1;
      }
    }
    return sign * (degrees + minutes / 60.0 + seconds / 3600.0);
  }

  this.GPRMC = function (data, cb) { // gets called for GPRMC mssgs
    var o = {
      code:data[0],
      status:data[3],
      latitude:decimalDegrees(data[4], data[5]),
      longitude:decimalDegrees(parts[6], parts[7]),
      speedOverGroundInKnots:parseFloat(data[8]),
      courseOverGround:parseFloat(data[9])
    }
    cb(null,o)
  }
}

function Gps (opts) {
  var self = this
  var parser = new Parser

  if (!opts) {
    opts = {
      port:'/dev/ttyAMA0',
      baud:9600
    }
  }

  var serialStream = new serial.SerialPort(opts.port, {
    baudrate:opts.baud,
    parser:serial.parsers.readline('\n')
  })

  var s = through(function write (chunk) {
    var sentence = chunk.substring(1).split(',')
    var type = sentence[0]
    if (parser[type]) {
      parser[type](sentence, function handleData (e, json) {
        if (e) this.emit('error', e)
        if (!e) this.emit('data', json)
      })
    }
    if (!parser[type]) self.emit('error', 'NMEA sentence unknown')
  }, function end () {
    this.emit('end')
  })

  serialStream.pipe(s)

  return s
}
<|endoftext|>


<commit_before>module.exports = {
  pathPrefix: '/docs',
  siteMetadata: {
    siteTitle: 'Storybook',
    baseColor: '#e64074',
    linkPrefix: '/',

    docSections: {
      basics: [
        '/basics/introduction/',
        '/basics/writing-stories/',
        '/basics/exporting-storybook/',
        '/basics/faq/',
        '/basics/live-examples/',
      ],
      guides: [
        '/guides/quick-start-guide/',
        '/guides/slow-start-guide/',
        '/guides/guide-react/',
        '/guides/guide-react-native/',
        '/guides/guide-vue/',
        '/guides/guide-angular/',
        '/guides/guide-mithril/',
        '/guides/guide-ember/',
        '/guides/guide-riot/',
      ],
      configurations: [
        '/configurations/options-parameter/',
        '/configurations/default-config/',
        '/configurations/custom-webpack-config/',
        '/configurations/custom-babel-config/',
        '/configurations/typescript-config/',
        '/configurations/add-custom-head-tags/',
        '/configurations/serving-static-files/',
        '/configurations/env-vars/',
        '/configurations/theming/',
        '/configurations/cli-options/',
        '/configurations/standalone-options/',
      ],
      testing: [
        '/testing/react-ui-testing/',
        '/testing/structural-testing/',
        '/testing/interaction-testing/',
        '/testing/automated-visual-testing/',
        '/testing/manual-testing/',
      ],
      addons: [
        '/addons/introduction/',
        '/addons/using-addons/',
        '/addons/writing-addons/',
        '/addons/api/',
      ],
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {
        repoUrl: 'https://github.com/storybooks/storybook',
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 690,
            },
          },
          'gatsby-remark-autolink-headers',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-plugin-sharp',
  ],
};
<commit_msg>Fix "Storybook for HTML" Edit link (#6658)<commit_after>module.exports = {
  pathPrefix: '/docs',
  siteMetadata: {
    siteTitle: 'Storybook',
    baseColor: '#e64074',
    linkPrefix: '/',

    docSections: {
      basics: [
        '/basics/introduction/',
        '/basics/writing-stories/',
        '/basics/exporting-storybook/',
        '/basics/faq/',
        '/basics/live-examples/',
      ],
      guides: [
        '/guides/quick-start-guide/',
        '/guides/slow-start-guide/',
        '/guides/guide-html/',
        '/guides/guide-react/',
        '/guides/guide-react-native/',
        '/guides/guide-vue/',
        '/guides/guide-angular/',
        '/guides/guide-mithril/',
        '/guides/guide-ember/',
        '/guides/guide-riot/',
      ],
      configurations: [
        '/configurations/options-parameter/',
        '/configurations/default-config/',
        '/configurations/custom-webpack-config/',
        '/configurations/custom-babel-config/',
        '/configurations/typescript-config/',
        '/configurations/add-custom-head-tags/',
        '/configurations/serving-static-files/',
        '/configurations/env-vars/',
        '/configurations/theming/',
        '/configurations/cli-options/',
        '/configurations/standalone-options/',
      ],
      testing: [
        '/testing/react-ui-testing/',
        '/testing/structural-testing/',
        '/testing/interaction-testing/',
        '/testing/automated-visual-testing/',
        '/testing/manual-testing/',
      ],
      addons: [
        '/addons/introduction/',
        '/addons/using-addons/',
        '/addons/writing-addons/',
        '/addons/api/',
      ],
    },
  },
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        name: 'pages',
        path: `${__dirname}/src/pages/`,
      },
    },
    {
      resolve: `gatsby-plugin-styled-components`,
      options: {
        repoUrl: 'https://github.com/storybooks/storybook',
      },
    },
    {
      resolve: 'gatsby-transformer-remark',
      options: {
        plugins: [
          {
            resolve: 'gatsby-remark-images',
            options: {
              maxWidth: 690,
            },
          },
          'gatsby-remark-autolink-headers',
          'gatsby-remark-copy-linked-files',
          'gatsby-remark-smartypants',
        ],
      },
    },
    'gatsby-plugin-sharp',
  ],
};
<|endoftext|>


<commit_before>(function() {
  const NS = 'http://www.w3.org/2000/svg';
  // const XMLNS = 'http://www.w3.org/2000/xmlns/';
  // const XLINK = 'http://www.w3.org/1999/xlink';
  const VERSION = '1.1';

  var mixin = {
    // TODO: add elements to SVG dom as they are created in js
    renderSVG(width, height) {
      var create = function(element, type) {
        var svg = document.createElementNS(NS, type);
        element.dom.svg = svg;
        return svg;
      };

      var calcX = function(element) {
        return draft.px(element.prop('x')) - draft.px(element.width()) / 2;
      };

      var calcY = function(element) {
        return -draft.px(element.prop('y')) - draft.px(element.height()) / 2;
      };

      var svgRoot = create(this, 'svg');
      svgRoot.setAttribute('xmlns', NS);
      svgRoot.setAttribute('version', VERSION);
      // svgRoot.setAttributeNS(XMLNS, 'xmlns:xlink', XLINK);

      svgRoot.setAttribute('id', this.domID);
      svgRoot.setAttribute('width', width);
      if (height !== undefined) {
        svgRoot.setAttribute('height', height);
      }

      // 1 SVG user unit = 1px
      svgRoot.setAttribute('viewBox', [
        calcX(this), calcY(this),
        draft.px(this.width()), draft.px(this.height())
      ].join(' '));

      // TODO: move this to draft.js
      var recursive = function(obj, func) {
        for (var key in obj) {
          recursive(obj[key] instanceof Array ?
            obj[key] : func(obj, key), func);
        }
      };

      recursive(this, function(obj, key) {
        if (key === 'parent' ||
          obj[key] instanceof draft.Doc ||
          obj[key] instanceof draft.View) {
          return false;
        } else if (obj[key] instanceof draft.Element) {
          console.info('rendering:', obj[key].prop());

          var type = obj[key].type;
          var listener;

          // TODO: modularize svg creation
          var svg = create(obj[key], type);
          obj[key].parent.dom.svg.appendChild(svg);
          svg.setAttribute('fill-opacity', 0);
          svg.setAttribute('stroke', '#000');

          // TODO: separate listener for each property?
          if (type === 'rect') {
            listener = function(prop, val) {
              val = draft.px(val);

              if (prop === 'width') {
                svg.setAttribute('width', draft.px(val));
              } else if (prop === 'height') {
                svg.setAttribute('height', draft.px(val));
              }

              if (prop === 'x' || prop === 'width') {
                svg.setAttribute('x', calcX(this.target));
              } else if (prop === 'y' || prop === 'height') {
                svg.setAttribute('y', calcY(this.target));
              }
              // svg.setAttribute('x', );
            };

            listener.apply({target: obj[key]}, ['width', obj[key].width()]);
            listener.apply({target: obj[key]}, ['height', obj[key].height()]);
            listener.apply({target: obj[key]}, ['x', obj[key].prop('x')]);
            listener.apply({target: obj[key]}, ['y', obj[key].prop('y')]);
            // svg.setAttribute('x', );
          } else if (type === 'circle') {
            listener = function(prop, val) {
              val = draft.px(val);

              if (prop === 'r') {
                svg.setAttribute('r', val);
              } else if (prop === 'x') {
                svg.setAttribute('cx', draft.px(val));
              } else if (prop === 'y') {
                svg.setAttribute('cy', -draft.px(val));
              }
            };

            listener('r', obj[key].radius());
          }

          obj[key].on('change', listener);

          return obj[key];
        }
      });

      return svgRoot;
    }
  };

  draft.Page.mixin(mixin);
  draft.View.mixin(mixin);
})();
<commit_msg>Clean up various small things<commit_after>(function() {
  const NS = 'http://www.w3.org/2000/svg';
  // const XMLNS = 'http://www.w3.org/2000/xmlns/';
  // const XLINK = 'http://www.w3.org/1999/xlink';
  const VERSION = '1.1';

  var mixin = {
    // TODO: add elements to SVG dom as they are created in js
    renderSVG(width, height) {
      var create = function(element, type) {
        var svg = document.createElementNS(NS, type);
        element.dom.svg = svg;
        return svg;
      };

      var calcX = function(element) {
        return draft.px(element.prop('x')) - draft.px(element.width()) / 2;
      };

      var calcY = function(element) {
        return -draft.px(element.prop('y')) - draft.px(element.height()) / 2;
      };

      var svgRoot = create(this, 'svg');
      svgRoot.setAttribute('xmlns', NS);
      svgRoot.setAttribute('version', VERSION);
      // svgRoot.setAttributeNS(XMLNS, 'xmlns:xlink', XLINK);

      svgRoot.setAttribute('id', this.domID);
      svgRoot.setAttribute('width', width);
      if (height !== undefined) {
        svgRoot.setAttribute('height', height);
      }

      // 1 SVG user unit = 1px
      svgRoot.setAttribute('viewBox', [
        calcX(this), calcY(this),
        draft.px(this.width()), draft.px(this.height())
      ].join(' '));

      // TODO: move this to draft.js
      var recursive = function(obj, func) {
        for (let key in obj) {
          recursive(Array.isArray(obj[key]) ?
            obj[key] : func(obj, key), func);
        }
      };

      recursive(this, function(obj, key) {
        if (key === 'parent' ||
          obj[key] instanceof draft.Doc ||
          obj[key] instanceof draft.View) {
          return false;
        } else if (obj[key] instanceof draft.Element) {
          console.info('rendering svg:', obj[key].prop());

          var type = obj[key].type;
          var listener;

          // TODO: modularize svg creation
          var svg = create(obj[key], type);
          obj[key].parent.dom.svg.appendChild(svg);
          svg.setAttribute('fill-opacity', 0);
          svg.setAttribute('stroke', '#000');

          // TODO: separate listener for each property?
          if (type === 'rect') {
            listener = function(prop, val) {
              val = draft.px(val);

              if (prop === 'width') {
                svg.setAttribute('width', draft.px(val));
              } else if (prop === 'height') {
                svg.setAttribute('height', draft.px(val));
              }

              if (prop === 'x' || prop === 'width') {
                svg.setAttribute('x', calcX(this.target));
              } else if (prop === 'y' || prop === 'height') {
                svg.setAttribute('y', calcY(this.target));
              }
              // svg.setAttribute('x', );
            };

            listener.apply({target: obj[key]}, ['width', obj[key].width()]);
            listener.apply({target: obj[key]}, ['height', obj[key].height()]);
            listener.apply({target: obj[key]}, ['x', obj[key].prop('x')]);
            listener.apply({target: obj[key]}, ['y', obj[key].prop('y')]);
            // svg.setAttribute('x', );
          } else if (type === 'circle') {
            listener = function(prop, val) {
              val = draft.px(val);

              if (prop === 'r') {
                svg.setAttribute('r', val);
              } else if (prop === 'x') {
                svg.setAttribute('cx', draft.px(val));
              } else if (prop === 'y') {
                svg.setAttribute('cy', -draft.px(val));
              }
            };

            listener('r', obj[key].radius());
          }

          obj[key].on('change', listener);

          return obj[key];
        }
      });

      return svgRoot;
    }
  };

  draft.Page.mixin(mixin);
  draft.View.mixin(mixin);
})();
<|endoftext|>


<commit_before>import AppCacheActionCreators from 'actions/AppCacheActionCreators';
//import AppCacheStore from 'stores/AppCacheStore';

class AppCache {
  constructor() {

    window.addEventListener('load', () => {

      window.applicationCache.addEventListener('updateready', this.onUpdateReady);

      // Check applications cache for update every 10 mins.
      setInterval(() => {
        window.applicationCache.update();
      }, 60000);

    }, false);

  }

  onUpdateReady() {

    window.applicationCache.swapCache();

    AppCacheActionCreators.openModal();
  }
}

const AppCacheInstance = new AppCache();

export default AppCacheInstance;
<commit_msg>feat(web): check appcache for updates every 10 minutes;<commit_after>import AppCacheActionCreators from 'actions/AppCacheActionCreators';
//import AppCacheStore from 'stores/AppCacheStore';

class AppCache {
  constructor() {

    window.addEventListener('load', () => {

      window.applicationCache.addEventListener('updateready', this.onUpdateReady);

      // Check applications cache for update every 10 mins.
      setInterval(() => {
        window.applicationCache.update();
      }, 600000);

    }, false);

  }

  onUpdateReady() {

    window.applicationCache.swapCache();

    AppCacheActionCreators.openModal();
  }
}

const AppCacheInstance = new AppCache();

export default AppCacheInstance;
<|endoftext|>


<commit_before>/* Copyright (C) 2013 Justin Windle, http://soulwire.co.uk */
!function(e,t){"object"==typeof exports?module.exports=t(e,e.document):"function"==typeof define&&define.amd?define(function(){return t(e,e.document)}):e.Sketch=t(e,e.document)}("undefined"!=typeof window?window:this,function(e,t){"use strict";function n(e){return"[object Array]"==Object.prototype.toString.call(e)}function o(e){return"function"==typeof e}function r(e){return"number"==typeof e}function i(e){return"string"==typeof e}function u(e){return C[e]||String.fromCharCode(e)}function a(e,t,n){for(var o in t)!n&&o in e||(e[o]=t[o]);return e}function c(e,t){return function(){e.apply(t,arguments)}}function l(e){var t={};for(var n in e)"webkitMovementX"!==n&&"webkitMovementY"!==n&&(o(e[n])?t[n]=c(e[n],e):t[n]=e[n]);return t}function s(e){function t(t){o(t)&&t.apply(e,[].splice.call(arguments,1))}function n(e){for(_=0;_<ee.length;_++)B=ee[_],i(B)?S[(e?"add":"remove")+"EventListener"].call(S,B,N,!1):o(B)?N=B:S=B}function r(){I(A),A=R(r),K||(t(e.setup),K=o(e.setup)),U||(t(e.resize),U=o(e.resize)),e.running&&!q&&(e.dt=(z=+new Date)-e.now,e.millis+=e.dt,e.now=z,t(e.update),Z&&(e.retina&&(e.save(),e.autoclear&&e.scale(V,V)),e.autoclear&&e.clear()),t(e.draw),Z&&e.retina&&e.restore()),q=++q%e.interval}function c(){S=J?e.style:e.canvas,D=J?"px":"",Y=e.width,j=e.height,e.fullscreen&&(j=e.height=v.innerHeight,Y=e.width=v.innerWidth),e.retina&&Z&&V&&(S.style.height=j+"px",S.style.width=Y+"px",Y*=V,j*=V),S.height!==j&&(S.height=j+D),S.width!==Y&&(S.width=Y+D),Z&&!e.autoclear&&e.retina&&e.scale(V,V),K&&t(e.resize)}function s(e,t){return L=t.getBoundingClientRect(),e.x=e.pageX-L.left-(v.scrollX||v.pageXOffset),e.y=e.pageY-L.top-(v.scrollY||v.pageYOffset),e}function f(t,n){return s(t,e.element),n=n||{},n.ox=n.x||t.x,n.oy=n.y||t.y,n.x=t.x,n.y=t.y,n.dx=n.x-n.ox,n.dy=n.y-n.oy,n}function d(e){if(e.preventDefault(),G=l(e),G.originalEvent=e,G.touches)for(Q.length=G.touches.length,_=0;_<G.touches.length;_++)Q[_]=f(G.touches[_],Q[_]);else Q.length=0,Q[0]=f(G,$);return a($,Q[0],!0),G}function p(n){for(n=d(n),M=(X=ee.indexOf(W=n.type))-1,e.dragging=!!/down|start/.test(W)||!/up|end/.test(W)&&e.dragging;M;)i(ee[M])?t(e[ee[M--]],n):i(ee[X])?t(e[ee[X++]],n):M=0}function g(n){F=n.keyCode,H="keyup"==n.type,te[F]=te[u(F)]=!H,t(e[n.type],n)}function m(n){e.autopause&&("blur"==n.type?E:y)(),t(e[n.type],n)}function y(){e.now=+new Date,e.running=!0}function E(){e.running=!1}function k(){(e.running?E:y)()}function P(){Z&&e.clearRect(0,0,e.width*V,e.height*V)}function T(){O=e.element.parentNode,_=b.indexOf(e),O&&O.removeChild(e.element),~_&&b.splice(_,1),n(!1),E()}var A,N,S,O,L,_,D,z,B,G,W,F,H,M,X,Y,j,q=0,Q=[],U=!1,K=!1,V=v.devicePixelRatio||1,J=e.type==w,Z=e.type==h,$={x:0,y:0,ox:0,oy:0,dx:0,dy:0},ee=[e.eventTarget||e.element,p,"mousedown","touchstart",p,"mousemove","touchmove",p,"mouseup","touchend",p,"click",p,"mouseout",p,"mouseover",x,g,"keydown","keyup",v,m,"focus","blur",c,"resize"],te={};for(F in C)te[C[F]]=!1;return a(e,{touches:Q,mouse:$,keys:te,dragging:!1,running:!1,millis:0,now:NaN,dt:NaN,destroy:T,toggle:k,clear:P,start:y,stop:E}),b.push(e),e.autostart&&y(),n(!0),c(),r(),e}for(var f,d,p="E LN10 LN2 LOG2E LOG10E PI SQRT1_2 SQRT2 abs acos asin atan ceil cos exp floor log round sin sqrt tan atan2 pow max min".split(" "),g="__hasSketch",m=Math,h="canvas",y="webgl",w="dom",x=t,v=e,b=[],E={fullscreen:!0,autostart:!0,autoclear:!0,autopause:!0,container:x.body,interval:1,globals:!0,retina:!1,type:h},C={8:"BACKSPACE",9:"TAB",13:"ENTER",16:"SHIFT",27:"ESCAPE",32:"SPACE",37:"LEFT",38:"UP",39:"RIGHT",40:"DOWN"},k={CANVAS:h,WEB_GL:y,WEBGL:y,DOM:w,instances:b,install:function(e){if(!e[g]){for(var t=0;t<p.length;t++)e[p[t]]=m[p[t]];a(e,{TWO_PI:2*m.PI,HALF_PI:m.PI/2,QUARTER_PI:m.PI/4,random:function(e,t){return n(e)?e[~~(m.random()*e.length)]:(r(t)||(t=e||1,e=0),e+m.random()*(t-e))},lerp:function(e,t,n){return e+n*(t-e)},map:function(e,t,n,o,r){return(e-t)/(n-t)*(r-o)+o}}),e[g]=!0}},create:function(e){return e=a(e||{},E),e.globals&&k.install(self),f=e.element=e.element||x.createElement(e.type===w?"div":"canvas"),d=e.context=e.context||function(){switch(e.type){case h:return f.getContext("2d",e);case y:return f.getContext("webgl",e)||f.getContext("experimental-webgl",e);case w:return f.canvas=f}}(),(e.container||x.body).appendChild(f),k.augment(d,e)},augment:function(e,t){return t=a(t||{},E),t.element=e.canvas||e,t.element.className+=" sketch",a(e,t,!0),s(e)}},P=["ms","moz","webkit","o"],T=self,A=0,N="AnimationFrame",S="request"+N,O="cancel"+N,R=T[S],I=T[O],L=0;L<P.length&&!R;L++)R=T[P[L]+"Request"+N],I=T[P[L]+"Cancel"+N];return T[S]=R=R||function(e){var t=+new Date,n=m.max(0,16-(t-A)),o=setTimeout(function(){e(t+n)},n);return A=t+n,o},T[O]=I=I||function(e){clearTimeout(e)},k});<commit_msg>Delete sketch.min.js<commit_after><|endoftext|>


<commit_before>"enable aexpr";

import Morph from 'src/components/widgets/lively-morph.js';
import { deepMapKeys } from 'src/client/rename_obj.js';
import { debounce } from "utils";

const visType1Conf = [
    {
      name: 'Name',
      type: 'primitive',
    },
    {
      name: 'Value',
      type: 'number',
    }
  ];

const visType2Conf = [
    {
      name: 'Name',
      type: 'primitive',
    },
    {
      name: 'Children',
      type: 'object',
      meta: [
        {
          name: 'Name',
          type: 'primitive'
        },
        {
          name: 'Size',
          type: 'primitive',
          optional: true,
        }
      ]
    }
  ];

const visSettings = {
  'BubbleChart': visType1Conf,
  'BarChart': visType1Conf,
  'RadialTree': visType2Conf,
  'Tree': visType2Conf,
  /** TreeMap is not working correctly as it its position is not set correctly in d3-treemap
  'TreeMap': [
    {
      name: 'Name',
      type: 'string',
    },
    {
      name: 'Children',
      type: 'object',
      meta: [
        {
          name: 'Name',
          type: 'primitive'
        },
        {
          name: 'Size',
          type: 'primitive',
          optional: true,
        }
      ]
    }
  ] **/
}

// map to lively-components
const visualizationComponents = {
  'BubbleChart': 'd3-bubblechart',
  'BarChart': 'd3-barchart-gh',
  'RadialTree': 'd3-radialtree',
  'Tree': 'd3-tree',
  'TreeMap': 'd3-treemap',
}

export default class DataExplorer extends Morph {
  async initialize() {
    this.windowTitle = "DataExplorer";
    this.registerButtons()

    lively.html.registerKeys(this);

    Object.keys(visSettings).forEach(vis => this.get('#visTypeSelection').appendChild(<option value={vis}>{vis}</option>))

    this.get('#visTypeSelection').addEventListener("change", e => this.onVisualizationChange(e))
    this.get('#refinementEnd').addEventListener("change", e => {
      this.endIndex = e.target.value;
      this.sliceData();
    })

    this.get('#refinementStart').addEventListener("change", e => {
      this.startIndex = e.target.value;
      this.sliceData();
    })
    // get first value
    this.selectedVisualizationType = this.get('#visTypeSelection').value;
    this.settingsVisualization = visSettings[this.selectedVisualizationType];
    this.setupParameterVis();
    this.startIndex = 0;
    this.endIndex = 0;

    this.addEventListener('extent-changed', ((evt) => { this.onExtentChanged(evt); })::debounce(500));

    this.visualizationHeight = 400;
  }

  setData(data) {
    this.originalData = data;
    this.data = data;
    this.setupParameterVis();
    this.startIndex = 0;
    this.endIndex = this.data.length;

    this.get('#refinementStart').value = this.startIndex;
    this.get('#refinementEnd').value = this.endIndex;
    this.get('#refinementEnd').max = this.endIndex;
    this.get('#refinementStart').max = this.endIndex;
    this.createCountVariables();
  }

  createCountVariables() {
    this.data.forEach(obj => {
      Object.keys(obj).forEach(key => {
        if(Array.isArray(obj[key])) {
         obj[key + 'COUNT'] = obj[key].length
        }
      });
    });
  }

  sliceData() {
    this.data = this.originalData.slice(this.startIndex, this.endIndex);
    this.setupParameterVis();
  }

  onVisualizationChange(e) {
    this.selectedVisualizationType = e.target.value;
    this.settingsVisualization = visSettings[this.selectedVisualizationType];
    this.setupParameterVis();
  }

  setupParameterVis() {
    const parametersEl = this.get('#parameterSection');
    parametersEl.innerHTML = '';
    this.settingsVisualization.forEach(parameter => {
      let paraEl =

;
      if(parameter.type === 'object' && parameter.meta) {
        paraEl =

;
      }
      paraEl.appendChild({parameter.name} ({parameter.type}):)
      const selection = <select id="name"></select>;
      selection.addEventListener("change", e => this.renderVisualization(e))

      parameter.selection = selection;

      if(this.data && this.data.length > 0) {
        // use first element as base for parameter selection;
        const fields = this.getPossibleFields(parameter);
        fields.forEach(field => {
          selection.appendChild(<option value={field}>{field}</option>);
        });
      }

      paraEl.appendChild(selection);
      this.setObjectParameters(parameter, paraEl);
      parametersEl.appendChild(paraEl);
    });
    this.renderVisualization();
  }

  setObjectParameters(parameter, parameterElement) {
    if(parameter.type === 'object') {
      if(parameter.meta) {
        parameter.meta.forEach(metaParameter => {
          const element =

;
          element.appendChild(
{metaParameter.name} ({metaParameter.type}):
);
          const inputElement = <input></input>;
          inputElement.addEventListener("change", e => this.renderVisualization(e));
          element.appendChild(inputElement)
          metaParameter.input = inputElement;
          parameterElement.appendChild(
{element}
);
        });
      }
    }
  }

  getPossibleFields(parameter) {
    let fields = [];
    switch(parameter.type) {
      case 'number':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'number'){
            fields.push(field);
          }
        });
        return fields;
      case 'object':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'object') {
            fields.push(field);
          }
        })
        return fields;
      case 'array of objects':
        break;
      case 'string':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'string'){
            fields.push(field);
          }
        });
        return fields;
      default:
        Object.keys(this.data[0]).forEach(field => {
          if(this.data[0][field] !== Object(this.data[0][field])){
            fields.push(field);
          }
        });
        return fields;
    }
  }

  renderVisualization(e) {
    this.visualizationEL = this.get('#visualization');
    this.visualizationEL.innerHTML = '';
    switch(this.selectedVisualizationType) {
      case 'BubbleChart':
        this.renderBubbleChart();
        break;
      case 'BarChart':
        this.renderBarChart();
        break;
      case 'RadialTree':
        this.renderTreeType();
        break;
      case 'Tree':
        this.renderTreeType();
        break;
      case 'PlainTree':
        this.renderTreeType();
        break;
      case 'TreeMap':
        this.renderTreeType();
        break;
      default:
        this.renderBubbleChart();
    }
  }

  async renderBubbleChart() {
    const bubbleChart = await lively.create(visualizationComponents[this.selectedVisualizationType]);
    if(this.getBoundingClientRect().width > 10) {
      bubbleChart.setSize(this.getBoundingClientRect().width, this.visualizationHeight);
    } else {
      bubbleChart.setSize(500, this.visualizationHeight);
    }
    const data = {
      children: []
    }

    this.data.forEach(obj => {
      const dataObj = {};
      this.settingsVisualization.forEach(parameter => {
        const selectedField = parameter.selection.value;
        dataObj[parameter.name] = obj[selectedField];
      });
      data.children.push(dataObj)
    })
    bubbleChart.setData(data);
    this.visualizationEL.appendChild(bubbleChart);
  }

  async renderBarChart() {
    const barChart = await lively.create(visualizationComponents[this.selectedVisualizationType]);
    const data = [];
    if(this.getBoundingClientRect().width > 10) {
      barChart.setSize(this.getBoundingClientRect().width, this.visualizationHeight);
    } else {
      barChart.setSize(500, this.visualizationHeight);
    }

    this.data.forEach(obj => {
      const dataObj = {};
      this.settingsVisualization.forEach(parameter => {
        const selectedField = parameter.selection.value;
        dataObj[parameter.name] = obj[selectedField];
      });
      data.push(dataObj)
    })
    barChart.setData(data);
    this.visualizationEL.appendChild(barChart);
  }

  async renderTreeType() {
    const vis = await lively.create(visualizationComponents[this.selectedVisualizationType]);

    const nameField =  this.settingsVisualization[0].selection.value;
    const childField = this.settingsVisualization[1].selection.value;

    const mapShortToLong = {};

    mapShortToLong[nameField] = 'name';
    mapShortToLong[childField] = 'children';

    try {
      mapShortToLong[this.settingsVisualization[1].meta[0].input.value] = 'name';
    } catch(e) {
      lively.notify('Failed to find this value for Name');
    }

    try {
      mapShortToLong[this.settingsVisualization[1].meta[1].input.value] = 'size';
    } catch(e) {
      lively.notify('Failed to find this value for Size');
    }

    vis.style.width = this.get('#content').getBoundingClientRect().width.toString() + 'px';
    vis.style.height = '100%';

    const renamedObject = deepMapKeys({data: this.data}, key => (mapShortToLong[key] || key))

    const data = {
      name: 'data',
      children: renamedObject.data,
    };

    vis.setTreeData(data);
    this.visualizationEL.appendChild(vis);
  }

  livelyMigrate(other) {
    this.data = other.data;
    this.originalData = other.data;
  }

  onExtentChanged() {
    this.renderVisualization()
  }

  async livelyExample() {
    this.setData([{
      sha: "f0df88fd2775f37e023ad628ec7d35a082394b6b",
      author: {
        login: "userdummy",
        company: "companydummy"
      },
      comments: [{
          body: "comment1",
          line: 1,
          position: 10
        },
        {
          body: "comment2",
          line: 5,
          position: 12
        },
        {
          body: "comment3",
          line: 3,
          position: 1
        }
      ],
      tests: []
    }, {
      sha: "abc88fd2775f37e023ad628ec7d35a082394b6a",
      author: {
        login: "anon",
        company: null
      },
      comments: [{
        body: "comment4",
        line: 1,
        position: 1
      }],
      tests: [{
          sha: "f0df88fd2775f37e023ad628ec7d35a082394b6b"
        },
        {
          sha: "ghi88fd2775f37e023ad628ec7d35a082394b6a"
        },
        {
          sha: "jkl88fd2775f37e023ad628ec7d35a082394b6a"
        }
      ]
    }]);
  }

}
<commit_msg>Rename all unused data keys<commit_after>"enable aexpr";

import Morph from 'src/components/widgets/lively-morph.js';
import { deepMapKeys } from 'src/client/rename_obj.js';
import { debounce } from "utils";

const visType1Conf = [
    {
      name: 'Name',
      type: 'primitive',
    },
    {
      name: 'Value',
      type: 'number',
    }
  ];

const visType2Conf = [
    {
      name: 'Name',
      type: 'primitive',
    },
    {
      name: 'Children',
      type: 'object',
      meta: [
        {
          name: 'Name',
          type: 'primitive'
        },
        {
          name: 'Size',
          type: 'number'
        }
      ]
    }
  ];

const visSettings = {
  'BubbleChart': visType1Conf,
  'BarChart': visType1Conf,
  'RadialTree': visType2Conf,
  'Tree': visType2Conf,
  /** TreeMap is not working correctly as it its position is not set correctly in d3-treemap
  'TreeMap': [
    {
      name: 'Name',
      type: 'string',
    },
    {
      name: 'Children',
      type: 'object',
      meta: [
        {
          name: 'Name',
          type: 'primitive'
        },
        {
          name: 'Size',
          type: 'primitive'
        }
      ]
    }
  ] **/
}

// map to lively-components
const visualizationComponents = {
  'BubbleChart': 'd3-bubblechart',
  'BarChart': 'd3-barchart-gh',
  'RadialTree': 'd3-radialtree',
  'Tree': 'd3-tree',
  'TreeMap': 'd3-treemap',
}

function getAllKeys(data) {
  return (
    data.reduce((keys, obj) => (
    keys.concat(Object.keys(obj).filter(key => (
      keys.indexOf(key) === -1))
    )
  ), [])
  );
}

export default class DataExplorer extends Morph {
  async initialize() {
    this.windowTitle = "DataExplorer";
    this.registerButtons()

    lively.html.registerKeys(this);

    Object.keys(visSettings).forEach(vis => this.get('#visTypeSelection').appendChild(<option value={vis}>{vis}</option>))

    this.get('#visTypeSelection').addEventListener("change", e => this.onVisualizationChange(e))
    this.get('#refinementEnd').addEventListener("change", e => {
      this.endIndex = e.target.value;
      this.sliceData();
    })

    this.get('#refinementStart').addEventListener("change", e => {
      this.startIndex = e.target.value;
      this.sliceData();
    })
    // get first value
    this.selectedVisualizationType = this.get('#visTypeSelection').value;
    this.settingsVisualization = visSettings[this.selectedVisualizationType];
    this.setupParameterVis();
    this.startIndex = 0;
    this.endIndex = 0;

    this.addEventListener('extent-changed', ((evt) => { this.onExtentChanged(evt); })::debounce(500));

    this.visualizationHeight = 400;
  }

  setData(data) {
    this.originalData = data;
    this.data = data;
    this.setupParameterVis();
    this.startIndex = 0;
    this.endIndex = this.data.length;

    this.get('#refinementStart').value = this.startIndex;
    this.get('#refinementEnd').value = this.endIndex;
    this.get('#refinementEnd').max = this.endIndex;
    this.get('#refinementStart').max = this.endIndex;
    this.createCountVariables();
  }

  createCountVariables() {
    this.data.forEach(obj => {
      Object.keys(obj).forEach(key => {
        if(Array.isArray(obj[key])) {
         obj[key + 'COUNT'] = obj[key].length
        }
      });
    });
  }

  sliceData() {
    this.data = this.originalData.slice(this.startIndex, this.endIndex);
    this.setupParameterVis();
  }

  onVisualizationChange(e) {
    this.selectedVisualizationType = e.target.value;
    this.settingsVisualization = visSettings[this.selectedVisualizationType];
    this.setupParameterVis();
  }

  setupParameterVis() {
    const parametersEl = this.get('#parameterSection');
    parametersEl.innerHTML = '';
    this.settingsVisualization.forEach(parameter => {
      let paraEl =

;
      if(parameter.type === 'object' && parameter.meta) {
        paraEl =

;
      }
      paraEl.appendChild({parameter.name} ({parameter.type}):)
      const selection = <select id="name"></select>;
      selection.addEventListener("change", e => this.renderVisualization(e))

      parameter.selection = selection;

      if(this.data && this.data.length > 0) {
        // use first element as base for parameter selection;
        const fields = this.getPossibleFields(parameter);
        fields.forEach(field => {
          selection.appendChild(<option value={field}>{field}</option>);
        });
      }

      paraEl.appendChild(selection);
      this.setObjectParameters(parameter, paraEl);
      parametersEl.appendChild(paraEl);
    });
    this.renderVisualization();
  }

  setObjectParameters(parameter, parameterElement) {
    if(parameter.type === 'object') {
      if(parameter.meta) {
        parameter.meta.forEach(metaParameter => {
          const element =

;
          element.appendChild(
{metaParameter.name} ({metaParameter.type}):
);
          const inputElement = <input></input>;
          inputElement.addEventListener("change", e => this.renderVisualization(e));
          element.appendChild(inputElement)
          metaParameter.input = inputElement;
          parameterElement.appendChild(
{element}
);
        });
      }
    }
  }

  getPossibleFields(parameter) {
    let fields = [];
    switch(parameter.type) {
      case 'number':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'number'){
            fields.push(field);
          }
        });
        return fields;
      case 'object':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'object') {
            fields.push(field);
          }
        })
        return fields;
      case 'array of objects':
        break;
      case 'string':
        Object.keys(this.data[0]).forEach(field => {
          if(typeof this.data[0][field] === 'string'){
            fields.push(field);
          }
        });
        return fields;
      default:
        Object.keys(this.data[0]).forEach(field => {
          if(this.data[0][field] !== Object(this.data[0][field])){
            fields.push(field);
          }
        });
        return fields;
    }
  }

  renderVisualization(e) {
    this.visualizationEL = this.get('#visualization');
    this.visualizationEL.innerHTML = '';
    switch(this.selectedVisualizationType) {
      case 'BubbleChart':
        this.renderBubbleChart();
        break;
      case 'BarChart':
        this.renderBarChart();
        break;
      case 'RadialTree':
        this.renderTreeType();
        break;
      case 'Tree':
        this.renderTreeType();
        break;
      case 'PlainTree':
        this.renderTreeType();
        break;
      case 'TreeMap':
        this.renderTreeType();
        break;
      default:
        this.renderBubbleChart();
    }
  }

  async renderBubbleChart() {
    const bubbleChart = await lively.create(visualizationComponents[this.selectedVisualizationType]);
    if(this.getBoundingClientRect().width > 10) {
      bubbleChart.setSize(this.getBoundingClientRect().width, this.visualizationHeight);
    } else {
      bubbleChart.setSize(500, this.visualizationHeight);
    }
    const data = {
      children: []
    }

    this.data.forEach(obj => {
      const dataObj = {};
      this.settingsVisualization.forEach(parameter => {
        const selectedField = parameter.selection.value;
        dataObj[parameter.name] = obj[selectedField];
      });
      data.children.push(dataObj)
    })
    bubbleChart.setData(data);
    this.visualizationEL.appendChild(bubbleChart);
  }

  async renderBarChart() {
    const barChart = await lively.create(visualizationComponents[this.selectedVisualizationType]);
    const data = [];
    if(this.getBoundingClientRect().width > 10) {
      barChart.setSize(this.getBoundingClientRect().width, this.visualizationHeight);
    } else {
      barChart.setSize(500, this.visualizationHeight);
    }

    this.data.forEach(obj => {
      const dataObj = {};
      this.settingsVisualization.forEach(parameter => {
        const selectedField = parameter.selection.value;
        dataObj[parameter.name] = obj[selectedField];
      });
      data.push(dataObj)
    })
    barChart.setData(data);
    this.visualizationEL.appendChild(barChart);
  }

  async renderTreeType() {
    const vis = await lively.create(visualizationComponents[this.selectedVisualizationType]);

    const nameField =  this.settingsVisualization[0].selection.value;
    const childField = this.settingsVisualization[1].selection.value;

    const mapShortToLong = {};

    mapShortToLong[nameField] = 'name';
    mapShortToLong[childField] = 'children';

    try {
      mapShortToLong[this.settingsVisualization[1].meta[0].input.value] = 'name';
    } catch(e) {
      lively.notify('Failed to find this value for Name');
    }

    try {
      mapShortToLong[this.settingsVisualization[1].meta[1].input.value] = 'size';
    } catch(e) {
      lively.notify('Failed to find this value for Size');
    }

    vis.style.width = this.get('#content').getBoundingClientRect().width.toString() + 'px';
    vis.style.height = '100%';

    // rename all unused fields
    const allKeys = getAllKeys(this.data);
    allKeys.forEach(key => {
      if(!(key in mapShortToLong)) {
        // assign a random string
        mapShortToLong[key] = Math.random().toString(36).substring(7);
      }
    })

    const renamedObject = deepMapKeys({data: this.data}, key => (mapShortToLong[key] || key))

    const data = {
      name: 'data',
      children: renamedObject.data,
    };

    vis.setTreeData(data);
    this.visualizationEL.appendChild(vis);
  }

  livelyMigrate(other) {
    this.data = other.data;
    this.originalData = other.data;
  }

  onExtentChanged() {
    this.renderVisualization()
  }

  async livelyExample() {
    this.setData([{
      sha: "f0df88fd2775f37e023ad628ec7d35a082394b6b",
      author: {
        login: "userdummy",
        company: "companydummy"
      },
      comments: [{
          body: "comment1",
          line: 1,
          position: 10
        },
        {
          body: "comment2",
          line: 5,
          position: 12
        },
        {
          body: "comment3",
          line: 3,
          position: 1
        }
      ],
      tests: []
    }, {
      sha: "abc88fd2775f37e023ad628ec7d35a082394b6a",
      author: {
        login: "anon",
        company: null
      },
      comments: [{
        body: "comment4",
        line: 1,
        position: 1
      }],
      tests: [{
          sha: "f0df88fd2775f37e023ad628ec7d35a082394b6b"
        },
        {
          sha: "ghi88fd2775f37e023ad628ec7d35a082394b6a"
        },
        {
          sha: "jkl88fd2775f37e023ad628ec7d35a082394b6a"
        }
      ]
    }]);
  }

}
<|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiNotifier
    ) {
        var currentPage, totalPages, limit = 100;

        $scope.busy = false;
        $scope.assessment_filter_options = [];
        $scope.assessment_filter = '';

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        $scope.$watch('assessment_filter', function(assessment) {
            currentPage = 0;
            totalPages = 0;
            var searchOptions = {skip: currentPage, limit: limit};

            if(assessment) {
                searchOptions.assessments = assessment;
            }

            rgiDocumentSrvc.queryCached(searchOptions, function (response) {
                if(response.reason) {
                    rgiNotifier.error('Load document data failure');
                } else {
                    $scope.count = response.count;
                    $scope.documents = response.data;

                    if($scope.documents.length === 0) {
                        rgiNotifier.error('No documents uploaded');
                    }

                    totalPages = Math.ceil(response.count / limit);
                    currentPage = 1;
                }
            }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
        });

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                var searchOptions = {skip: currentPage, limit: limit};

                if($scope.assessment_filter) {
                    searchOptions.assessments = $scope.assessment_filter;
                }

                rgiDocumentSrvc.query(searchOptions, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };
    });
<commit_msg>add 'Unlink Document' feature<commit_after>'use strict';

angular.module('app')
    .controller('rgiDocumentTableCtrl', ['_', '$scope', '$rootScope', 'rgiDialogFactory', 'rgiAssessmentSrvc', 'rgiDocumentSrvc', 'rgiHttpResponseProcessorSrvc', 'rgiNotifier', function (
        _,
        $scope,
        $rootScope,
        rgiDialogFactory,
        rgiAssessmentSrvc,
        rgiDocumentSrvc,
        rgiHttpResponseProcessorSrvc,
        rgiNotifier
    ) {
        var currentPage, totalPages, limit = 100;

        $scope.busy = false;
        $scope.assessment_filter_options = [];
        $scope.assessment_filter = '';

        rgiAssessmentSrvc.query({}, function (assessments) {
            if(assessments.reason) {
                rgiNotifier.error('No assessments');
            } else {
                assessments.forEach(function(assessment) {
                    $scope.assessment_filter_options.push({
                        value: assessment.assessment_ID,
                        text: assessment.country + ' ' + assessment.year + ' ' + assessment.version
                    });
                });
            }
        });

        $scope.$watch('assessment_filter', function(assessment) {
            currentPage = 0;
            totalPages = 0;
            var searchOptions = {skip: currentPage, limit: limit};

            if(assessment) {
                searchOptions.assessments = assessment;
            }

            rgiDocumentSrvc.queryCached(searchOptions, function (response) {
                if(response.reason) {
                    rgiNotifier.error('Load document data failure');
                } else {
                    $scope.count = response.count;
                    $scope.documents = response.data;

                    if($scope.documents.length === 0) {
                        rgiNotifier.error('No documents uploaded');
                    }

                    totalPages = Math.ceil(response.count / limit);
                    currentPage = 1;
                }
            }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
        });

        $scope.loadMoreDocs = function() {
            if ($scope.busy) {
                return;
            }

            $scope.busy = true;

            if(currentPage < totalPages) {
                var searchOptions = {skip: currentPage, limit: limit};

                if($scope.assessment_filter) {
                    searchOptions.assessments = $scope.assessment_filter;
                }

                rgiDocumentSrvc.query(searchOptions, function (response) {
                    if(response.reason) {
                        rgiNotifier.error('Documents loading failure');
                    } else {
                        $scope.documents = _.union($scope.documents, response.data);
                        currentPage = currentPage + 1;
                        $scope.busy = false;
                    }
                }, rgiHttpResponseProcessorSrvc.getDefaultHandler('Load document data failure'));
            }
        };

        $scope.deleteDocument = function(doc) {
            rgiDialogFactory.deleteDocument($scope, doc);
        };

        $scope.unlink = function(doc) {
            rgiDialogFactory.unlinkDocument($scope, doc);
        };
    }]);
<|endoftext|>


<commit_before>(function ()
{
	'use strict';
	angular
		.module('PLMApp')
		.factory('PancakeView', PancakeView);

	function PancakeView()
	{
		var ctx;
		var canvasWidth;
		var canvasHeight;

		var service = {
			draw: draw,
		};

		return service;

		function initUtils(canvas, pancakeWorld)
		{
			ctx=canvas.getContext('2d');
			canvasWidth = canvas.width;
			canvasHeight = canvas.height;
		};

		function draw(canvas, pancakeWorld)
		{
			initUtils(canvas, pancakeWorld);
			ctx.beginPath();

			//draws edge of our drawArena
			ctx.strokeRect(0,0,canvasWidth,canvasHeight);
			ctx.closePath();

			drawPancake(pancakeWorld);

			drawText(pancakeWorld);
		};

		function drawText(pancakeWorld)
		{
			ctx.beginPath();

			ctx.fillStyle = "rgb(0,0,0)";
			ctx.font = "15px sans-serif";

			if(pancakeWorld.moveCount === 0)
			ctx.fillText(pancakeWorld.moveCount+" Move",5,25);
			else ctx.fillText(pancakeWorld.moveCount+ " Moves",5,25);
			ctx.closePath();
		};

		function drawPancake(pancakeWorld)
		{
			ctx.beginPath();

			//each pancake has its height
			var heightUnit = canvasHeight / pancakeWorld.pancakeStack.length;

			//each pancake has a radius between 1 and 1 * the number of pancakes
			var widthUnit = canvasWidth / (pancakeWorld.pancakeStack.length + 1); //+1 for the edges

			for(var i=0;i<pancakeWorld.pancakeStack.length;i++)
			{
				//each pancake has its radius
				var radius = pancakeWorld.pancakeStack[i].radius;

				//the width depends of the radius
				var x = (canvasWidth / 2) - ((widthUnit * radius) / 2);

				//each pancake takes place in the canvasHeight
				var y = heightUnit * i;

				var width = widthUnit * radius;

				ctx.fillStyle = "#FFFF00";

				//draws pancakes
				ctx.fillRect(x, y, width, heightUnit);

				//draws edges of the pancakes
				ctx.beginPath();
				ctx.fillStyle = "#F00000";
				ctx.strokeRect(x,y,width,heightUnit);
				ctx.closePath();
			}

			ctx.closePath();
		};
	};
})();<commit_msg>add drawCircle<commit_after>(function ()
{
	'use strict';
	angular
		.module('PLMApp')
		.factory('PancakeView', PancakeView);

	function PancakeView()
	{
		var ctx;
		var canvasWidth;
		var canvasHeight;

		var service = {
			draw: draw,
		};

		return service;

		function initUtils(canvas, pancakeWorld)
		{
			ctx=canvas.getContext('2d');
			canvasWidth = canvas.width;
			canvasHeight = canvas.height;
		};

		function draw(canvas, pancakeWorld)
		{
			initUtils(canvas, pancakeWorld);
			ctx.beginPath();

			//draws edge of our drawArena
			ctx.strokeRect(0,0,canvasWidth,canvasHeight);
			ctx.closePath();

			drawPancake(pancakeWorld);
			drawCircle(pancakeWorld);
			drawText(pancakeWorld);
		};

		function drawText(pancakeWorld)
		{
			ctx.beginPath();

			ctx.fillStyle = "rgb(0,0,0)";
			ctx.font = "15px sans-serif";

			if(pancakeWorld.moveCount === 0)
			ctx.fillText(pancakeWorld.moveCount+" Move",5,25);
			else ctx.fillText(pancakeWorld.moveCount+ " Moves",5,25);
			ctx.closePath();
		};

		function drawPancake(pancakeWorld)
		{
			ctx.beginPath();

			//each pancake has its height
			var heightUnit = canvasHeight / pancakeWorld.pancakeStack.length;

			//each pancake has a radius between 1 and 1 * the number of pancakes
			var widthUnit = canvasWidth / (pancakeWorld.pancakeStack.length + 1); //+1 for the edges

			for(var i=0;i<pancakeWorld.pancakeStack.length;i++)
			{

				//each pancake has its radius
				var radius = pancakeWorld.pancakeStack[i].radius;

				//the width depends of the radius
				var x = (canvasWidth / 2) - ((widthUnit * radius) / 2);

				//each pancake takes place in the canvasHeight
				var y = canvasHeight - (heightUnit * i);

				var width = widthUnit * radius;

				ctx.fillStyle = "#FFFF00";

				//draws pancakes
				ctx.fillRect(x, y, width, -heightUnit);

				//draws edges of the pancakes
				ctx.beginPath();
				ctx.fillStyle = "#F00000";
				ctx.strokeRect(x,y,width,-heightUnit);
				ctx.closePath();
			}

			ctx.closePath();
		};

		function drawCircle(pancakeWorld)
		{
			var heightUnit = canvasHeight / pancakeWorld.pancakeStack.length;
			var x = canvasWidth / 2;

			var j = 1;

			for(var i=0;i<pancakeWorld.pancakeStack.length;i++)
			{
				var y = canvasHeight - (heightUnit * j);
				var up = pancakeWorld.pancakeStack[i].radius === (pancakeWorld.pancakeStack[j].radius)+1;
				var down = pancakeWorld.pancakeStack[i].radius === (pancakeWorld.pancakeStack[j].radius)-1;
				if(up || down)
				{
					ctx.beginPath();
					ctx.fillStyle = "#FF00FF";
					ctx.arc(x,y,10,0,2 * Math.PI,false);
					ctx.fill();
					ctx.closePath();
				}
				if(j<pancakeWorld.pancakeStack.length-1)
					j++;

			}
		};

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


<commit_before>/**
 * Mission module
 * Todo. Needs clean up
 * @param parameters
 * @returns {{className: string}}
 * @constructor
 * @memberof svl
 */
function Mission(parameters) {
    var self = { className: "Mission" },
        properties = {
            auditDistance: null,
            auditDistanceFt: null,
            auditDistanceMi: null,
            regionId: null,
            label: null,
            missionId: null,
            level: null,
            isCompleted: false,
            instruction: null,
            completionMessage: null,
            badgeURL: null,
            distance: null,
            distanceFt: null,
            distanceMi: null,
            coverage: null
        },
        _tasksForTheMission = [],
        labelCountsAtCompletion;

    function _init(parameters) {
        if ("regionId" in parameters) setProperty("regionId", parameters.regionId);
        if ("missionId" in parameters) setProperty("missionId", parameters.missionId);
        if ("level" in parameters) setProperty("level", parameters.level);
        if ("distance" in parameters) setProperty("distance", parameters.distance);
        if ("distanceFt" in parameters) setProperty("distanceFt", parameters.distanceFt);
        if ("distanceMi" in parameters) setProperty("distanceMi", parameters.distanceMi);
        if ("coverage" in parameters) setProperty("coverage", parameters.coverage);
        if ("isCompleted" in parameters) setProperty("isCompleted", parameters.isCompleted);

        if ("label" in parameters) {
            var instruction, completionMessage, badgeURL;
            setProperty("label", parameters.label);
            self.label = parameters.label;  // For debugging. You don't actually need this.
            self.distance = parameters.distance;  // For debugging. You don't actually need this.

            if (parameters.label == "initial-mission") {
                instruction = "Your goal is to audit 1000 feet of the streets " +
                    "in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have completed the first mission. " +
                    "Keep making the city more accessible!";
                badgeURL = svl.rootDirectory + "/img/misc/BadgeInitialMission.png";
            } else if (parameters.label == "distance-mission") {
                var distance = parameters.distance;
                var distanceString = imperialDistance();

                instruction = "Your goal is to audit " + distanceString +
                    " of the streets in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have successfully made " + distanceString +
                    " of this neighborhood accessible.";

                if (distance == 500) {
                    // 2000 ft
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_500.png";
                } else if (distance == 1000) {
                    // 4000 ft
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_1000.png";
                } else {
                    // miles
                    var level = "level" in parameters ? parameters.level : 1;
                    level = (level - 1) % 5 + 1;
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_Level" + level + ".png";
                }
            } else if (parameters.label == "area-coverage-mission") {
                var coverage = parameters.coverage, coverageString = coverage + "%";
                instruction = "Your goal is to audit " + coverageString +
                    " of the streets in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have successfully made " + coverageString +
                    " of this neighborhood accessible.";
                badgeURL = svl.rootDirectory + "/img/misc/Badge" + coverage + "Percent.png";
            } else if (parameters.label == "onboarding") {

            } else {
                console.error("It shouldn't reach here.");
            }
            setProperty("instruction", instruction);
            setProperty("completionMessage", completionMessage);
            setProperty("badgeURL", badgeURL);
        }
    }

    /**
     * Adjust the target distance if the total distance of available tasks are less than the target audit distance
     * @param availableTaskDistance Available task distance in km
     */
    self.adjustTheTargetDistance = function (availableTaskDistance) {
        if (properties.auditDistance && (properties.auditDistance / 1000 > availableTaskDistance)) {
            properties.auditDistance = availableTaskDistance * 1000;
            properties.auditDistanceFt = availableTaskDistance * 3280.84; // km -> ft
            properties.auditedDistanceMi = availableTaskDistance * 0.621371;  // km -> mi
        }
    };

    /**
     * Because the imperial metric system is messed up.
     * @returns {string}
     */
    function imperialDistance () {
        var distance = getProperty("distance");
        if (distance) {
            if (distance < 1500) {
                if (distance == 250) {
                    return "1000 feet";
                } else if (distance == 500) {
                    return "2000 feet";
                } else if (distance == 1000) {
                    return "4000 feet";
                } else {
                    return distance * 3;
                }
            } else {
                var miles = distance % 1500;
                return miles + "miles";
            }
        } else {
            console.error("Distance is null");
        }
    }

    /**
     * Set the property to complete
     */
    function complete () {
        // Play the animation and audio effect after task completion.

        setProperty("isCompleted", true);

        // Update the neighborhood status
        if ("labelContainer" in svl) {
            var regionId = svl.neighborhoodContainer.getCurrentNeighborhood().getProperty("regionId");
            var count = svl.labelContainer.countLabels(regionId);
            svl.statusFieldNeighborhood.setLabelCount(count);
        }

        // Reset the label counter
        if ('labelCounter' in svl) {
            labelCountsAtCompletion = {
                "CurbRamp": svl.labelCounter.countLabel("CurbRamp"),
                "NoCurbRamp": svl.labelCounter.countLabel("NoCurbRamp"),
                "Obstacle": svl.labelCounter.countLabel("Obstacle"),
                "SurfaceProblem": svl.labelCounter.countLabel("SurfaceProblem"),
                "Other": svl.labelCounter.countLabel("Other")
            };
            svl.labelCounter.reset();
        }
    }

    /**
     * Total line distance of the completed tasks in this mission
     * @param unit
     */
    function completedLineDistance (unit) {
        if (!unit) unit = "kilometers";
        var completedTasks = _tasksForTheMission.filter(function (t) { return t.isCompleted(); });
        var distances = completedTasks.map(function (t) { return t.lineDistance(unit); });
        return distances.sum();
    }

    /**
     * Todo. WARNING. This method is not completed yet. DO NOT USE.
     * @param currentTask
     * @param unit
     * @returns {*}
     */
    function computeRoute (currentTask, unit) {
        if ("taskContainer" in svl && svl.taskContainer && "neighborhoodContainer" in svl && svl.neighborhoodContainer) {
            if (!unit) unit = "kilometers";
            var tmpDistance  = currentTask.lineDistance(unit);
            var tasksInARoute = [currentTask];
            var targetDistance = properties.distance / 1000;
            var neighborhood = svl.neighborhoodContainer.getCurrentNeighborhood(); // Todo. Pass this as a parameter
            var incompleteTasks = svl.taskContainer.getIncompleteTasks(neighborhood.getProperty("regionId"));
            var connectedTasks;
            var currentTaskIndex;
            var lastCoordinate;
            var lastPoint;

            if (targetDistance < tmpDistance && incompleteTasks.length == 0) {
                return tasksInARoute;
            }

            // Check if there are any street edges connected to the last coordinate of currentTask's street edge.
            lastCoordinate = currentTask.getLastCoordinate();
            lastPoint = turf.point([lastCoordinate.lng, lastCoordinate.lat]);
            connectedTasks = incompleteTasks.filter(function (t) { return t.isConnectedToAPoint(lastPoint) && tasksInARoute.indexOf(t) < 0});
            if (connectedTasks.length == 0) {
                // Reverse the coordinates in the currentTask's street edge if there are no street edges connected to the current last coordinate
                currentTask.reverseCoordinates();
                lastCoordinate = currentTask.getLastCoordinate();
                lastPoint = turf.point([lastCoordinate.lng, lastCoordinate.lat]);
                connectedTasks = incompleteTasks.filter(function (t) { return t.isConnectedToAPoint(lastPoint) && tasksInARoute.indexOf(t) < 0});
            }

            // Compute a route
            while (targetDistance > tmpDistance && incompleteTasks.length > 0) {
                lastCoordinate = currentTask.getLastCoordinate();
                lastPoint = turf.point([lastCoordinate.lng, lastCoordinate.lat]);
                connectedTasks = incompleteTasks.filter(function (t) { return t.isConnectedToAPoint(lastPoint) && tasksInARoute.indexOf(t) < 0});

                if (connectedTasks.length > 0) {
                    connectedTasks = util.shuffle(connectedTasks);
                    currentTask = connectedTasks[0];
                } else {
                    incompleteTasks = util.shuffle(incompleteTasks);  // Shuffle the incommplete tasks
                    currentTask = incompleteTasks[0];  // get the first item in the array
                }
                currentTaskIndex = incompleteTasks.indexOf(currentTask);
                incompleteTasks.splice(currentTaskIndex, 1);  // Remove the current task from the incomplete tasks

                tasksInARoute.push(currentTask);
                tmpDistance +=  currentTask.lineDistance(unit);
            }
            return tasksInARoute;
        } else {
            return null;
        }
    }

    /**
     * This method returns the label count object
     * @returns {*}
     */
    function getLabelCount () {
        return labelCountsAtCompletion;
    }

    /**
     * Compute and return the mission completion rate
     * @returns {number}
     */
    function getMissionCompletionRate (unit) {
        if (!unit) unit = "kilometers";
        if ("taskContainer" in svl) {
            var neighborhood = svl.neighborhoodContainer.getCurrentNeighborhood();
            var targetDistance = getProperty("distance") / 1000;  // Convert meters to kilometers
            var completedDistance = svl.taskContainer.getCompletedTaskDistance(neighborhood.getProperty("regionId"), unit);
            if (completedDistance > targetDistance) {
                return 1.0;
            }

            var missions = svl.missionContainer.getMissionsByRegionId(neighborhood.getProperty("regionId"));
            var completedMissions = missions.filter(function (m) { return m.isCompleted(); });  // Get the completed missions

            completedMissions = completedMissions.filter(function (m) { return m.getProperty("distance") / 1000 < completedDistance; });
            var lastMissionDistance;
            if (completedMissions.length > 0) {
                lastMissionDistance = completedMissions[completedMissions.length - 1].getProperty("distance") / 1000;
            } else {
                lastMissionDistance = 0;
            }

            return Math.max(0, completedDistance - lastMissionDistance) / (targetDistance - lastMissionDistance);
        } else {
            return 0;
        }
    }

    /** Returns a property */
    function getProperty (key) {
        return key in properties ? properties[key] : null;
    }

    /**
     * Get an array of tasks for this mission
     * @returns {Array}
     */
    function getRoute () {
        return _tasksForTheMission;
    }

    /**
     * Check if the mission is completed or not
     * Todo. Shouldn't it be isComplete rather than isCompleted???
     *
     * @returns {boolean}
     */
    function isCompleted () {
        return getProperty("isCompleted");
    }

    /**
     * Push a completed task into `_tasksForTheMission`
     * @param task
     */
    function pushATaskToTheRoute(task) {
        _tasksForTheMission.push(task);
    }

    /**
     * Sets a property
     */
    function setProperty (key, value) {
        properties[key] = value;
        return this;
    }

    /** Compute the remaining audit distance till complete (in meters) */
    function remainingAuditDistanceTillComplete () {
        var label = getProperty("label");
        if (label) {
            var distance, cumulativeDistanceAudited = 0;  // Todo.
            if (label == "initial-mission") {
                distance = getProperty("level") * 1000;
                return distance - cumulativeDistanceAudited;
            } else if (label == "distance-mission") {
                distance = getProperty("level") * 1000;
                return distance - cumulativeDistanceAudited;
            } else if (label == "area-coverage-mission") {
                return Infinity;
            } else if (label == "neighborhood-coverage-mission") {
                return Infinity;  // Return infinity as this mission does not depend on distance traveled.
            } else {
                return Infinity;  // This should not happen...
            }
        } else {
            return Infinity;  // The label is not specified.
        }
    }

    /**
     * Return a string describing this data
     * @returns {string}
     */
    function toString () {
        return "Mission: " + getProperty("label") + ", Level: "+ getProperty("level") +
            ", Distance: " + getProperty("distance") + ", Coverage " + getProperty("coverage") +
            ", Mission Id: " + getProperty("missionId") + ", Region Id: " + getProperty("regionId") +
            ", Completed: " + getProperty("isCompleted") + "\n";
    }

    /**
     * Return an object that is in a submittable format
     * @returns {{region_id: *, label: *, mission_id: *, level: *, distance: *, coverage: *}}
     */
    function toSubmissionFormat () {
        return {
            region_id: getProperty("regionId"),
            label: getProperty("label"),
            mission_id: getProperty("missionId"),
            level: getProperty("level"),
            distance: getProperty("distance"),
            coverage: getProperty("coverage"),
            deleted: false
        };
    }

    /**
     * Total line distance in this mission.
     * @param unit
     */
    function totalLineDistance (unit) {
        if (unit == "miles") {
            return getProperty("distanceMi");
        } else if (unit == "feet") {
            return getProperty("distanceFt");
        } else {
            return getProperty("distance");
        }
    }
    _init(parameters);

    self.complete = complete;
    self.completedLineDistance = completedLineDistance;
    self.computeRoute = computeRoute;
    self.getLabelCount = getLabelCount;
    self.getProperty = getProperty;
    self.getRoute = getRoute;
    self.getMissionCompletionRate = getMissionCompletionRate;
    self.isCompleted = isCompleted;
    self.pushATaskToTheRoute = pushATaskToTheRoute;
    self.remainingAuditDistanceTillComplete = remainingAuditDistanceTillComplete;
    self.setProperty = setProperty;
    self.toString = toString;
    self.toSubmissionFormat = toSubmissionFormat;
    self.totalLineDistance = totalLineDistance;

    return self;
}<commit_msg>removed Mission.computeRoute<commit_after>/**
 * Mission module
 * Todo. Needs clean up
 * @param parameters
 * @returns {{className: string}}
 * @constructor
 * @memberof svl
 */
function Mission(parameters) {
    var self = { className: "Mission" },
        properties = {
            auditDistance: null,
            auditDistanceFt: null,
            auditDistanceMi: null,
            regionId: null,
            label: null,
            missionId: null,
            level: null,
            isCompleted: false,
            instruction: null,
            completionMessage: null,
            badgeURL: null,
            distance: null,
            distanceFt: null,
            distanceMi: null,
            coverage: null
        },
        _tasksForTheMission = [],
        labelCountsAtCompletion;

    function _init(parameters) {
        if ("regionId" in parameters) setProperty("regionId", parameters.regionId);
        if ("missionId" in parameters) setProperty("missionId", parameters.missionId);
        if ("level" in parameters) setProperty("level", parameters.level);
        if ("distance" in parameters) setProperty("distance", parameters.distance);
        if ("distanceFt" in parameters) setProperty("distanceFt", parameters.distanceFt);
        if ("distanceMi" in parameters) setProperty("distanceMi", parameters.distanceMi);
        if ("coverage" in parameters) setProperty("coverage", parameters.coverage);
        if ("isCompleted" in parameters) setProperty("isCompleted", parameters.isCompleted);

        if ("label" in parameters) {
            var instruction, completionMessage, badgeURL;
            setProperty("label", parameters.label);
            self.label = parameters.label;  // For debugging. You don't actually need this.
            self.distance = parameters.distance;  // For debugging. You don't actually need this.

            if (parameters.label == "initial-mission") {
                instruction = "Your goal is to audit 1000 feet of the streets " +
                    "in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have completed the first mission. " +
                    "Keep making the city more accessible!";
                badgeURL = svl.rootDirectory + "/img/misc/BadgeInitialMission.png";
            } else if (parameters.label == "distance-mission") {
                var distance = parameters.distance;
                var distanceString = imperialDistance();

                instruction = "Your goal is to audit " + distanceString +
                    " of the streets in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have successfully made " + distanceString +
                    " of this neighborhood accessible.";

                if (distance == 500) {
                    // 2000 ft
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_500.png";
                } else if (distance == 1000) {
                    // 4000 ft
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_1000.png";
                } else {
                    // miles
                    var level = "level" in parameters ? parameters.level : 1;
                    level = (level - 1) % 5 + 1;
                    badgeURL = svl.rootDirectory + "/img/misc/Badge_Level" + level + ".png";
                }
            } else if (parameters.label == "area-coverage-mission") {
                var coverage = parameters.coverage, coverageString = coverage + "%";
                instruction = "Your goal is to audit " + coverageString +
                    " of the streets in this neighborhood and find the accessibility attributes!";
                completionMessage = "Good job! You have successfully made " + coverageString +
                    " of this neighborhood accessible.";
                badgeURL = svl.rootDirectory + "/img/misc/Badge" + coverage + "Percent.png";
            } else if (parameters.label == "onboarding") {

            } else {
                console.error("It shouldn't reach here.");
            }
            setProperty("instruction", instruction);
            setProperty("completionMessage", completionMessage);
            setProperty("badgeURL", badgeURL);
        }
    }

    /**
     * Adjust the target distance if the total distance of available tasks are less than the target audit distance
     * @param availableTaskDistance Available task distance in km
     */
    self.adjustTheTargetDistance = function (availableTaskDistance) {
        if (properties.auditDistance && (properties.auditDistance / 1000 > availableTaskDistance)) {
            properties.auditDistance = availableTaskDistance * 1000;
            properties.auditDistanceFt = availableTaskDistance * 3280.84; // km -> ft
            properties.auditedDistanceMi = availableTaskDistance * 0.621371;  // km -> mi
        }
    };

    /**
     * Because the imperial metric system is messed up.
     * @returns {string}
     */
    function imperialDistance () {
        var distance = getProperty("distance");
        if (distance) {
            if (distance < 1500) {
                if (distance == 250) {
                    return "1000 feet";
                } else if (distance == 500) {
                    return "2000 feet";
                } else if (distance == 1000) {
                    return "4000 feet";
                } else {
                    return distance * 3;
                }
            } else {
                var miles = distance % 1500;
                return miles + "miles";
            }
        } else {
            console.error("Distance is null");
        }
    }

    /**
     * Set the property to complete
     */
    function complete () {
        // Play the animation and audio effect after task completion.

        setProperty("isCompleted", true);

        // Update the neighborhood status
        if ("labelContainer" in svl) {
            var regionId = svl.neighborhoodContainer.getCurrentNeighborhood().getProperty("regionId");
            var count = svl.labelContainer.countLabels(regionId);
            svl.statusFieldNeighborhood.setLabelCount(count);
        }

        // Reset the label counter
        if ('labelCounter' in svl) {
            labelCountsAtCompletion = {
                "CurbRamp": svl.labelCounter.countLabel("CurbRamp"),
                "NoCurbRamp": svl.labelCounter.countLabel("NoCurbRamp"),
                "Obstacle": svl.labelCounter.countLabel("Obstacle"),
                "SurfaceProblem": svl.labelCounter.countLabel("SurfaceProblem"),
                "Other": svl.labelCounter.countLabel("Other")
            };
            svl.labelCounter.reset();
        }
    }

    /**
     * Total line distance of the completed tasks in this mission
     * @param unit
     */
    function completedLineDistance (unit) {
        if (!unit) unit = "kilometers";
        var completedTasks = _tasksForTheMission.filter(function (t) { return t.isCompleted(); });
        var distances = completedTasks.map(function (t) { return t.lineDistance(unit); });
        return distances.sum();
    }

    /**
     * This method returns the label count object
     * @returns {*}
     */
    function getLabelCount () {
        return labelCountsAtCompletion;
    }

    /**
     * Compute and return the mission completion rate
     * @returns {number}
     */
    function getMissionCompletionRate (unit) {
        if (!unit) unit = "kilometers";
        if ("taskContainer" in svl) {
            var neighborhood = svl.neighborhoodContainer.getCurrentNeighborhood();
            var targetDistance = getProperty("distance") / 1000;  // Convert meters to kilometers
            var completedDistance = svl.taskContainer.getCompletedTaskDistance(neighborhood.getProperty("regionId"), unit);
            if (completedDistance > targetDistance) {
                return 1.0;
            }

            var missions = svl.missionContainer.getMissionsByRegionId(neighborhood.getProperty("regionId"));
            var completedMissions = missions.filter(function (m) { return m.isCompleted(); });  // Get the completed missions

            completedMissions = completedMissions.filter(function (m) { return m.getProperty("distance") / 1000 < completedDistance; });
            var lastMissionDistance;
            if (completedMissions.length > 0) {
                lastMissionDistance = completedMissions[completedMissions.length - 1].getProperty("distance") / 1000;
            } else {
                lastMissionDistance = 0;
            }

            return Math.max(0, completedDistance - lastMissionDistance) / (targetDistance - lastMissionDistance);
        } else {
            return 0;
        }
    }

    /** Returns a property */
    function getProperty (key) {
        return key in properties ? properties[key] : null;
    }

    /**
     * Get an array of tasks for this mission
     * @returns {Array}
     */
    function getRoute () {
        return _tasksForTheMission;
    }

    /**
     * Check if the mission is completed or not
     * Todo. Shouldn't it be isComplete rather than isCompleted???
     *
     * @returns {boolean}
     */
    function isCompleted () {
        return getProperty("isCompleted");
    }

    /**
     * Push a completed task into `_tasksForTheMission`
     * @param task
     */
    function pushATaskToTheRoute(task) {
        _tasksForTheMission.push(task);
    }

    /**
     * Sets a property
     */
    function setProperty (key, value) {
        properties[key] = value;
        return this;
    }

    /** Compute the remaining audit distance till complete (in meters) */
    function remainingAuditDistanceTillComplete () {
        var label = getProperty("label");
        if (label) {
            var distance, cumulativeDistanceAudited = 0;  // Todo.
            if (label == "initial-mission") {
                distance = getProperty("level") * 1000;
                return distance - cumulativeDistanceAudited;
            } else if (label == "distance-mission") {
                distance = getProperty("level") * 1000;
                return distance - cumulativeDistanceAudited;
            } else if (label == "area-coverage-mission") {
                return Infinity;
            } else if (label == "neighborhood-coverage-mission") {
                return Infinity;  // Return infinity as this mission does not depend on distance traveled.
            } else {
                return Infinity;  // This should not happen...
            }
        } else {
            return Infinity;  // The label is not specified.
        }
    }

    /**
     * Return a string describing this data
     * @returns {string}
     */
    function toString () {
        return "Mission: " + getProperty("label") + ", Level: "+ getProperty("level") +
            ", Distance: " + getProperty("distance") + ", Coverage " + getProperty("coverage") +
            ", Mission Id: " + getProperty("missionId") + ", Region Id: " + getProperty("regionId") +
            ", Completed: " + getProperty("isCompleted") + "\n";
    }

    /**
     * Return an object that is in a submittable format
     * @returns {{region_id: *, label: *, mission_id: *, level: *, distance: *, coverage: *}}
     */
    function toSubmissionFormat () {
        return {
            region_id: getProperty("regionId"),
            label: getProperty("label"),
            mission_id: getProperty("missionId"),
            level: getProperty("level"),
            distance: getProperty("distance"),
            coverage: getProperty("coverage"),
            deleted: false
        };
    }

    /**
     * Total line distance in this mission.
     * @param unit
     */
    function totalLineDistance (unit) {
        if (unit == "miles") {
            return getProperty("distanceMi");
        } else if (unit == "feet") {
            return getProperty("distanceFt");
        } else {
            return getProperty("distance");
        }
    }
    _init(parameters);

    self.complete = complete;
    self.completedLineDistance = completedLineDistance;
    self.getLabelCount = getLabelCount;
    self.getProperty = getProperty;
    self.getRoute = getRoute;
    self.getMissionCompletionRate = getMissionCompletionRate;
    self.isCompleted = isCompleted;
    self.pushATaskToTheRoute = pushATaskToTheRoute;
    self.remainingAuditDistanceTillComplete = remainingAuditDistanceTillComplete;
    self.setProperty = setProperty;
    self.toString = toString;
    self.toSubmissionFormat = toSubmissionFormat;
    self.totalLineDistance = totalLineDistance;

    return self;
}<|endoftext|>


<commit_before>// @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

/**
 * @type { import("protractor").Config }
 */
exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  chromeOptions: {
     args: [ "--headless", "--disable-gpu", "--window-size=400,1000", "--start-maximized" ]
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 100000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<commit_msg>chore(): bumping timeout<commit_after>  // @ts-check
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts

const { SpecReporter } = require('jasmine-spec-reporter');

/**
 * @type { import("protractor").Config }
 */
exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './src/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome'
  },
  chromeOptions: {
     args: [ "--headless", "--disable-gpu", "--window-size=400,1000", "--start-maximized" ]
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 100000,
    print: function() {}
  },
  onPrepare() {
    require('ts-node').register({
      project: require('path').join(__dirname, './tsconfig.json')
    });
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
<|endoftext|>