<commit_before>var loki    = require('lokijs');
var irc     = require('tmi.js');
var uuid    = require('uuid');
var express = require('express');

var util  = require('../src/util');
var digraph = require('../src/digraph');
var entity  = require('../src/entity');

var extend = util.extend;
var DirectedGraph = digraph.DirectedGraph;
var Entity        = entity.Entity;
var Relationship  = entity.Relationship;

var User = (function(superclass) {
  extend(User, superclass);
  function User(username) {
    return User.__super__.constructor.apply(this, username, {username: username});
  }
  return User;
})(Entity);

var Channel = (function(superclass) {
  extend(Channel, superclass);
  function Channel(username) {
    return User.__super__.constructor.apply(this, username, {username: username});
  }
  return Channel;
})(Entity);

var Event = (function(superclass) {
  extend(Event, superclass);
  function Event(opts) {
    Event.__super__.constructor.apply(this, uuid.v4(), opts);
  }
  return Event;
})(Entity);

var JoinEvent = (function(superclass) {
  extend(JoinEvent, superclass);
  function JoinEvent(channel, username) {
    this.eventType = "irc-join";
    return User.__super__.constructor.apply(this, {channel: channel, username: username});
  }
  return JoinEvent;
})(Event);

var PartEvent = (function(superclass) {
  extend(PartEvent, superclass);
  function PartEvent(channel, username) {
    this.eventType = "irc-part";
    return User.__super__.constructor.apply(this, {channel: channel, username: username});
  }
  return PartEvent;
})(Event);

module.exports = function(emitter, username, secret, config) {

  this.started = new Date();

  var lokiConfig = {
    autosave: true,
    autosaveInterval: 1000
  };

  var channeldb = new loki('twitch-channel.json', lokiConfig);
  var channels  = channeldb.addCollection('channels');

  var socialdb = new loki('twitch-' + username + '-social-graph.json');
  var entities = socialdb.addCollection('entities');
  var relationships = socialdb.addCollection('relationships');
  var socialGraph = new DirectedGraph("twitch-" + username + "-social");

  var userdb = new loki('twitch-' + username + '.json', lokiConfig);
  var users      = userdb.addCollection('users');
  var hosting    = userdb.addCollection('hosting');
  var follows    = userdb.addCollection('follow');
  var events     = userdb.addCollection('event');

  this.client = new irc.client(config);

  this.cacheChannel= function(name) {
    //var channel = channels.findObject({"name": {"$eq": name}});
    if (!channel) { // always cache channels for now
      client.api({
        url: "https://api.twitch.tv/kraken/channels/" + name
      }, function(err, res, body) {
        if (err) return console.error(err);
        var tchannel = JSON.parse(body);
        var channel = new Channel(username);
        channels.insert(channel.toJSON());
        //vres = socialGraph.addVertex(channel.toVertex());
        //if (vres.error) return console.error(vres.error);
        //entities.insert(vres.result);
      });
      cacheChannelHosting(name);
      cacheChannelFollows(name);
    }
  }

  this.cacheChannelHosting = function(name) {

  }

  this.cacheChannelFollows = function(name) {

  }

  this.cacheUser = function(name) {
    var user = users.findObject({"username": {"$eq": name}});
    if (!user) {
      this.client.api({
        url: "https://api.twitch.tv/kraken/users/" + name
      }, function(err, res, body) {
        if (err) return console.error(err);
        var tuser = JSON.parse(body);
        var user = new User(tuser.username);
        users.insert(user.toJSON());
        //vres = socialGraph.addVertex(user.toVertex());
        //if (vres.error) return console.error(vres.error);
        //entities.insert(vres.result);
      });
    }
  }

  function onConnected(address, port) {
    var event = new Event({address: address, port: port});
    even.eventType = "server-connected"; // FIXME: refactor Event constructor
    console.dir(event);
  }

  function onJoin(channel, user) {
    var event = new JoinEvent(channel, user);
    events.insert(event);
    var user = users.findObject({"username": {"$eq": username}});
    if (!user) {
      cacheUser(user);
    }
  }

  function onPart(channel, username) {
    var event = new PartEvent(channel, user);
    events.insert(event);
  };

  function onHosted(channel, user, viewers) {
    var ts = new Date();
    console.log("%s [%s] <%s> host %s", ts.toUTCString(), channel, user, viewers);
    var event = {
      created: ts.toUTCString(),
      type: "hosted",
      channel: channel,
      username: user,
      viewers: viewers
    };
    events.insert(event);
    if (!user) {
      cacheUser(user);
    }
  }

  function onChat(channel, user, message, self) {
    var ts = new Date();
    console.log("%s [%s] <%s> %s", ts.toUTCString(), channel, user.username, message);
    events.insert({
      created: ts.toUTCString(),
      type: "chat",
      channel: channel,
      username: user.username,
      message: message
    });
    cacheUser(user.username);
    var commandPattern = new RegExp("^!\\w+");
    if (commandPattern.test(message)) {
      var command = commandPattern.exec(message);
      emitter.emit("command-dispatch", command, user.username, message);
    }
  }

  function onAction(channel, user, message, self) {
    var ts = new Date();
    console.log("%s [%s] <*%s> %s", ts.toUTCString(), channel, user.username, message);
    events.insert({
      created: ts.toUTCString(),
      type: "action",
      channel: channel,
      user: user.username,
      message: message
    });
    cacheUser(user.username);
  };

  this.say = function(channel, message) {
    this.client.say(channel, message);
  }

  this.client.on("connected", onConnected);
  this.client.on("join", onJoin);
  this.client.on("part", onPart);
  this.client.on("hosted", onHosted);
  this.client.on("chat", onChat);
  this.client.on("action", onAction);

  emitter.on('cache-user', this.cacheUser);
  emitter.on('cache-channel', this.cacheChannel);
  emitter.on('cache-channel-hosting', this.cacheChannelHosting);
  emitter.on('cache-channel-follows', this.cacheChannelFollows);

  this.router = express.Router();
  this.router.get('/channel/:name', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(channels.find({"name": req.params.name}));
  });
  this.router.get('/channel/:name/hosting', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(hosting.find());
  });
  this.router.get('/channel/:name/follows', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(follows.find());
  });

  // register new router for every new user identified so they get their own base loki file registered once

  this.connect = function() {
    this.client.connect();
  };

  this.disconnect = function() {
    this.client.disconnect();
  };

  return this;
};
<commit_msg>remove naked connect event<commit_after>var loki    = require('lokijs');
var irc     = require('tmi.js');
var uuid    = require('uuid');
var express = require('express');

var util  = require('../src/util');
var digraph = require('../src/digraph');
var entity  = require('../src/entity');

var extend = util.extend;
var DirectedGraph = digraph.DirectedGraph;
var Entity        = entity.Entity;
var Relationship  = entity.Relationship;

var User = (function(superclass) {
  extend(User, superclass);
  function User(username) {
    return User.__super__.constructor.apply(this, username, {username: username});
  }
  return User;
})(Entity);

var Channel = (function(superclass) {
  extend(Channel, superclass);
  function Channel(username) {
    return User.__super__.constructor.apply(this, username, {username: username});
  }
  return Channel;
})(Entity);

var Event = (function(superclass) {
  extend(Event, superclass);
  function Event(opts) {
    Event.__super__.constructor.apply(this, uuid.v4(), opts);
  }
  return Event;
})(Entity);

var JoinEvent = (function(superclass) {
  extend(JoinEvent, superclass);
  function JoinEvent(channel, username) {
    this.eventType = "irc-join";
    return User.__super__.constructor.apply(this, {channel: channel, username: username});
  }
  return JoinEvent;
})(Event);

var PartEvent = (function(superclass) {
  extend(PartEvent, superclass);
  function PartEvent(channel, username) {
    this.eventType = "irc-part";
    return User.__super__.constructor.apply(this, {channel: channel, username: username});
  }
  return PartEvent;
})(Event);

module.exports = function(emitter, username, secret, config) {

  this.started = new Date();

  var lokiConfig = {
    autosave: true,
    autosaveInterval: 1000
  };

  var channeldb = new loki('twitch-channel.json', lokiConfig);
  var channels  = channeldb.addCollection('channels');

  var socialdb = new loki('twitch-' + username + '-social-graph.json');
  var entities = socialdb.addCollection('entities');
  var relationships = socialdb.addCollection('relationships');
  var socialGraph = new DirectedGraph("twitch-" + username + "-social");

  var userdb = new loki('twitch-' + username + '.json', lokiConfig);
  var users      = userdb.addCollection('users');
  var hosting    = userdb.addCollection('hosting');
  var follows    = userdb.addCollection('follow');
  var events     = userdb.addCollection('event');

  this.client = new irc.client(config);

  this.cacheChannel= function(name) {
    //var channel = channels.findObject({"name": {"$eq": name}});
    if (!channel) { // always cache channels for now
      client.api({
        url: "https://api.twitch.tv/kraken/channels/" + name
      }, function(err, res, body) {
        if (err) return console.error(err);
        var tchannel = JSON.parse(body);
        var channel = new Channel(username);
        channels.insert(channel.toJSON());
        //vres = socialGraph.addVertex(channel.toVertex());
        //if (vres.error) return console.error(vres.error);
        //entities.insert(vres.result);
      });
      cacheChannelHosting(name);
      cacheChannelFollows(name);
    }
  }

  this.cacheChannelHosting = function(name) {

  }

  this.cacheChannelFollows = function(name) {

  }

  this.cacheUser = function(name) {
    var user = users.findObject({"username": {"$eq": name}});
    if (!user) {
      this.client.api({
        url: "https://api.twitch.tv/kraken/users/" + name
      }, function(err, res, body) {
        if (err) return console.error(err);
        var tuser = JSON.parse(body);
        var user = new User(tuser.username);
        users.insert(user.toJSON());
        //vres = socialGraph.addVertex(user.toVertex());
        //if (vres.error) return console.error(vres.error);
        //entities.insert(vres.result);
      });
    }
  }

  function onConnected(address, port) {
    //var event = new Event({address: address, port: port});
    //even.eventType = "server-connected"; // FIXME: refactor Event constructor
    //console.dir(event);
  }

  function onJoin(channel, user) {
    var event = new JoinEvent(channel, user);
    events.insert(event);
    var user = users.findObject({"username": {"$eq": username}});
    if (!user) {
      cacheUser(user);
    }
  }

  function onPart(channel, username) {
    var event = new PartEvent(channel, user);
    events.insert(event);
  };

  function onHosted(channel, user, viewers) {
    var ts = new Date();
    console.log("%s [%s] <%s> host %s", ts.toUTCString(), channel, user, viewers);
    var event = {
      created: ts.toUTCString(),
      type: "hosted",
      channel: channel,
      username: user,
      viewers: viewers
    };
    events.insert(event);
    if (!user) {
      cacheUser(user);
    }
  }

  function onChat(channel, user, message, self) {
    var ts = new Date();
    console.log("%s [%s] <%s> %s", ts.toUTCString(), channel, user.username, message);
    events.insert({
      created: ts.toUTCString(),
      type: "chat",
      channel: channel,
      username: user.username,
      message: message
    });
    cacheUser(user.username);
    var commandPattern = new RegExp("^!\\w+");
    if (commandPattern.test(message)) {
      var command = commandPattern.exec(message);
      emitter.emit("command-dispatch", command, user.username, message);
    }
  }

  function onAction(channel, user, message, self) {
    var ts = new Date();
    console.log("%s [%s] <*%s> %s", ts.toUTCString(), channel, user.username, message);
    events.insert({
      created: ts.toUTCString(),
      type: "action",
      channel: channel,
      user: user.username,
      message: message
    });
    cacheUser(user.username);
  };

  this.say = function(channel, message) {
    this.client.say(channel, message);
  }

  this.client.on("connected", onConnected);
  this.client.on("join", onJoin);
  this.client.on("part", onPart);
  this.client.on("hosted", onHosted);
  this.client.on("chat", onChat);
  this.client.on("action", onAction);

  emitter.on('cache-user', this.cacheUser);
  emitter.on('cache-channel', this.cacheChannel);
  emitter.on('cache-channel-hosting', this.cacheChannelHosting);
  emitter.on('cache-channel-follows', this.cacheChannelFollows);

  this.router = express.Router();
  this.router.get('/channel/:name', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(channels.find({"name": req.params.name}));
  });
  this.router.get('/channel/:name/hosting', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(hosting.find());
  });
  this.router.get('/channel/:name/follows', function(req, res) {
    cacheChannel(req.params.name);
    return res.json(follows.find());
  });

  // register new router for every new user identified so they get their own base loki file registered once

  this.connect = function() {
    this.client.connect();
  };

  this.disconnect = function() {
    this.client.disconnect();
  };

  return this;
};
<|endoftext|>


<commit_before>importScripts('../js/turfjs/turf.min.js');

function genStreetsGrid(pointsWithin, extent) {
    // This module generates streets. given a grid of points.
    var rows = [];
    var columns = [];
    var buildingPoints = [];
    var roadPoints = [];
    var buildingPointsVert = [];
    var roadPointsVert = [];
    for (var k = 0, ptslen = pointsWithin.features.length; k < ptslen; k++) {
        var curPt = pointsWithin.features[k];
        var curLng = curPt.geometry.coordinates[0];
        var curLat = curPt.geometry.coordinates[1];
        if (rows[curLng]) {} else {
            rows[curLng] = [];
        }
        if (columns[curLat]) {} else {
            columns[curLat] = [];
        }
        rows[curLng].push(curPt);
        columns[curLat].push(curPt);
    }

    var allCols = [];
    var allRows = [];
    for (key in columns) {
        allCols.push({
            'key': key,
            'points': columns[key]
        });
    }
    for (key in rows) {
        allRows.push({
            'key': key,
            'points': rows[key]
        });
    }

    var rCounter = 0;
    var cCounter = 0;
    var sortedCols = allCols.sort(function(a, b) {
        return parseFloat(a.key) - parseFloat(b.key);
    });
    var sortedRows = allRows.sort(function(a, b) {
        return parseFloat(a.key) - parseFloat(b.key);
    });
    for (var x2 = 0, collen = sortedCols.length; x2 < collen; x2++) {
        var feattype = (rCounter % 3 === 0) ? "road" : "building";
        // var pts = sortedCols[x2].points;
        (feattype === 'road') ? roadPoints.push(sortedCols[x2]): buildingPoints.push(sortedCols[x2]);
        rCounter += 1;
    }
    for (var x3 = 0, rowlen = sortedRows.length; x3 < rowlen; x3++) {
        var feattype = (cCounter % 5 === 0) ? "road" : "building";
        // var pts = sortedCols[x2].points;
        (feattype === 'road') ? roadPointsVert.push(sortedRows[x3]): buildingPointsVert.push(sortedRows[x3]);
        cCounter += 1;
    }
    // var allLines = [];
    var streets = [];
    var distance = 0;

    for (var k1 = 0, numRoads = roadPoints.length; k1 < numRoads; k1++) {
        var curRoad = roadPoints[k1];
        var tmpPts = [];
        for (var p1 = 0, ptsLen = curRoad.points.length; p1 < ptsLen; p1++) {
            tmpPts.push(curRoad.points[p1].geometry.coordinates);
        }
        var linestring = turf.linestring(tmpPts);
        // allLines.push(linestring);
        var d = turf.lineDistance(linestring, 'kilometers');
        distance = (distance > Math.round(d)) ? distance : Math.round(d);
        var street = turf.buffer(linestring, 0.0075, 'kilometers');
        street.features[0].properties = {
            "color": "#202020",
            "roofColor": "#202020",
            "height": 2
        };
        streets.push.apply(streets, street.features);
    }
    if (distance >= 0.7) { // there is a road that is greater than 1KM, so we need vertical streets.
        for (var k2 = 0, numRoads = roadPointsVert.length; k2 < numRoads; k2++) {
            var curRoad = roadPointsVert[k2];
            var tmpPts = [];
            for (var p2 = 0, ptsLen = curRoad.points.length; p2 < ptsLen; p2++) {
                tmpPts.push(curRoad.points[p2].geometry.coordinates);
            }
            var linestring = turf.linestring(tmpPts);
            var street = turf.buffer(linestring, 0.005, 'kilometers');
            street.features[0].properties = {
                "color": "#202020",
                "roofColor": "#202020",
                "height": 2
            };
            streets.push.apply(streets, street.features);
        }
    }
    var s = {
        "type": "FeatureCollection",
        "features": streets
    };
    return s;
}

function genStreetsHeatMapped(pointsWithin, extent) {
    function keyFor(item) {
        return item.geometry.coordinates[0] + ':' + item.geometry.coordinates[1];
    }
    // var area = Math.round(turf.area(pointsWithin));
    // var points = {0: 360.0,1: 180.0,2: 90.0,3: 45.0,4: 22.5,5: 11.25,6: 5.625,7: 2.813,8: 1.406,9: 0.703,10: 0.352,11: 0.176,12: 0.088,13: 0.044,14: 0.022,15: 0.011,16: 0.005,17: 0.003,18: 0.001,19: 0.0005};
    var heatmap = turf.random('points', 5, {
        bbox: extent
    });
    // console.log(JSON.stringify(extent));
    var startPoint = turf.point([extent[0], extent[1]]);
    // assign a random z property.
    for (var i = 0; i < heatmap.features.length; i++) {
        heatmap.features[i].properties.z = ~~(Math.random() * 9);
    }
    var tin = turf.tin(heatmap, 'z');
    for (var i = 0; i < tin.features.length; i++) {
        var properties = tin.features[i].properties;
        properties.fill = '#' + properties.a +
            properties.b + properties.c;
    }
    var tinPtsFC = {
        "type": "FeatureCollection",
        "features": []
    };
    for (var k = 0; k < tin.features.length; k++) {
        var prop = tin.features[k].properties;
        var tincoords = tin.features[k].geometry.coordinates[0];
        for (var m = 0; m < tincoords.length; m++) {
            var tco = tincoords[m];
            var ptFeat = {
                "type": "Feature",
                "properties": prop,
                "geometry": {
                    "type": "Point",
                    "coordinates": tco
                }
            };
            tinPtsFC.features.push(ptFeat);
        }
    }
    var roadStart = turf.nearest(startPoint, tinPtsFC);
    var ptindexed = {};
    var ptcounts = {};
    tinPtsFC.features.forEach(function(item) {
        var key = keyFor(item);
        item.properties.key = key;
        var exists = ptindexed[key];
        ptcounts[keyFor(item)] = (exists) ? ptcounts[keyFor(item)] + 1 : 0;
        ptindexed[key] = item;
    });
    var result = Object.keys(ptindexed).map(function(k) {
        return ptindexed[k];
    });
    tinPtsFC.features = result;
    // console.log(JSON.stringify(tinPtsFC));
    var arr = Object.keys(ptcounts).map(function(key) {
        return ptcounts[key];
    });
    var minfreq = Math.min.apply(null, arr);
    var maxfreq = Math.max.apply(null, arr);
    var diff = maxfreq - minfreq;
    var threshold = Math.round((diff * 90) / 100);
    var ptsofInt = [];
    var ct = 0;
    for (key in ptcounts) {
        ct = ct + 1;
        var value = ptcounts[key];
        if (value >= threshold) {
            ptsofInt.push(key);
        }
    }
    // extract all points from tin
    var tinLinesFC = {
        "type": "FeatureCollection",
        "features": []
    };
    var fc = [];
    for (var k = 0; k < tin.features.length; k++) {
        var curTriangle = tin.features[k];
        var lineFeatures = generateLineFeatures(curTriangle);
        tinLinesFC.features.push.apply(tinLinesFC.features, lineFeatures);
    }

    // All the line segements from the tin are extracted.
    // check count
    function isInArray(value, array) {
        return array.indexOf(value) > -1;
    }

    var indexed = [];
    var filteredFeats = [];
    tinLinesFC.features.forEach(function(item) {
        // a duplicate key will replace the existing entry
        var key = item.properties.id;
        if (isInArray(key, indexed)) {

        } else {
            indexed.push(key);
            filteredFeats.push(item);
        }
    });
    var mainPts = [];
    for (var p = 0; p < ptsofInt.length; p++) {
        var ptKey = ptsofInt[p];
        for (var o = 0; o < tinPtsFC.features.length; o++) {
            var curF = tinPtsFC.features[o];
            if (curF.properties.key === ptKey) {
                mainPts.push(curF);
            }
        }
    }
    var filteredLineFC = {
        "type": "FeatureCollection",
        "features": filteredFeats
    };

    // console.log(JSON.stringify(filteredLineFC));
    // console.log(JSON.stringify(mainPts));
    // var curved = turf.bezier(filteredLineFC.features[0]);
    // var streets = turf.buffer(curved, 0.010, 'kilometers');
    return filteredLineFC;

}

function getRandomHeight(reqtype) {
    var smbHeights = [2, 3, 5, 6, 7, 10];
    var labHeights = [0, 5, 7, 10, 12, 15];
    var restHeights = [0, 2, 5];

    return reqtype === 'SMB' ? smbHeights[Math.floor(Math.random() * smbHeights.length)] :
        reqtype === 'LAB' ? labHeights[Math.floor(Math.random() * labHeights.length)] :
        reqtype === 'POR' ? restHeights[Math.floor(Math.random() * restHeights.length)] :
        reqtype > 'POL' ? 0 :
        reqtype > 'PAV' ? 0 :
        0;
}

function generateFinal3DGeoms(constraintedModelDesigns, genstreets) {
    var genstreets = (genstreets === 'false') ? false : true;
    var finalGJFeats = [];
    var plFeats = [];
    // get the center of the design so that the map once returned can be recentered.
    var centerPt = turf.center(constraintedModelDesigns);
    var lat = centerPt.geometry.coordinates[1];
    var lng = centerPt.geometry.coordinates[0];
    // iterate over the features.
    var curFeats = constraintedModelDesigns.features;
    var flen = curFeats.length;
    for (var h = 0; h < flen; h++) {
        // for every feature , create a point grid.
        var curFeat = curFeats[h];
        // if it is a line then simply buffer it and paint it black with a small height
        if (curFeat.geometry.type === "LineString") {
            f = turf.buffer(curFeat, 0.005, 'kilometers');
            var linefeats = f.features;
            var linefeatlen = linefeats.length;
            for (var x1 = 0; x1 < linefeatlen; x1++) {
                curlineFeat = linefeats[x1];
                curlineFeat.properties = {
                    "color": "#202020",
                    "roofColor": "#202020",
                    "height": 2
                };

                finalGJFeats.push.apply(finalGJFeats, [curlineFeat]);
            }

        } else if ("height" in curFeat.properties && curFeat.properties.height === 'ag') {

            var featProps = curFeat.properties;
            var color = featProps.color;
            var roofColor = color;
            var reqTag = featProps.reqtag;
            // featProps.roofShape = 'pyramid';
            // featProps.roofMaterial = 'roof_tiles';
            // featProps.roofHeight = 10;
            // get the extent of the feature
            var featExtent = turf.extent(curFeat);
            // 50 meter cell width
            var cellWidth = 0.05;
            var unit = 'kilometers';
            // make this feature a feature collection since point grid only takes in a feature collection
            var diagJSON = {
                "type": "FeatureCollection",
                "features": [curFeat]
            };
            // make the grid of 50 meter points
            var grid = turf.pointGrid(featExtent, cellWidth, unit);
            // filter the grid so that only points within the feature are left.
            var ptsWithin = turf.within(grid, diagJSON);
            // 15 meter subtract
            var bufferWidth = cellWidth - 0.002; //48 meter buffer
            for (var k = 0, ptslen = ptsWithin.features.length; k < ptslen; k++) {
                var curPt = ptsWithin.features[k];
                var buffered = turf.buffer(curPt, bufferWidth, unit); // buffer 35 meters
                var indWidth = bufferWidth - 0.02; // subtract 1 meter = 34 meters
                var bds = turf.extent(buffered); // get the extent of the buffered features
                var subGrid = turf.pointGrid(bds, indWidth, unit); // generate a grid within 34 meters
                for (var h1 = 0, glen = subGrid.features.length; h1 < glen; h1++) {
                    var smallWidth = indWidth - 0.017; //9 meters width
                    var curSubGrid = subGrid.features[h1];
                    var bfrd = turf.buffer(curSubGrid, smallWidth, unit); // 9 m buffer
                    var bfrdext = turf.extent(bfrd);
                    var bfrdextPlgn = turf.bboxPolygon(bfrdext); // generate the polygon
                    var height = getRandomHeight(reqTag);
                    // console.log(JSON.stringify(featProps));
                    var p = {
                        'height': height,
                        'color': color,
                        'roofColor': color
                    };
                    bfrdextPlgn.properties = p;
                    finalGJFeats.push.apply(finalGJFeats, [bfrdextPlgn]);
                }
            }
            if (genstreets) {
                var finalFeatures = [];
                var streetFeatureCollection = genStreetsGrid(ptsWithin, featExtent);
                // console.log(JSON.stringify(streetFeatureCollection));
                for (var l = 0; l < finalGJFeats.length; l++) {
                    var curF1 = finalGJFeats[l];
                    var intersects = false;
                    for (var p = 0, stLen = streetFeatureCollection.features.length; p < stLen; p++) {
                        var curStF = streetFeatureCollection.features[p];
                        var intersect = turf.intersect(curF1, curStF);
                        // chop road
                        // var intersect2 = turf.intersect(curFeat, curStF);
                        if (intersect) {
                            intersects = true;
                        }
                    }
                    if (intersects) {} else {
                        // console.log(curF1.properties.height);
                        finalFeatures.push(curF1);
                    }
                }

                finalFeatures.push.apply(finalFeatures, streetFeatureCollection.features);
                finalGJFeats = finalFeatures;
            }

        } else {
            var prop = {
                'color': curFeat.properties.color,
                'roofColor': curFeat.properties.color,
                'areatype': curFeat.properties.areatype,
                'height': 2
            }
            curFeat.properties = prop;
            finalGJFeats.push.apply(finalGJFeats, [curFeat]);
        }
    }

    var fpolygons = {
        "type": "FeatureCollection",
        "features": finalGJFeats
    };
    self.postMessage({
        'polygons': JSON.stringify(fpolygons),
        'center': JSON.stringify([lat, lng])
    });
}

function generate3DGeoms(allFeaturesList, genstreets) {;
    var allFeaturesList = JSON.parse(allFeaturesList);
    var threeDOutput = generateFinal3DGeoms(allFeaturesList, genstreets);

}

self.onmessage = function(e) {
    generate3DGeoms(e.data.allFeaturesList, e.data.genstreets);
}<commit_msg>Updated to fix widths<commit_after>importScripts('../js/turfjs/turf.min.js');

function genStreetsGrid(pointsWithin, extent) {
    // This module generates streets. given a grid of points.
    var rows = [];
    var columns = [];
    var buildingPoints = [];
    var roadPoints = [];
    var buildingPointsVert = [];
    var roadPointsVert = [];
    for (var k = 0, ptslen = pointsWithin.features.length; k < ptslen; k++) {
        var curPt = pointsWithin.features[k];
        var curLng = curPt.geometry.coordinates[0];
        var curLat = curPt.geometry.coordinates[1];
        if (rows[curLng]) {} else {
            rows[curLng] = [];
        }
        if (columns[curLat]) {} else {
            columns[curLat] = [];
        }
        rows[curLng].push(curPt);
        columns[curLat].push(curPt);
    }

    var allCols = [];
    var allRows = [];
    for (key in columns) {
        allCols.push({
            'key': key,
            'points': columns[key]
        });
    }
    for (key in rows) {
        allRows.push({
            'key': key,
            'points': rows[key]
        });
    }

    var rCounter = 0;
    var cCounter = 0;
    var sortedCols = allCols.sort(function(a, b) {
        return parseFloat(a.key) - parseFloat(b.key);
    });
    var sortedRows = allRows.sort(function(a, b) {
        return parseFloat(a.key) - parseFloat(b.key);
    });
    for (var x2 = 0, collen = sortedCols.length; x2 < collen; x2++) {
        var feattype = (rCounter % 3 === 0) ? "road" : "building";
        // var pts = sortedCols[x2].points;
        (feattype === 'road') ? roadPoints.push(sortedCols[x2]): buildingPoints.push(sortedCols[x2]);
        rCounter += 1;
    }
    for (var x3 = 0, rowlen = sortedRows.length; x3 < rowlen; x3++) {
        var feattype = (cCounter % 5 === 0) ? "road" : "building";
        // var pts = sortedCols[x2].points;
        (feattype === 'road') ? roadPointsVert.push(sortedRows[x3]): buildingPointsVert.push(sortedRows[x3]);
        cCounter += 1;
    }
    // var allLines = [];
    var streets = [];
    var distance = 0;

    for (var k1 = 0, numRoads = roadPoints.length; k1 < numRoads; k1++) {
        var curRoad = roadPoints[k1];
        var tmpPts = [];
        for (var p1 = 0, ptsLen = curRoad.points.length; p1 < ptsLen; p1++) {
            tmpPts.push(curRoad.points[p1].geometry.coordinates);
        }
        var linestring = turf.linestring(tmpPts);
        // allLines.push(linestring);
        var d = turf.lineDistance(linestring, 'kilometers');
        distance = (distance > Math.round(d)) ? distance : Math.round(d);
        var street = turf.buffer(linestring, 0.0075, 'kilometers');
        street.features[0].properties = {
            "color": "#202020",
            "roofColor": "#202020",
            "height": 2
        };
        streets.push.apply(streets, street.features);
    }
    if (distance >= 0.7) { // there is a road that is greater than 1KM, so we need vertical streets.
        for (var k2 = 0, numRoads = roadPointsVert.length; k2 < numRoads; k2++) {
            var curRoad = roadPointsVert[k2];
            var tmpPts = [];
            for (var p2 = 0, ptsLen = curRoad.points.length; p2 < ptsLen; p2++) {
                tmpPts.push(curRoad.points[p2].geometry.coordinates);
            }
            var linestring = turf.linestring(tmpPts);
            var street = turf.buffer(linestring, 0.005, 'kilometers');
            street.features[0].properties = {
                "color": "#202020",
                "roofColor": "#202020",
                "height": 2
            };
            streets.push.apply(streets, street.features);
        }
    }
    var s = {
        "type": "FeatureCollection",
        "features": streets
    };
    return s;
}

function genStreetsHeatMapped(pointsWithin, extent) {
    function keyFor(item) {
        return item.geometry.coordinates[0] + ':' + item.geometry.coordinates[1];
    }
    // var area = Math.round(turf.area(pointsWithin));
    // var points = {0: 360.0,1: 180.0,2: 90.0,3: 45.0,4: 22.5,5: 11.25,6: 5.625,7: 2.813,8: 1.406,9: 0.703,10: 0.352,11: 0.176,12: 0.088,13: 0.044,14: 0.022,15: 0.011,16: 0.005,17: 0.003,18: 0.001,19: 0.0005};
    var heatmap = turf.random('points', 5, {
        bbox: extent
    });
    // console.log(JSON.stringify(extent));
    var startPoint = turf.point([extent[0], extent[1]]);
    // assign a random z property.
    for (var i = 0; i < heatmap.features.length; i++) {
        heatmap.features[i].properties.z = ~~(Math.random() * 9);
    }
    var tin = turf.tin(heatmap, 'z');
    for (var i = 0; i < tin.features.length; i++) {
        var properties = tin.features[i].properties;
        properties.fill = '#' + properties.a +
            properties.b + properties.c;
    }
    var tinPtsFC = {
        "type": "FeatureCollection",
        "features": []
    };
    for (var k = 0; k < tin.features.length; k++) {
        var prop = tin.features[k].properties;
        var tincoords = tin.features[k].geometry.coordinates[0];
        for (var m = 0; m < tincoords.length; m++) {
            var tco = tincoords[m];
            var ptFeat = {
                "type": "Feature",
                "properties": prop,
                "geometry": {
                    "type": "Point",
                    "coordinates": tco
                }
            };
            tinPtsFC.features.push(ptFeat);
        }
    }
    var roadStart = turf.nearest(startPoint, tinPtsFC);
    var ptindexed = {};
    var ptcounts = {};
    tinPtsFC.features.forEach(function(item) {
        var key = keyFor(item);
        item.properties.key = key;
        var exists = ptindexed[key];
        ptcounts[keyFor(item)] = (exists) ? ptcounts[keyFor(item)] + 1 : 0;
        ptindexed[key] = item;
    });
    var result = Object.keys(ptindexed).map(function(k) {
        return ptindexed[k];
    });
    tinPtsFC.features = result;
    // console.log(JSON.stringify(tinPtsFC));
    var arr = Object.keys(ptcounts).map(function(key) {
        return ptcounts[key];
    });
    var minfreq = Math.min.apply(null, arr);
    var maxfreq = Math.max.apply(null, arr);
    var diff = maxfreq - minfreq;
    var threshold = Math.round((diff * 90) / 100);
    var ptsofInt = [];
    var ct = 0;
    for (key in ptcounts) {
        ct = ct + 1;
        var value = ptcounts[key];
        if (value >= threshold) {
            ptsofInt.push(key);
        }
    }
    // extract all points from tin
    var tinLinesFC = {
        "type": "FeatureCollection",
        "features": []
    };
    var fc = [];
    for (var k = 0; k < tin.features.length; k++) {
        var curTriangle = tin.features[k];
        var lineFeatures = generateLineFeatures(curTriangle);
        tinLinesFC.features.push.apply(tinLinesFC.features, lineFeatures);
    }

    // All the line segements from the tin are extracted.
    // check count
    function isInArray(value, array) {
        return array.indexOf(value) > -1;
    }

    var indexed = [];
    var filteredFeats = [];
    tinLinesFC.features.forEach(function(item) {
        // a duplicate key will replace the existing entry
        var key = item.properties.id;
        if (isInArray(key, indexed)) {

        } else {
            indexed.push(key);
            filteredFeats.push(item);
        }
    });
    var mainPts = [];
    for (var p = 0; p < ptsofInt.length; p++) {
        var ptKey = ptsofInt[p];
        for (var o = 0; o < tinPtsFC.features.length; o++) {
            var curF = tinPtsFC.features[o];
            if (curF.properties.key === ptKey) {
                mainPts.push(curF);
            }
        }
    }
    var filteredLineFC = {
        "type": "FeatureCollection",
        "features": filteredFeats
    };

    // console.log(JSON.stringify(filteredLineFC));
    // console.log(JSON.stringify(mainPts));
    // var curved = turf.bezier(filteredLineFC.features[0]);
    // var streets = turf.buffer(curved, 0.010, 'kilometers');
    return filteredLineFC;

}

function getRandomHeight(reqtype) {
    var smbHeights = [2, 3, 5, 6, 7, 10];
    var labHeights = [0, 5, 7, 10, 12, 15];
    var restHeights = [0, 2, 5];

    return reqtype === 'SMB' ? smbHeights[Math.floor(Math.random() * smbHeights.length)] :
        reqtype === 'LAB' ? labHeights[Math.floor(Math.random() * labHeights.length)] :
        reqtype === 'POR' ? restHeights[Math.floor(Math.random() * restHeights.length)] :
        reqtype > 'POL' ? 0 :
        reqtype > 'PAV' ? 0 :
        0;
}

function generateFinal3DGeoms(constraintedModelDesigns, genstreets) {
    var genstreets = (genstreets === 'false') ? false : true;
    var finalGJFeats = [];
    var plFeats = [];
    // get the center of the design so that the map once returned can be recentered.
    var centerPt = turf.center(constraintedModelDesigns);
    var lat = centerPt.geometry.coordinates[1];
    var lng = centerPt.geometry.coordinates[0];
    // iterate over the features.
    var curFeats = constraintedModelDesigns.features;
    var flen = curFeats.length;
    for (var h = 0; h < flen; h++) {
        // for every feature , create a point grid.
        var curFeat = curFeats[h];
        // if it is a line then simply buffer it and paint it black with a small height
        if (curFeat.geometry.type === "LineString") {
            f = turf.buffer(curFeat, 0.005, 'kilometers');
            var linefeats = f.features;
            var linefeatlen = linefeats.length;
            for (var x1 = 0; x1 < linefeatlen; x1++) {
                curlineFeat = linefeats[x1];
                curlineFeat.properties = {
                    "color": "#202020",
                    "roofColor": "#202020",
                    "height": 2
                };

                finalGJFeats.push.apply(finalGJFeats, [curlineFeat]);
            }

        } else if ("height" in curFeat.properties && curFeat.properties.height === 'ag') {

            var featProps = curFeat.properties;
            var color = featProps.color;
            var roofColor = color;
            var reqTag = featProps.reqtag;
            // featProps.roofShape = 'pyramid';
            // featProps.roofMaterial = 'roof_tiles';
            // featProps.roofHeight = 10;
            // get the extent of the feature
            var featExtent = turf.extent(curFeat);
            // 50 meter cell width
            var cellWidth = 0.05;
            var unit = 'kilometers';
            // make this feature a feature collection since point grid only takes in a feature collection
            var diagJSON = {
                "type": "FeatureCollection",
                "features": [curFeat]
            };
            // make the grid of 50 meter points
            var grid = turf.pointGrid(featExtent, cellWidth, unit);
            // filter the grid so that only points within the feature are left.
            var ptsWithin = turf.within(grid, diagJSON);
            // 15 meter subtract
            var bufferWidth = cellWidth - 0.005; //45 meter buffer
            for (var k = 0, ptslen = ptsWithin.features.length; k < ptslen; k++) {
                var curPt = ptsWithin.features[k];
                var buffered = turf.buffer(curPt, bufferWidth, unit); // buffer 48 meters
                var indWidth = bufferWidth - 0.02; // subtract 20 meter = 25 meters
                var bds = turf.extent(buffered); // get the extent of the buffered features
                var subGrid = turf.pointGrid(bds, indWidth, unit); // generate a grid within 34 meters
                for (var h1 = 0, glen = subGrid.features.length; h1 < glen; h1++) {
                    var smallWidth = indWidth - 0.015; //(25-15 = 8 meters width
                    var curSubGrid = subGrid.features[h1];
                    var bfrd = turf.buffer(curSubGrid, smallWidth, unit); // 9 m buffer
                    var bfrdext = turf.extent(bfrd);
                    var bfrdextPlgn = turf.bboxPolygon(bfrdext); // generate the polygon
                    var height = getRandomHeight(reqTag);
                    // console.log(JSON.stringify(featProps));
                    var p = {
                        'height': height,
                        'color': color,
                        'roofColor': color
                    };
                    bfrdextPlgn.properties = p;
                    finalGJFeats.push.apply(finalGJFeats, [bfrdextPlgn]);
                }
            }
            if (genstreets) {
                var finalFeatures = [];
                var streetFeatureCollection = genStreetsGrid(ptsWithin, featExtent);
                // console.log(JSON.stringify(streetFeatureCollection));
                for (var l = 0; l < finalGJFeats.length; l++) {
                    var curF1 = finalGJFeats[l];
                    var intersects = false;
                    for (var p = 0, stLen = streetFeatureCollection.features.length; p < stLen; p++) {
                        var curStF = streetFeatureCollection.features[p];
                        var intersect = turf.intersect(curF1, curStF);
                        // chop road
                        // var intersect2 = turf.intersect(curFeat, curStF);
                        if (intersect) {
                            intersects = true;
                        }
                    }
                    if (intersects) {} else {
                        // console.log(curF1.properties.height);
                        finalFeatures.push(curF1);
                    }
                }

                finalFeatures.push.apply(finalFeatures, streetFeatureCollection.features);
                finalGJFeats = finalFeatures;
            }

        } else {
            var prop = {
                'color': curFeat.properties.color,
                'roofColor': curFeat.properties.color,
                'areatype': curFeat.properties.areatype,
                'height': 2
            }
            curFeat.properties = prop;
            finalGJFeats.push.apply(finalGJFeats, [curFeat]);
        }
    }

    var fpolygons = {
        "type": "FeatureCollection",
        "features": finalGJFeats
    };
    self.postMessage({
        'polygons': JSON.stringify(fpolygons),
        'center': JSON.stringify([lat, lng])
    });
}

function generate3DGeoms(allFeaturesList, genstreets) {;
    var allFeaturesList = JSON.parse(allFeaturesList);
    var threeDOutput = generateFinal3DGeoms(allFeaturesList, genstreets);

}

self.onmessage = function(e) {
    generate3DGeoms(e.data.allFeaturesList, e.data.genstreets);
}<|endoftext|>


<commit_before>function min_unv_exp(num) {
    /* Returns a number representing the minimal universal exponent
     * of a positive integer num, which is assumed to be valid */
    var e = 0;
    //TODO

    return e;
}

function prime_factorization(n) {
    /* Returns an array of prime factors (in least sorted order)
     * where each factor is an object of the form
     * {'p': 7, 'e': 4}
     * where p is the prime base and e is the exponent to which that
     * factor is raised in the factorization of n
     */
    var factors = [], e;
    for(var p = 2; p <= n; p++) {
        e = 0;
        while(n % e == 0) {
            n = n / p;
            e++;
        }
        if(e > 0) {
            factors.push({'p':p,'e':e});
        }
    }
    return factors;
}
<commit_msg>implemented exponent function<commit_after>function min_unv_exp(num) {
    /* Returns a number representing the minimal universal exponent
     * of a positive integer num, which is assumed to be valid */

    var e = 1; /* This will be the returned exponent, note: needs to be
    one for the first lcm to work */

    /* Iterate through prime factors, computing lcm of each's totient */
    prime_factorization(num).forEach(function(factor){
        if(factor.p === 2) {
            if(factor.e == 2) {
                e = lcm(e, 2);
            }
            else if(factor.e > 2) {
                e = lcm(e, Math.pow(2, factor.e - 2));
            }
        }
        else {
            e = lcm(e, Math.pow(factor.p, factor.e - 1) * (factor.p - 1));
        }
    });

    return e;
}

function prime_factorization(n) {
    /* Returns an array of prime factors (in least sorted order)
     * where each factor is an object of the form
     * {'p': 7, 'e': 4}
     * where p is the prime base and e is the exponent to which that
     * factor is raised in the factorization of n
     */
    var factors = [], e;
    for(var p = 2; p <= n; p++) {
        e = 0;
        while(n % p == 0) {
            n = n / p;
            e++;
        }
        if(e > 0) {
            factors.push({'p':p,'e':e});
        }
    }
    return factors;
}

function gcd(a, b){
    /* Returns greatest common divisor of two (assumed) positive integers
     * Uses Euclidean algorithm
     */
    var t;
    while (b != 0){
        t = b;
        b = a % b;
        a = t;
    }
    return a;
}

function lcm(a, b){
    /* Returns least common multiple of two (assumed) positive integers
     * Uses gcd function above
     */
    return (a * b / gcd(a, b));
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2007 Alexander MacCaw

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

if (typeof Prototype == 'undefined') throw("Juggernaut error. Prototype could not be found.");
if (Prototype.Version < "1.6") throw("Juggernaut error. Prototype 1.6.0 is required.");

var Juggernaut = Class.create({
  is_connected: false,
  attempting_to_reconnect: false,
  ever_been_connected: false,
  hasFirebug: "console" in window && "firebug" in window.console && window.console.firebug.indexOf("1.0") > -1,

  logger: function(msg) {
    if (this.options.debug) {
      msg = "Juggernaut: " + msg + " on " + this.options.host + ':' + this.options.port;
      this.hasFirebug ? console.log(msg) : alert(msg);
    }
  },

  fire_event: function(fx_name) {
     $(document).fire("juggernaut:" + fx_name);
   },

  initialize: function(options) {
    this.options = options.evalJSON();
    Event.observe(window, 'load', function() {
      juggernaut = this;
      this.appendFlashObject();
    }.bind(this));
  },

  initialized: function(){
    this.fire_event('initialized');
    this.connect();
  },

  broadcast: function(body, type, client_ids, channels){
    var msg = new Hash();
    msg.set('command',  'broadcast');
    msg.set('body',     body);
    msg.set('type',     (type||'to_channels'));
    if(channels)  msg.set('channels', channels);
    if(client_ids) msg.set('client_ids', client_ids);
    this.sendData(msg.toJSON());
  },

  sendData: function(data){
    this.swf().sendData(escape(data));
  },

  connect: function(){
    this.fire_event('connect');
    if(!this.is_connected) this.swf().connect(this.options.host, this.options.port);
  },

  disconnect: function(){
    if(this.is_connected) {
      this.swf().disconnect();
      this.is_connected = false;
      this.fire_event('disconnect');
    }
  },

  connected: function(e) {
    var handshake = new Hash();
    handshake.set('command', 'subscribe');
    if(this.options.session_id) handshake.set('session_id', this.options.session_id);
    if(this.options.client_id)  handshake.set('client_id',  this.options.client_id);
    if(this.options.channels)   handshake.set('channels',   this.options.channels);
    if(this.currentMsgId) {
      handshake.set('last_msg_id', this.currentMsgId);
      handshake.set('signature',   this.currentSignature);
    }
    this.sendData(handshake.toJSON());
    this.ever_been_connected = true;
    this.is_connected = true;
    setTimeout(function(){
      if(this.is_connected) this.attempting_to_reconnect = false;
    }.bind(this), 1 * 1000);
    this.logger('Connected');
    this.fire_event('connected');
  },

  receiveData: function(e) {
     var msg = unescape(e.toString()).evalJSON();
     this.currentMsgId = msg.id;
     this.currentSignature = msg.signature;
     this.logger("Received data:\n" + msg.body + "\n");
     eval(msg.body);
  },

  appendFlashObject: function() {
    if($(this.options.swf_name)) {
      throw("Juggernaut error. 'swf_name' must be unique per juggernaut instance.");
    }
    this.element = new Element('div', {
      className: 'juggernaut'
    });
    this.element.setStyle({
      height: this.options.height,
      width:  this.options.width
    });
    $(document.body).insert({ bottom: this.element });
    this.so = new SWFObject(
      this.options.swf_address,
      this.options.swf_name,
      this.options.width,
      this.options.height,
      this.options.flash_version,
      this.options.flash_color
    );
    this.so.useExpressInstall(this.options.ei_swf_address);
	  this.so.addVariable("bridgeName", this.options.bridge_name);
    this.so.write(this.element);
  },

  swf: function(){
    return $(this.options.swf_name);
  },

  refreshFlashObject: function(){
    this.so.write(this.element);
  },

  errorConnecting: function(e) {
    this.is_connected = false;
    if(!this.attempting_to_reconnect) {
      this.logger('There has been an error connecting');
      this.fire_event('errorConnecting');
      this.reconnect();
    }
  },

  disconnected: function(e) {
    this.is_connected = false;
    if(!this.attempting_to_reconnect) {
      this.logger('Connection has been lost');
      this.fire_event('disconnected');
      this.reconnect();
    }
  },

  reconnect: function(){
    if(this.options.reconnect_attempts){
      this.attempting_to_reconnect = true;
      this.fire_event('reconnect');
      this.logger('Will attempt to reconnect ' + this.options.reconnect_attempts + ' times,\
the first in ' + (this.options.reconnect_intervals || 3) + ' seconds');
      for(var i=0; i < this.options.reconnect_attempts; i++){
        setTimeout(function(){
          if(!this.is_connected){
            this.logger('Attempting reconnect');
            if(!this.ever_been_connected){
              this.refreshFlashObject();
            } else {
              this.connect();
            }
          }
        }.bind(this), (this.options.reconnect_intervals || 3) * 1000 * (i + 1))
      }
    }
  }

});<commit_msg>no need for the 'disconnect' event since disconnect() is always called from a user's code<commit_after>/*
Copyright (c) 2007 Alexander MacCaw

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

if (typeof Prototype == 'undefined') throw("Juggernaut error. Prototype could not be found.");
if (Prototype.Version < "1.6") throw("Juggernaut error. Prototype 1.6.0 is required.");

var Juggernaut = Class.create({
  is_connected: false,
  attempting_to_reconnect: false,
  ever_been_connected: false,
  hasFirebug: "console" in window && "firebug" in window.console && window.console.firebug.indexOf("1.0") > -1,

  logger: function(msg) {
    if (this.options.debug) {
      msg = "Juggernaut: " + msg + " on " + this.options.host + ':' + this.options.port;
      this.hasFirebug ? console.log(msg) : alert(msg);
    }
  },

  fire_event: function(fx_name) {
     $(document).fire("juggernaut:" + fx_name);
   },

  initialize: function(options) {
    this.options = options.evalJSON();
    Event.observe(window, 'load', function() {
      juggernaut = this;
      this.appendFlashObject();
    }.bind(this));
  },

  initialized: function(){
    this.fire_event('initialized');
    this.connect();
  },

  broadcast: function(body, type, client_ids, channels){
    var msg = new Hash();
    msg.set('command',  'broadcast');
    msg.set('body',     body);
    msg.set('type',     (type||'to_channels'));
    if(channels)  msg.set('channels', channels);
    if(client_ids) msg.set('client_ids', client_ids);
    this.sendData(msg.toJSON());
  },

  sendData: function(data){
    this.swf().sendData(escape(data));
  },

  connect: function(){
    this.fire_event('connect');
    if(!this.is_connected) this.swf().connect(this.options.host, this.options.port);
  },

  disconnect: function(){
    if(this.is_connected) {
      this.swf().disconnect();
      this.is_connected = false;
    }
  },

  connected: function(e) {
    var handshake = new Hash();
    handshake.set('command', 'subscribe');
    if(this.options.session_id) handshake.set('session_id', this.options.session_id);
    if(this.options.client_id)  handshake.set('client_id',  this.options.client_id);
    if(this.options.channels)   handshake.set('channels',   this.options.channels);
    if(this.currentMsgId) {
      handshake.set('last_msg_id', this.currentMsgId);
      handshake.set('signature',   this.currentSignature);
    }
    this.sendData(handshake.toJSON());
    this.ever_been_connected = true;
    this.is_connected = true;
    setTimeout(function(){
      if(this.is_connected) this.attempting_to_reconnect = false;
    }.bind(this), 1 * 1000);
    this.logger('Connected');
    this.fire_event('connected');
  },

  receiveData: function(e) {
     var msg = unescape(e.toString()).evalJSON();
     this.currentMsgId = msg.id;
     this.currentSignature = msg.signature;
     this.logger("Received data:\n" + msg.body + "\n");
     eval(msg.body);
  },

  appendFlashObject: function() {
    if($(this.options.swf_name)) {
      throw("Juggernaut error. 'swf_name' must be unique per juggernaut instance.");
    }
    this.element = new Element('div', {
      className: 'juggernaut'
    });
    this.element.setStyle({
      height: this.options.height,
      width:  this.options.width
    });
    $(document.body).insert({ bottom: this.element });
    this.so = new SWFObject(
      this.options.swf_address,
      this.options.swf_name,
      this.options.width,
      this.options.height,
      this.options.flash_version,
      this.options.flash_color
    );
    this.so.useExpressInstall(this.options.ei_swf_address);
	  this.so.addVariable("bridgeName", this.options.bridge_name);
    this.so.write(this.element);
  },

  swf: function(){
    return $(this.options.swf_name);
  },

  refreshFlashObject: function(){
    this.so.write(this.element);
  },

  errorConnecting: function(e) {
    this.is_connected = false;
    if(!this.attempting_to_reconnect) {
      this.logger('There has been an error connecting');
      this.fire_event('errorConnecting');
      this.reconnect();
    }
  },

  disconnected: function(e) {
    this.is_connected = false;
    if(!this.attempting_to_reconnect) {
      this.logger('Connection has been lost');
      this.fire_event('disconnected');
      this.reconnect();
    }
  },

  reconnect: function(){
    if(this.options.reconnect_attempts){
      this.attempting_to_reconnect = true;
      this.fire_event('reconnect');
      this.logger('Will attempt to reconnect ' + this.options.reconnect_attempts + ' times,\
the first in ' + (this.options.reconnect_intervals || 3) + ' seconds');
      for(var i=0; i < this.options.reconnect_attempts; i++){
        setTimeout(function(){
          if(!this.is_connected){
            this.logger('Attempting reconnect');
            if(!this.ever_been_connected){
              this.refreshFlashObject();
            } else {
              this.connect();
            }
          }
        }.bind(this), (this.options.reconnect_intervals || 3) * 1000 * (i + 1))
      }
    }
  }

});<|endoftext|>


<commit_before>/*global getJSON*/
/*jslint vars:true, todo:true*/
(function () {'use strict';

    function getRandomIntInclusive(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    function initialCase (str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    function WorldCreator (cfg) {
        if (!(this instanceof WorldCreator)) {
            return new WorldCreator();
        }
        cfg = cfg || {};
        if (cfg.prompt) {
            this.prompt = cfg.prompt;
        }
        if (cfg.alert) {
            this.alert = cfg.alert;
        }
        this.directions = cfg.directions || ['north', 'south', 'east', 'west', 'northeast', 'northwest', 'southeast', 'southwest'];
    }
    WorldCreator.prototype.processJSON = function (json) {
        this.gameType = json.gameType; // roomID, treasure (and minimum), all
        this.gameValue = json.gameValue;
        this.describeDirections = json.describeDirections === undefined ? true : json.describeDirections;

        this.defaultRoomType = json.defaultRoomType;
        this.antagonists = json.antagonists; // id: description, strength, agility
        this.treasures = json.treasures; // id: description, value

        this.userPattern = json.userPattern;
        this.injuryLevels = json.injuryLevels;
        this.characterTypes = json.characterTypes;
        this.rooms = json.rooms;

        // Todo: Give choice from existing users or option to create a new one
        // Todo: Save user stats and allow reuse
        this.createCharacter(function () {
            var room = this.rooms[json.startingRoom];
            this.processRoom(room);
        }.bind(this));
    };
    WorldCreator.prototype.createCharacter = function (cb) {
        this.user = {};
        this.prompt("characterType", "Please choose a type of character: " + Object.keys(this.characterTypes)./*map(function (characterType) {
            return this.characterTypes[characterType].name;
        }, this).*/join(', '), function (characterType) {
            this.createCharacterAttributes(characterType, cb);
        }, this);
    };
    WorldCreator.prototype.createCharacterAttributes = function (characterType, cb) {
        this.userPattern = this.characterTypes[characterType];
        if (!this.userPattern) {
            this.alert("wrongCharacterType", "Please choose a valid character type", function () {
                this.createCharacter(cb);
            }, this);
            return;
        }

        var strength = this.userPattern.strength;
        var agility = this.userPattern.agility;
        this.user.strength = WorldCreator.getRandomIntInclusive(strength.min, strength.max);
        this.user.agility = WorldCreator.getRandomIntInclusive(agility.min, agility.max);
        this.user.treasure = 0;
        this.prompt("userName", "You have strength " + this.user.strength + ", agility " + this.user.agility + "; Please choose a name for your character", function (name) {
            if (!name) {
                this.alert("wrongUserName", "Please choose a valid user name.", function () {
                    this.createCharacterAttributes(characterType, cb);
                }, this);
                return;
            }
            this.user.name = name;
            cb();
        }, this);
    };
    WorldCreator.prototype.processRoom = function (room) {
        var antagonist = this.antagonists[room.antagonistID]; // description, strength, agility
        var treasure = this.treasures[room.treasureID]; // description, value

        var desc = room.description.
                replace(/\{\{antagonist\}\}/g, antagonist.description).
                replace(/\{\{antagonist\|initialCap\}\}/g, function () {
                    return initialCase(antagonist.description);
                }).
                replace(/\{\{treasure\}\}/g, treasure.description).
                replace(/\{\{treasure\|initialCap\}\}/g, function () {
                    return initialCase(treasure.description);
                }) +
            (this.describeDirections ? " You may go " + Object.keys(room.rooms).join(', ') : '') +
            '\n';

        desc += " What would you like to do (attack, north, south, etc.)?";

        this.prompt("action", desc, function (action) {
            if (this.directions.indexOf(action) > -1) {
                if (!room.rooms[action]) {
                    return this.alert("wrongDirection", "You can't go that direction.", function () {
                        this.processRoom(room);
                    }, this);
                }
                this.processRoom(room.rooms[action]);
            }
            else if (action === 'a' || action === 'attack') {
                var userRand = Math.random();
                var antagRand = Math.random();
                if ((userRand + this.user.strength) > (antagRand + antagonist.agility)) {

                }
                this.user.agility;
                antagonist.strength;
                this.injuryLevels.user[i].replace(/\{\{user\}\}/g, this.user.name);
                this.injuryLevels.antagonist[i].replace(/\{\{antagonist\}\}/g, antagonist.description);

                this.user.treasure += treasure.value;
                if (this.gameType === '') { // roomID, treasure (and minimum), all
                    this.gameValue;
                }
            }
            else {
                this.alert("wrongAction", "The action you have chosen is not recognized. Please try another.", function () {
                    this.processRoom(room);
                }, this);
            }
        }, this);
    };
    WorldCreator.prototype.alert = function (code, msg, cb, thisArg) {
        alert(msg);
        cb.call(thisArg, code);
    };
    WorldCreator.prototype.prompt = function (code, desc, cb, thisArg) {
        var response = prompt(desc);
        cb.call(thisArg, response, code);
    };
    WorldCreator.prototype.createWorld = function (jsonURL) {
        if (typeof jsonURL === 'string') {
            getJSON(jsonURL, this.processJSON.bind(this));
        }
        else {
            this.processJSON(jsonURL);
        }
    };
    WorldCreator.getRandomIntInclusive = getRandomIntInclusive;

    window.WorldCreator = WorldCreator;
}());
<commit_msg>fix room for moving<commit_after>/*global getJSON*/
/*jslint vars:true, todo:true*/
(function () {'use strict';

    function getRandomIntInclusive(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    function initialCase (str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    function WorldCreator (cfg) {
        if (!(this instanceof WorldCreator)) {
            return new WorldCreator();
        }
        cfg = cfg || {};
        if (cfg.prompt) {
            this.prompt = cfg.prompt;
        }
        if (cfg.alert) {
            this.alert = cfg.alert;
        }
        this.directions = cfg.directions || ['north', 'south', 'east', 'west', 'northeast', 'northwest', 'southeast', 'southwest'];
    }
    WorldCreator.prototype.processJSON = function (json) {
        this.gameType = json.gameType; // roomID, treasure (and minimum), all
        this.gameValue = json.gameValue;
        this.describeDirections = json.describeDirections === undefined ? true : json.describeDirections;

        this.defaultRoomType = json.defaultRoomType;
        this.antagonists = json.antagonists; // id: description, strength, agility
        this.treasures = json.treasures; // id: description, value

        this.userPattern = json.userPattern;
        this.injuryLevels = json.injuryLevels;
        this.characterTypes = json.characterTypes;
        this.rooms = json.rooms;

        // Todo: Give choice from existing users or option to create a new one
        // Todo: Save user stats and allow reuse
        this.createCharacter(function () {
            var room = this.rooms[json.startingRoom];
            this.processRoom(room);
        }.bind(this));
    };
    WorldCreator.prototype.createCharacter = function (cb) {
        this.user = {};
        this.prompt("characterType", "Please choose a type of character: " + Object.keys(this.characterTypes)./*map(function (characterType) {
            return this.characterTypes[characterType].name;
        }, this).*/join(', '), function (characterType) {
            this.createCharacterAttributes(characterType, cb);
        }, this);
    };
    WorldCreator.prototype.createCharacterAttributes = function (characterType, cb) {
        this.userPattern = this.characterTypes[characterType];
        if (!this.userPattern) {
            this.alert("wrongCharacterType", "Please choose a valid character type", function () {
                this.createCharacter(cb);
            }, this);
            return;
        }

        var strength = this.userPattern.strength;
        var agility = this.userPattern.agility;
        this.user.strength = WorldCreator.getRandomIntInclusive(strength.min, strength.max);
        this.user.agility = WorldCreator.getRandomIntInclusive(agility.min, agility.max);
        this.user.treasure = 0;
        this.prompt("userName", "You have strength " + this.user.strength + ", agility " + this.user.agility + "; Please choose a name for your character", function (name) {
            if (!name) {
                this.alert("wrongUserName", "Please choose a valid user name.", function () {
                    this.createCharacterAttributes(characterType, cb);
                }, this);
                return;
            }
            this.user.name = name;
            cb();
        }, this);
    };
    WorldCreator.prototype.processRoom = function (room) {
        var antagonist = this.antagonists[room.antagonistID]; // description, strength, agility
        var treasure = this.treasures[room.treasureID]; // description, value

        var desc = room.description.
                replace(/\{\{antagonist\}\}/g, antagonist.description).
                replace(/\{\{antagonist\|initialCap\}\}/g, function () {
                    return initialCase(antagonist.description);
                }).
                replace(/\{\{treasure\}\}/g, treasure.description).
                replace(/\{\{treasure\|initialCap\}\}/g, function () {
                    return initialCase(treasure.description);
                }) +
            (this.describeDirections ? " You may go " + Object.keys(room.rooms).join(', ') : '') +
            '\n';

        desc += " What would you like to do (attack, north, south, etc.)?";

        this.prompt("action", desc, function (action) {
            if (this.directions.indexOf(action) > -1) {
                if (!room.rooms[action]) {
                    return this.alert("wrongDirection", "You can't go that direction.", function () {
                        this.processRoom(room);
                    }, this);
                }
                this.processRoom(this.rooms[room.rooms[action]]);
            }
            else if (action === 'a' || action === 'attack') {
                var userRand = Math.random();
                var antagRand = Math.random();
                if ((userRand + this.user.strength) > (antagRand + antagonist.agility)) {

                }
                this.user.agility;
                antagonist.strength;
                this.injuryLevels.user[i].replace(/\{\{user\}\}/g, this.user.name);
                this.injuryLevels.antagonist[i].replace(/\{\{antagonist\}\}/g, antagonist.description);

                this.user.treasure += treasure.value;
                if (this.gameType === '') { // roomID, treasure (and minimum), all
                    this.gameValue;
                }
            }
            else {
                this.alert("wrongAction", "The action you have chosen is not recognized. Please try another.", function () {
                    this.processRoom(room);
                }, this);
            }
        }, this);
    };
    WorldCreator.prototype.alert = function (code, msg, cb, thisArg) {
        alert(msg);
        cb.call(thisArg, code);
    };
    WorldCreator.prototype.prompt = function (code, desc, cb, thisArg) {
        var response = prompt(desc);
        cb.call(thisArg, response, code);
    };
    WorldCreator.prototype.createWorld = function (jsonURL) {
        if (typeof jsonURL === 'string') {
            getJSON(jsonURL, this.processJSON.bind(this));
        }
        else {
            this.processJSON(jsonURL);
        }
    };
    WorldCreator.getRandomIntInclusive = getRandomIntInclusive;

    window.WorldCreator = WorldCreator;
}());
<|endoftext|>


<commit_before>module.exports = function (grunt) {

  grunt.loadNpmTasks( 'grunt-browserify' )
  grunt.loadNpmTasks( 'gruntify-eslint' )
  grunt.loadNpmTasks( 'grunt-contrib-copy' )
  grunt.loadNpmTasks( 'grunt-contrib-less' )

  var allJSFilesInJSFolder = 'js/**/*.js'
  var distFolder = '../wikipedia/assets/'

  grunt.initConfig( {

    browserify: {
      distMain: {
        src: [
          'index-main.js',
          allJSFilesInJSFolder,
          '!preview-main.js'
        ],
        dest: `${distFolder}index.js`
      },
      distPreview: {
        src: [
          'preview-main.js',
          'js/utilities.js'
        ],
        dest: `${distFolder}preview.js`
      },
      distAbout: {
        src: [
          'about-main.js'
        ],
        dest: `${distFolder}about.js`
      }
    },

    less: {
      all: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: [
          {
            src: 'less/**/*.less',
            dest: `${distFolder}styleoverrides.css`
          }
        ]
      }
    },

    eslint: {
      src: [
        '*.js',
        allJSFilesInJSFolder
      ],
      options: {
        fix: false
      }
    },

    copy: {
      main: {
        files: [
          {
            src: [
              '*.html',
              '*.css',
              'ios.json',
              'languages.json',
              'mainpages.json',
              '*.png',
              '*.pdf'
            ],
            dest: distFolder
          },
          {
            src: 'node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css',
            dest: `${distFolder}wikimedia-page-library-transform.css`
          }
        ]
      }
    }
  } )

  grunt.registerTask('default', [
    'eslint',
    'browserify',
    'less',
    'copy'
  ])
}<commit_msg>Fix JS '.map' file warning.<commit_after>module.exports = function (grunt) {

  grunt.loadNpmTasks( 'grunt-browserify' )
  grunt.loadNpmTasks( 'gruntify-eslint' )
  grunt.loadNpmTasks( 'grunt-contrib-copy' )
  grunt.loadNpmTasks( 'grunt-contrib-less' )

  var allJSFilesInJSFolder = 'js/**/*.js'
  var distFolder = '../wikipedia/assets/'

  grunt.initConfig( {

    browserify: {
      distMain: {
        src: [
          'index-main.js',
          allJSFilesInJSFolder,
          '!preview-main.js'
        ],
        dest: `${distFolder}index.js`
      },
      distPreview: {
        src: [
          'preview-main.js',
          'js/utilities.js'
        ],
        dest: `${distFolder}preview.js`
      },
      distAbout: {
        src: [
          'about-main.js'
        ],
        dest: `${distFolder}about.js`
      }
    },

    less: {
      all: {
        options: {
          compress: true,
          yuicompress: true,
          optimization: 2
        },
        files: [
          {
            src: 'less/**/*.less',
            dest: `${distFolder}styleoverrides.css`
          }
        ]
      }
    },

    eslint: {
      src: [
        '*.js',
        allJSFilesInJSFolder
      ],
      options: {
        fix: false
      }
    },

    copy: {
      main: {
        files: [
          {
            src: [
              '*.html',
              '*.css',
              'ios.json',
              'languages.json',
              'mainpages.json',
              '*.png',
              '*.pdf'
            ],
            dest: distFolder
          },
          {
            src: 'node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css',
            dest: `${distFolder}wikimedia-page-library-transform.css`
          },
          {
            src: 'node_modules/wikimedia-page-library/build/wikimedia-page-library-transform.css.map',
            dest: `${distFolder}wikimedia-page-library-transform.css.map`
          }
        ]
      }
    }
  } )

  grunt.registerTask('default', [
    'eslint',
    'browserify',
    'less',
    'copy'
  ])
}<|endoftext|>


<commit_before>/*
    Copyright 2015 IBM Corp.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
var exec = require("cordova/exec");

var success = function(message) {
    console.log("Success");
    console.log(message);
};
var failure = function(message) {
    console.log("Failure");
    console.log(message);
};

var Logger = function (name){
    this.name = name; // instance variable
};

Logger.prototype = function(){
    var debug = function (message) {
        cordova.exec(success, failure, "MFPLogger", "debug", [this.name, message]);
    }
    var info = function (message) {
        cordova.exec(success, failure, "MFPLogger", "info", [this.name, message]);
    }
    var error = function (message) {
        cordova.exec(success, failure, "MFPLogger", "error", [this.name, message]);
    }
    var fatal = function (message) {
        cordova.exec(success, failure, "MFPLogger", "fatal", [this.name, message]);
    }
    var warn = function (message) {
        cordova.exec(success, failure, "MFPLogger", "warn", [this.name, message]);
    }
    var getName = function () {
        return this.name;
    }

    return {
        debug : debug,
        info : info,
        error : error,
        fatal : fatal,
        warn : warn,
        getName : getName
    };
}();

var MFPLogger = (function () {
    var instances = {};

    function createInstance(name) {
        var logger = new Logger(name);
        return logger;
    }

    return {
        getInstance: function (name) {
            if (!instances[name]) {
                instances[name] = createInstance(name);
            }
            cordova.exec(success , failure, "MFPLogger", "getInstance", [name]);
            return instances[name];
        },
        getCapture : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getCapture", []);
        },
        setCapture : function (enabled) {
            cordova.exec(success , failure, "MFPLogger", "setCapture", [enabled]);
        },
        getFilters : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getFilters", []);
        },
        setFilters : function (filters) {
            cordova.exec(success , failure, "MFPLogger", "setFilters", [filters]);
        },
        getMaxStoreSize : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getMaxStoreSize", []);
        },
        setMaxStoreSize : function (intSize) {
            cordova.exec(success , failure, "MFPLogger", "setMaxStoreSize", [intSize]);
        },
        getLevel : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getLevel", []);
        },
        setLevel : function (logLevel) {
            cordova.exec(success , failure, "MFPLogger", "setLevel", [logLevel]);
        },
        isUncaughtExceptionDetected : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "isUncaughtExceptionDetected", []);
        },
        send : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "send", []);
        }
    };
});
MFPLogger.FATAL = "FATAL";
MFPLogger.ERROR = "ERROR";
MFPLogger.WARN = "WARN";
MFPLogger.INFO = "INFO";
MFPLogger.DEBUG = "DEBUG";

module.exports = new MFPLogger();<commit_msg>updated Log Level values to match those defined in Client SDKs and Worklight<commit_after>/*
    Copyright 2015 IBM Corp.
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
        http://www.apache.org/licenses/LICENSE-2.0
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/
var exec = require("cordova/exec");

var success = function(message) {
    console.log("Success");
    console.log(message);
};
var failure = function(message) {
    console.log("Failure");
    console.log(message);
};

var Logger = function (name){
    this.name = name; // instance variable
};

Logger.prototype = function(){
    var debug = function (message) {
        cordova.exec(success, failure, "MFPLogger", "debug", [this.name, message]);
    }
    var info = function (message) {
        cordova.exec(success, failure, "MFPLogger", "info", [this.name, message]);
    }
    var error = function (message) {
        cordova.exec(success, failure, "MFPLogger", "error", [this.name, message]);
    }
    var fatal = function (message) {
        cordova.exec(success, failure, "MFPLogger", "fatal", [this.name, message]);
    }
    var warn = function (message) {
        cordova.exec(success, failure, "MFPLogger", "warn", [this.name, message]);
    }
    var getName = function () {
        return this.name;
    }

    return {
        debug : debug,
        info : info,
        error : error,
        fatal : fatal,
        warn : warn,
        getName : getName
    };
}();

var MFPLogger = (function () {
    var instances = {};

    function createInstance(name) {
        var logger = new Logger(name);
        return logger;
    }

    return {
        getInstance: function (name) {
            if (!instances[name]) {
                instances[name] = createInstance(name);
            }
            cordova.exec(success , failure, "MFPLogger", "getInstance", [name]);
            return instances[name];
        },
        getCapture : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getCapture", []);
        },
        setCapture : function (enabled) {
            cordova.exec(success , failure, "MFPLogger", "setCapture", [enabled]);
        },
        getFilters : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getFilters", []);
        },
        setFilters : function (filters) {
            cordova.exec(success , failure, "MFPLogger", "setFilters", [filters]);
        },
        getMaxStoreSize : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getMaxStoreSize", []);
        },
        setMaxStoreSize : function (intSize) {
            cordova.exec(success , failure, "MFPLogger", "setMaxStoreSize", [intSize]);
        },
        getLevel : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "getLevel", []);
        },
        setLevel : function (logLevel) {
            cordova.exec(success , failure, "MFPLogger", "setLevel", [logLevel]);
        },
        isUncaughtExceptionDetected : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "isUncaughtExceptionDetected", []);
        },
        send : function (success, failure) {
            cordova.exec(success , failure, "MFPLogger", "send", []);
        }
    };
});

/** Trace level */
MFPLogger.FATAL = 50;
MFPLogger.ERROR = 100;
MFPLogger.WARN = 200;
MFPLogger.INFO = 300;
MFPLogger.DEBUG = 500;

module.exports = new MFPLogger();<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var utils = require('cordova/utils'),
    exec = require('cordova/exec'),
    File = require('cordova-plugin-file.File'),
    CaptureError = require('./CaptureError');
/**
 * Represents a single file.
 *
 * name {DOMString} name of the file, without path information
 * fullPath {DOMString} the full path of the file, including the name
 * type {DOMString} mime type
 * lastModifiedDate {Date} last modified date
 * size {Number} size of the file in bytes
 */
var MediaFile = function(name, localURL, type, lastModifiedDate, size){
    MediaFile.__super__.constructor.apply(this, arguments);
};

utils.extend(MediaFile, File);

/**
 * Request capture format data for a specific file and type
 *
 * @param {Function} successCB
 * @param {Function} errorCB
 */
MediaFile.prototype.getFormatData = function(successCallback, errorCallback) {
    if (typeof this.fullPath === "undefined" || this.fullPath === null) {
        errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
    } else {
        exec(successCallback, errorCallback, "Capture", "getFormatData", [this.localURL, this.type]);
    }
};

module.exports = MediaFile;
<commit_msg>CB-10488 Fix for MediaFile.getFormatData<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var utils = require('cordova/utils'),
    exec = require('cordova/exec'),
    File = require('cordova-plugin-file.File'),
    CaptureError = require('./CaptureError');
/**
 * Represents a single file.
 *
 * name {DOMString} name of the file, without path information
 * fullPath {DOMString} the full path of the file, including the name
 * type {DOMString} mime type
 * lastModifiedDate {Date} last modified date
 * size {Number} size of the file in bytes
 */
var MediaFile = function(name, localURL, type, lastModifiedDate, size){
    MediaFile.__super__.constructor.apply(this, arguments);
};

utils.extend(MediaFile, File);

/**
 * Request capture format data for a specific file and type
 *
 * @param {Function} successCB
 * @param {Function} errorCB
 */
MediaFile.prototype.getFormatData = function(successCallback, errorCallback) {
    if (typeof this.fullPath === "undefined" || this.fullPath === null) {
        errorCallback(new CaptureError(CaptureError.CAPTURE_INVALID_ARGUMENT));
    } else {
        exec(successCallback, errorCallback, "Capture", "getFormatData", [this.fullPath, this.type]);
    }
};

module.exports = MediaFile;
<|endoftext|>