<commit_before>/// <reference path="Chunck.js" />
/// <reference path="BoundingBox.js" />
/// <reference path="gl-Matrix.js" />
function Quadtree(option)
{
    this.initialRootSize = option.initialRootSize;

    this.chunck = new Chunck(option.chunckSize);
    this.chunck.create();
    this.nodeCenter = vec3.create();

    this.initialtexturePath = option.initialtexturePath;
    this.initialElevationPath = option.initialElevationPath;

    this.rootNode = new QuadtreeNode(vec3.create([0, 0, 0]), option.initialRootSize, vec3.create([255, 0, 0]), vec3.create([0, 0, 0]), "", option.quadtreeDepth, "", "-1",undefined, this.chunck.bbox);

    this._build(this.rootNode);
    this._Wms = new Wms(option.initialRootSize);
    this.counter = 0;

};

Quadtree.prototype =
{
    _build: function (node)
    {
        if (node.depth > 1)
        {
            this._addNode(node);

            for (var i = 0; i < 4; i++)
            {
                this._build(node.child[i]);
            }
        }
    },

    _removeChilds : function(node) {
        node.child = [];
    },

    _addNode: function (node)
    {
        var scaling = node.scaleFactor * 0.5;

        var centerUpperLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, scaling]), centerUpperLeft);

        var centerUpperRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, scaling]), centerUpperRight);

        var centerLowerLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, -scaling]), centerLowerLeft);

        var centerLowerRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, -scaling]), centerLowerRight);

        var upperLeft  = new QuadtreeNode(centerUpperLeft, scaling, vec3.create([255, 0, 0]), centerUpperLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 2, node, this.chunck.bbox, node.elevation);
        var upperRight = new QuadtreeNode(centerUpperRight, scaling, vec3.create([0, 255, 0]), centerUpperRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 3, node, this.chunck.bbox, node.elevation);
        var lowerLeft  = new QuadtreeNode(centerLowerLeft, scaling, vec3.create([0, 0, 255]), centerLowerLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 0, node, this.chunck.bbox, node.elevation);
        var lowerRight = new QuadtreeNode(centerLowerRight, scaling, vec3.create([255, 0, 255]), centerLowerRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 1, node, this.chunck.bbox, node.elevation);

        node.child[0] = upperLeft;
        node.child[1] = upperRight;
        node.child[2] = lowerLeft;
        node.child[3] = lowerRight;

        node.type = 1;

    },

    setMatrixUniforms : function(projMatrix, viewMatrix, spherify, camera)
    {
        this.chunck.setMatrixUniforms(projMatrix, viewMatrix, spherify, camera);
    },

    setBBoxMatrixUniforms: function (projMatrix, viewMatrix)
    {
        this.chunck.setBBoxMatrixUniforms(projMatrix, viewMatrix);
    },

    setProgram: function ()
    {
        this.chunck.setProgram();
    },

    setBBoxProgram : function() {
        this.chunck.setBBoxProgram();
    },

    disableProgram: function ()
    {
        this.chunck.disableProgram();
    },

    removechild:function(parent)
    {
        for(var i =0 ; i < parent.child.length;i++)
        {
            if(parent.child[i].texture!==null && parent.child[i].texture.image!==null)
            {
                parent.child[i].texture.image.removeEventListener("load",parent.child[i].loadtextureHandler, false);
                parent.child[i].texture.image = null;
            }

            if(parent.child[i].elevation!==null && parent.child[i].elevation.image!==null)
            {
                parent.child[i].elevation.image.removeEventListener("load",parent.child[i].loadElevation, false);
                parent.child[i].elevation.image = null;
            }

            if(parent.child[i].child.length > 0)
            {
                this.removechild(parent.child[i])
                parent.child[i] = null;
            }
        }
    },

    //node.type == 2 ---->leaf
    draw: function (wireframe, frustum, node, ext, delta, tile, Wms) {

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

        if(!frustum.isBoxInsideFrustum(node.bbox)){
            node.type = 2;

            if(node.child.length >0)
            {
                this.removechild(node);
            }

            node.child = [];

            if(node.texture!==null && node.texture.image!==null)
            {
                node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                node.texture.image = null;
            }

            if(node.elevation!==null && node.elevation.image!==null)
            {
                node.elevation.image.removeEventListener("load",node.loadElevation, false);
                node.elevation.image = null;
            }

            return;
        }

        if(frustum.isBoxInsideFrustum(node.bbox) && node.child.length < 4){
            this._addNode(node);
        }

        this.nodeCenter = node.center;
        this.chunckDistFromCamera = Math.sqrt((frustum.position[0] - this.nodeCenter[0]) * (frustum.position[0] - this.nodeCenter[0]) +
                                              (frustum.position[1] - this.nodeCenter[1]) * (frustum.position[1] - this.nodeCenter[1]) +
                                              (frustum.position[2] - this.nodeCenter[2]) * (frustum.position[2] - this.nodeCenter[2]));

        if (this.chunckDistFromCamera - delta >=0.01  && node.type === 1) {

            if (tile !== node.initialtexturePath)
            {
                node.updateTexturePath(tile);
            }

            if (node.parent!== undefined
                && node.parent.child[0].textureLoaded && node.parent.child[0].elevationLoaded
                && node.parent.child[1].textureLoaded && node.parent.child[1].elevationLoaded
                && node.parent.child[2].textureLoaded && node.parent.child[2].elevationLoaded
                && node.parent.child[3].textureLoaded && node.parent.child[3].elevationLoaded) {

                this.chunck.prerender(node);
                this.chunck.draw(wireframe);
                return;
            }

            if (!node.textureLoaded  && this.counter < 6) {

                node.getTexture(ext, function ()
                {
                    if(node.texture.image ===null)
                        return;

                    node.textureLoaded = true;
                    node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                    node.texture.image = null;
                });
                this.counter++;
            }

            if (!node.elevationLoaded  && this.counter < 6) {
                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    if(node.elevation.image ===null)
                        return;

                    node.elevationLoaded = true;
                    node.elevation.image.removeEventListener("load", node.loadElevation, false);
                    node.elevation.image = null;
                });

                this.counter++;
            }

            //Blurring
            if ((!node.elevationLoaded || !node.textureLoaded) && node.type === 1)
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

        }
        else
        {
            if (node.type !== 1)
            {

                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    this._addNode(node);

                }.bind(this));

                this.counter++;
            }
            else if(node.type === 1 && node.child.length > 0)
            {
                for (var i = 0; i < 4; i++)
                {
                    this.draw(wireframe, frustum, node.child[i], ext, delta/2.0, tile, Wms);
                }
            }
        }
    }
};<commit_msg>optimization<commit_after>/// <reference path="Chunck.js" />
/// <reference path="BoundingBox.js" />
/// <reference path="gl-Matrix.js" />
function Quadtree(option)
{
    this.initialRootSize = option.initialRootSize;

    this.chunck = new Chunck(option.chunckSize);
    this.chunck.create();
    this.nodeCenter = vec3.create();

    this.initialtexturePath = option.initialtexturePath;
    this.initialElevationPath = option.initialElevationPath;

    this.rootNode = new QuadtreeNode(vec3.create([0, 0, 0]), option.initialRootSize, vec3.create([255, 0, 0]), vec3.create([0, 0, 0]), "", option.quadtreeDepth, "", "-1",undefined, this.chunck.bbox);

    this._build(this.rootNode);
    this._Wms = new Wms(option.initialRootSize);
    this.counter = 0;

};

Quadtree.prototype =
{
    _build: function (node)
    {
        if (node.depth > 1)
        {
            this._addNode(node);

            for (var i = 0; i < 4; i++)
            {
                this._build(node.child[i]);
            }
        }
    },

    _removeChilds : function(node) {
        node.child = [];
    },

    _addNode: function (node)
    {
        var scaling = node.scaleFactor * 0.5;

        var centerUpperLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, scaling]), centerUpperLeft);

        var centerUpperRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, scaling]), centerUpperRight);

        var centerLowerLeft = vec3.create();
        vec3.add(node.center, vec3.create([-scaling, 0, -scaling]), centerLowerLeft);

        var centerLowerRight = vec3.create();
        vec3.add(node.center, vec3.create([scaling, 0, -scaling]), centerLowerRight);

        var upperLeft  = new QuadtreeNode(centerUpperLeft, scaling, vec3.create([255, 0, 0]), centerUpperLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 2, node, this.chunck.bbox, node.elevation);
        var upperRight = new QuadtreeNode(centerUpperRight, scaling, vec3.create([0, 255, 0]), centerUpperRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 3, node, this.chunck.bbox, node.elevation);
        var lowerLeft  = new QuadtreeNode(centerLowerLeft, scaling, vec3.create([0, 0, 255]), centerLowerLeft, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 0, node, this.chunck.bbox, node.elevation);
        var lowerRight = new QuadtreeNode(centerLowerRight, scaling, vec3.create([255, 0, 255]), centerLowerRight, this.initialtexturePath, node.depth - 1, this.initialElevationPath, 1, node, this.chunck.bbox, node.elevation);

        node.child[0] = upperLeft;
        node.child[1] = upperRight;
        node.child[2] = lowerLeft;
        node.child[3] = lowerRight;

        node.type = 1;

    },

    setMatrixUniforms : function(projMatrix, viewMatrix, spherify, camera)
    {
        this.chunck.setMatrixUniforms(projMatrix, viewMatrix, spherify, camera);
    },

    setBBoxMatrixUniforms: function (projMatrix, viewMatrix)
    {
        this.chunck.setBBoxMatrixUniforms(projMatrix, viewMatrix);
    },

    setProgram: function ()
    {
        this.chunck.setProgram();
    },

    setBBoxProgram : function() {
        this.chunck.setBBoxProgram();
    },

    disableProgram: function ()
    {
        this.chunck.disableProgram();
    },

    removechild:function(parent)
    {
        for(var i =0 ; i < parent.child.length;i++)
        {
            if(parent.child[i].texture!==null && parent.child[i].texture.image!==null)
            {
                parent.child[i].texture.image.removeEventListener("load",parent.child[i].loadtextureHandler, false);
                parent.child[i].texture.image = null;
            }

            if(parent.child[i].elevation!==null && parent.child[i].elevation.image!==null)
            {
                parent.child[i].elevation.image.removeEventListener("load",parent.child[i].loadElevation, false);
                parent.child[i].elevation.image = null;
            }

            if(parent.child[i].child.length > 0)
            {
                this.removechild(parent.child[i])
                parent.child[i] = null;
            }
        }
    },

    //node.type == 2 ---->leaf
    draw: function (wireframe, frustum, node, ext, delta, tile, Wms) {

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

        if(!frustum.isBoxInsideFrustum(node.bbox)){
            node.type = 2;

            if(node.child.length >0)
            {
                this.removechild(node);
            }

            node.child = [];

            if(node.texture!==null && node.texture.image!==null)
            {
                node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                node.texture.image = null;
            }

            if(node.elevation!==null && node.elevation.image!==null)
            {
                node.elevation.image.removeEventListener("load",node.loadElevation, false);
                node.elevation.image = null;
            }

            return;
        }

        if(frustum.isBoxInsideFrustum(node.bbox) && node.child.length < 4){
            this._addNode(node);
        }

        this.nodeCenter = node.center;
        this.chunckDistFromCamera = Math.sqrt((frustum.position[0] - this.nodeCenter[0]) * (frustum.position[0] - this.nodeCenter[0]) +
                                              (frustum.position[1] - this.nodeCenter[1]) * (frustum.position[1] - this.nodeCenter[1]) +
                                              (frustum.position[2] - this.nodeCenter[2]) * (frustum.position[2] - this.nodeCenter[2]));

        if (this.chunckDistFromCamera - delta >=0.01  && node.type === 1) {

            if (tile !== node.initialtexturePath)
            {
                node.updateTexturePath(tile);
            }

            if (node.parent!== undefined
                && node.parent.child[0].textureLoaded && node.parent.child[0].elevationLoaded
                && node.parent.child[1].textureLoaded && node.parent.child[1].elevationLoaded
                && node.parent.child[2].textureLoaded && node.parent.child[2].elevationLoaded
                && node.parent.child[3].textureLoaded && node.parent.child[3].elevationLoaded) {

                this.chunck.prerender(node);
                this.chunck.draw(wireframe);
                return;
            }

            if (!node.textureLoaded  && this.counter < 6) {

                node.getTexture(ext, function ()
                {
                    if(node.texture.image ===null)
                        return;

                    node.textureLoaded = true;
                    node.texture.image.removeEventListener("load",node.loadtextureHandler, false);
                    node.texture.image = null;
                });
                this.counter++;
            }

            if (!node.elevationLoaded  && this.counter < 6) {
                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    if(node.elevation.image ===null)
                        return;

                    node.elevationLoaded = true;
                    node.elevation.image.removeEventListener("load", node.loadElevation, false);
                    node.elevation.image = null;
                });

                this.counter++;
            }

            //Blurring
            if ((!node.elevationLoaded || !node.textureLoaded) && node.type === 1)
                this.draw(wireframe, frustum, node.parent, ext, delta , tile, Wms);

        }
        else
        {
            if (node.type !== 1)
            {

                this._Wms.prepareRequest(node);

                node.getElevationFromWms(this._Wms.url, function ()
                {
                    if(node.elevation.image ===null)
                        return;

                    node.elevationLoaded = true;
                    node.elevation.image.removeEventListener("load", node.loadElevation, false);
                    node.elevation.image = null;
                });

                this.counter++;
            }
            else if(node.type === 1 && node.child.length > 0)
            {
                for (var i = 0; i < 4; i++)
                {
                    this.draw(wireframe, frustum, node.child[i], ext, delta/2.0, tile, Wms);
                }
            }
        }
    }
};<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {};
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      _votes.forEach(vote => {
        Vote.findOpts(vote._id).exec(function(err, opts) {
          if (err) {
            handleError(err);
          } else {
            console.log(opts);
            rs.voteopts.push(opts);
          }
        });
      });
      console.log(opts);
      res.jsonp(rs);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<commit_msg>Commited from lenh at 2017年 6月 21日 水曜日 11:02:51<commit_after>'use strict';

/**
 * Module dependencies.
 */
var path = require('path'),
  mongoose = require('mongoose'),
  Poll = mongoose.model('Poll'),
  Opt = mongoose.model('Opt'),
  Vote = mongoose.model('Vote'),
  Polltag = mongoose.model('Polltag'),
  errorHandler = require(path.resolve('./modules/core/server/controllers/errors.server.controller')),
  _ = require('lodash');

/**
 * Create a Poll
 */
exports.create = function(req, res) {
  var poll = new Poll(req.body);
  poll.user = req.user;

  var tags = req.body.tags;
  var opts = req.body.opts;
  var promises = [];
  poll.save()
    .then(_poll => {
      poll = _poll;
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = _poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        var _opt = new Opt(opt);
        _opt.user = req.user;
        _opt.poll = poll;
        promises.push(_opt.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Show the current Poll
 */
exports.read = function(req, res) {
  // convert mongoose document to JSON
  var poll = req.poll ? req.poll.toJSON() : {};

  // Add a custom field to the Article, for determining if the current User is the "owner".
  // NOTE: This field is NOT persisted to the database, since it doesn't exist in the Article model.
  poll.isCurrentUserOwner = req.user && poll.user && poll.user._id.toString() === req.user._id.toString();
  poll.canEdit = req.user && req.user.roles && req.user.roles.length && req.user.roles.indexOf('admin') > -1;

  res.jsonp(poll);
};

/**
 * Update a Poll
 */
exports.update = function(req, res) {
  var poll = req.poll;
  poll = _.extend(poll, req.body);
  var tags = req.body.tags || [];
  var opts = req.body.opts || [];
  var promises = [];
  poll.save()
    .then(_poll => {
      return Polltag.remove({ poll: _poll._id });
    }, handleError)
    .then(() => {
      tags.forEach((tag) => {
        var polltag = new Polltag();
        polltag.tag = tag;
        polltag.poll = poll;
        promises.push(polltag.save());
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      opts.forEach((opt) => {
        if (opt._id) {
          promises.push(() => {
            Opt.findById(opt._id).exec((err, _opt) => {
              _opt = _.extend(_opt, opt);
              return _opt.save();
            });
          });
        } else {
          var _opt = new Opt(opt);
          _opt.user = req.user;
          _opt.poll = poll;
          promises.push(_opt.save());
        }
      });
      return Promise.all(promises);
    }, handleError)
    .then(() => {
      promises = [];
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Delete an Poll
 */
exports.delete = function(req, res) {
  var poll = req.poll;
  poll.remove()
    .then(() => {
      return Opt.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      return Vote.remove({ poll: poll._id });
    }, handleError)
    .then(() => {
      res.jsonp(poll);
    }, handleError);

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * List of Polls
 */
exports.list = function(req, res) {
  Poll.find().sort('-created').populate('user', 'displayName').exec(function(err, polls) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polls);
    }
  });
};

/**
 * List of Opts in poll
 */
exports.findOpts = function(req, res) {
  Poll.findOpts(req.poll._id).populate('user', 'displayName').exec(function(err, opts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(opts);
    }
  });
};

/**
 * List of Cmts in poll
 */
exports.findCmts = function(req, res) {
  Poll.findCmts(req.poll._id).populate('user', 'displayName profileImageURL').exec(function(err, cmts) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(cmts);
    }
  });
};

/**
 * List of Tags in poll
 */
exports.findTags = function(req, res) {
  Poll.findTags(req.poll._id).populate('tag').exec(function(err, polltags) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(polltags);
    }
  });
};

/**
 * List of Votes in poll
 */
exports.findVotes = function(req, res) {
  Poll.findVotes(req.poll._id).exec(function(err, votes) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(votes);
    }
  });
};

/**
 * Vote in poll of user
 */
exports.findOwnerVote = function(req, res) {
  var condition = {};
  condition.poll = req.poll._id;
  if (req.user) {
    condition.user = req.user._id;
    condition.guest = false;
  } else {
    condition.ip = req.headers["X-Forwarded-For"] || req.headers["x-forwarded-for"] || req.client.remoteAddress;
    condition.guest = true;
  }
  Poll.findOwnerVote(condition).exec(function(err, vote) {
    if (err) {
      return res.status(400).send({
        message: errorHandler.getErrorMessage(err)
      });
    } else {
      res.jsonp(vote);
    }
  });
};

/**
 * Get all info of vote in poll
 */
exports.findVoteopts = function(req, res) {
  var rs = {};
  Poll.findVotes(req.poll._id).exec(function(err, _votes) {
    if (err) {
      handleError(err);
    } else {
      rs.votes = _votes;
      rs.voteopts = [];
      _votes.forEach(vote => {
        Vote.findOpts(vote._id).exec(function(err, opts) {
          if (err) {
            handleError(err);
          } else {
            console.log(opts);
            rs.voteopts.push(opts);
          }
        });
      });
      console.log(rs);
      res.jsonp(rs);
    }
  });

  function handleError(err) {
    return res.status(400).send({
      message: errorHandler.getErrorMessage(err)
    });
  }
};

/**
 * Poll middleware
 */
exports.pollByID = function(req, res, next, id) {

  if (!mongoose.Types.ObjectId.isValid(id)) {
    return res.status(400).send({
      message: 'Poll is invalid'
    });
  }

  Poll.findById(id).populate('user', 'displayName profileImageURL').exec(function(err, poll) {
    if (err) {
      return next(err);
    } else if (!poll) {
      return res.status(404).send({
        message: 'No Poll with that identifier has been found'
      });
    }
    req.poll = poll;
    next();
  });
};
<|endoftext|>


<commit_before>import fs from 'fs-extra'
import { dirname } from 'path'
import { noop } from 'lodash'

import RemoteHandlerAbstract from './abstract'

export default class LocalHandler extends RemoteHandlerAbstract {
  get type() {
    return 'file'
  }

  _getRealPath() {
    return this._remote.path
  }

  _getFilePath(file) {
    return this._getRealPath() + file
  }

  async _sync() {
    const path = this._getRealPath()
    await fs.ensureDir(path)
    await fs.access(path, fs.R_OK | fs.W_OK)

    return this._remote
  }

  async _forget() {
    return noop()
  }

  async _outputFile(file, data, options) {
    const path = this._getFilePath(file)
    await fs.ensureDir(dirname(path))
    await fs.writeFile(path, data, options)
  }

  async _read(file, buffer, position) {
    const needsClose = typeof file === 'string'
    file = needsClose ? await fs.open(this._getFilePath(file), 'r') : file.fd
    try {
      return await fs.read(
        file,
        buffer,
        0,
        buffer.length,
        position === undefined ? null : position
      )
    } finally {
      if (needsClose) {
        await fs.close(file)
      }
    }
  }

  async _readFile(file, options) {
    return fs.readFile(this._getFilePath(file), options)
  }

  async _rename(oldPath, newPath) {
    return fs.rename(this._getFilePath(oldPath), this._getFilePath(newPath))
  }

  async _list(dir = '.') {
    return fs.readdir(this._getFilePath(dir))
  }

  async _createReadStream(file, options) {
    return typeof file === 'string'
      ? fs.createReadStream(this._getFilePath(file), options)
      : fs.createReadStream('', {
          autoClose: false,
          ...options,
          fd: file.fd,
        })
  }

  async _createOutputStream(file, options) {
    if (typeof file === 'string') {
      const path = this._getFilePath(file)
      await fs.ensureDir(dirname(path))
      return fs.createWriteStream(path, options)
    }
    return fs.createWriteStream('', {
      autoClose: false,
      ...options,
      fd: file.fd,
    })
  }

  async _unlink(file) {
    return fs.unlink(this._getFilePath(file)).catch(error => {
      // do not throw if the file did not exist
      if (error == null || error.code !== 'ENOENT') {
        throw error
      }
    })
  }

  async _getSize(file) {
    const stats = await fs.stat(
      this._getFilePath(typeof file === 'string' ? file : file.path)
    )
    return stats.size
  }

  async _openFile(path, flags) {
    return fs.open(this._getFilePath(path), flags)
  }

  async _closeFile(fd) {
    return fs.close(fd)
  }

  async _rmdir(dir) {
    return fs.rmdir(dir)
  }
}
<commit_msg>fix(fs/local#_rmdir): correctly prefix path<commit_after>import fs from 'fs-extra'
import { dirname } from 'path'
import { noop } from 'lodash'

import RemoteHandlerAbstract from './abstract'

export default class LocalHandler extends RemoteHandlerAbstract {
  get type() {
    return 'file'
  }

  _getRealPath() {
    return this._remote.path
  }

  _getFilePath(file) {
    return this._getRealPath() + file
  }

  async _sync() {
    const path = this._getRealPath()
    await fs.ensureDir(path)
    await fs.access(path, fs.R_OK | fs.W_OK)

    return this._remote
  }

  async _forget() {
    return noop()
  }

  async _outputFile(file, data, options) {
    const path = this._getFilePath(file)
    await fs.ensureDir(dirname(path))
    await fs.writeFile(path, data, options)
  }

  async _read(file, buffer, position) {
    const needsClose = typeof file === 'string'
    file = needsClose ? await fs.open(this._getFilePath(file), 'r') : file.fd
    try {
      return await fs.read(
        file,
        buffer,
        0,
        buffer.length,
        position === undefined ? null : position
      )
    } finally {
      if (needsClose) {
        await fs.close(file)
      }
    }
  }

  async _readFile(file, options) {
    return fs.readFile(this._getFilePath(file), options)
  }

  async _rename(oldPath, newPath) {
    return fs.rename(this._getFilePath(oldPath), this._getFilePath(newPath))
  }

  async _list(dir = '.') {
    return fs.readdir(this._getFilePath(dir))
  }

  async _createReadStream(file, options) {
    return typeof file === 'string'
      ? fs.createReadStream(this._getFilePath(file), options)
      : fs.createReadStream('', {
          autoClose: false,
          ...options,
          fd: file.fd,
        })
  }

  async _createOutputStream(file, options) {
    if (typeof file === 'string') {
      const path = this._getFilePath(file)
      await fs.ensureDir(dirname(path))
      return fs.createWriteStream(path, options)
    }
    return fs.createWriteStream('', {
      autoClose: false,
      ...options,
      fd: file.fd,
    })
  }

  async _unlink(file) {
    return fs.unlink(this._getFilePath(file)).catch(error => {
      // do not throw if the file did not exist
      if (error == null || error.code !== 'ENOENT') {
        throw error
      }
    })
  }

  async _getSize(file) {
    const stats = await fs.stat(
      this._getFilePath(typeof file === 'string' ? file : file.path)
    )
    return stats.size
  }

  async _openFile(path, flags) {
    return fs.open(this._getFilePath(path), flags)
  }

  async _closeFile(fd) {
    return fs.close(fd)
  }

  async _rmdir(dir) {
    return fs.rmdir(this._getFilePath(dir))
  }
}
<|endoftext|>


<commit_before>( function( mw, $ ) {"use strict";

	mw.PluginManager.add( 'smartContainer', mw.KBaseComponent.extend({

		defaultConfig: {
			'parent': 'controlsContainer',
			"align": "right",
			'order': 100,
			'width': 220,
			'showTooltip': true,
			'displayImportance': "high",
			'title': "Master Plugin",
			'iconClass': 'icon-cog',
			'config':{}
		},

		menuOpened: false,
		$menu: null,

		setup: function( embedPlayer ) {
			var _this = this;
			if ( $.isEmptyObject(this.getConfig("config")) ){
				this.setConfig( "visible", false ); // remove plugin if no config was specified
				return;
			}
			// hide specified plugins
			var config = this.getConfig('config');
			config.plugins.forEach(function (plugin, index) {
				_this.embedPlayer.setKalturaConfig( plugin.pluginName, "visible", false );
			});

			this.getMenu(); // create menu
		},
		getComponent: function() {
			var _this = this;
			if( !this.$el ) {
				this.$el = $( '<button />' )
					.attr( 'title', this.getConfig('title') )
					.addClass( this.getConfig('iconClass') + " btn " + this.getCssClass() )
					.click( function(e) {
						_this.toggleMenu( e.clientX ); // pass the mouse pointer x position to set the menu position
					});
			}
			return this.$el;
		},
		addBindings: function() {
			var _this = this;
		},
		toggleMenu: function(x) {
			if ( this.isDisabled ){return};
			if ( this.menuOpened ){
				this.closeMenu();
			}else{
				this.openMenu(x);
			}
		},

		openMenu: function(x){
			// set menu position
			var rightPosition = this.embedPlayer.getVideoHolder().width() - x - 20; // set right position for the menu according to the mouse click x position
			var bottomPosition = 0; // set the menu bottom to the video holder bottom
			if  ( this.embedPlayer.getKalturaConfig( "controlBarContainer", "hover" ) === true ){
				bottomPosition = this.embedPlayer.getInterface().find(".controlsContainer").height(); // for hovering controls, update the menu bottom to the controls bar height
			}
			this.getMenu().css({"bottom": bottomPosition, "right": rightPosition}).show();
			this.menuOpened = true;
			this.getPlayer().triggerHelper( 'onDisableKeyboardBinding' );
		},

		closeMenu: function(){
			this.getMenu().hide();
			this.menuOpened = false;
			this.getPlayer().triggerHelper( 'onEnableKeyboardBinding' );
		},

		getMenu: function(){
			if ( !this.$menu ){
				var _this = this;
				// add menu DIV
				this.$menu = $('

').width(this.getConfig("width"));
				var config = this.getConfig('config');

				// set menu height
				var menuHeight = this.calculateMenuHeight(config);
				if ( menuHeight > this.embedPlayer.getVideoHolder().height() - 20 ){
					this.$menu.height(this.embedPlayer.getVideoHolder().height() - 20);
					this.$menu.css("overflow-y","scroll");
				}else{
					this.$menu.height(this.calculateMenuHeight(config));
				}
				this.$menu.close = function(){
					_this.closeMenu();
				}
				// render menu
				this.renderMenu(config);
				this.embedPlayer.getVideoHolder().append( this.$menu.hide());

			}
			return this.$menu;
		},

		calculateMenuHeight: function(config){
			var menuHeight = 50 + config.plugins.length * 40; // give each plugin header 40 px and 50px for the title
			config.plugins.forEach(function (plugin, index) {
				menuHeight += plugin.properties.length * 30; // give each plugin property 30 px
			});
			return menuHeight;
		},

		renderMenu: function(config){
			var _this = this;
			this.$menu.append('
' + this.getConfig("title") + '
');
			config.plugins.forEach(function (plugin, index) {
				_this.$menu.append('
' + plugin.displayName + '
');
				plugin.properties.forEach(function (property, index) {
					var initialValue = _this.embedPlayer.getKalturaConfig( plugin.pluginName, property.property );
					switch (property.type){
						case 'boolean':
							var propField = $('<input class="pluginProperty pluginPropertyLabel checkbox" type="checkbox">')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).is(":checked") );
								});
							if ( initialValue !== undefined ){
								propField.prop( "checked", initialValue ); // set checkbox value according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									propField.prop( "checked", data.value ); // set checkbox value according to value passed on the updatePropertyEvent event
								}
							});
							var wrapper = $('
' + property.label + '
');
							_this.$menu.append(wrapper.find("label").prepend(propField));
							break;
						case 'enum':
							var propField = $('<select class="pluginProperty pluginPropertyLabel"></select>')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).get(0).selectedIndex );
								});
							var addOptions = function(items){
								$.each(items, function (i, item) {
									propField.append($('<option>', {
										value: item.value,
										text : item.label
									}));
								});
							}
							if ( initialValue !== undefined && initialValue.length ){
								addOptions( initialValue ); // set combobox options according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									addOptions(data.items); // set combobox options according to value passed on the updatePropertyEvent event
									if ( data.selectedItem ){
										propField.val(data.selectedItem); // support selected item change
									}
								}
							});
							var elm = $("

").append('' + property.label + '').append(propField);
							_this.$menu.append(elm);
							break;
						case 'string':
						case 'number':
						case 'float':
							var propField = $('<input class="pluginProperty pluginPropertyLabel" type="text"/>')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).val() )
								});
							if ( initialValue !== undefined ){
								propField.val( initialValue ); // set field value according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									propField.val( data.value ); // set field value according to value passed on the updatePropertyEvent event
								}
							});
							var elm = $("

").append('' + property.label + '').append(propField);
							_this.$menu.append(elm);
							break;
						default:
							break;
					}
				});
			});
			this.$menu.find(".pluginProperty").not(".checkbox").width(this.getConfig("width")-70);
		},

		propertyChanged: function(plugin, property, type, value){
			if (type == "number"){
				value = parseInt(value);
			}
			if (type == "float"){
				value = parseFloat(value);
			}
			this.embedPlayer.triggerHelper("propertyChangedEvent",{"plugin": plugin, "property": property, "value": value})
		}
	}));

} )( window.mw, window.jQuery );<commit_msg>updated title<commit_after>( function( mw, $ ) {"use strict";

	mw.PluginManager.add( 'smartContainer', mw.KBaseComponent.extend({

		defaultConfig: {
			'parent': 'controlsContainer',
			"align": "right",
			'order': 100,
			'width': 220,
			'showTooltip': true,
			'displayImportance': "high",
			'title': "Smart Container",
			'iconClass': 'icon-cog',
			'config':{}
		},

		menuOpened: false,
		$menu: null,

		setup: function( embedPlayer ) {
			var _this = this;
			if ( $.isEmptyObject(this.getConfig("config")) ){
				this.setConfig( "visible", false ); // remove plugin if no config was specified
				return;
			}
			// hide specified plugins
			var config = this.getConfig('config');
			config.plugins.forEach(function (plugin, index) {
				_this.embedPlayer.setKalturaConfig( plugin.pluginName, "visible", false );
			});

			this.getMenu(); // create menu
		},
		getComponent: function() {
			var _this = this;
			if( !this.$el ) {
				this.$el = $( '<button />' )
					.attr( 'title', this.getConfig('title') )
					.addClass( this.getConfig('iconClass') + " btn " + this.getCssClass() )
					.click( function(e) {
						_this.toggleMenu( e.clientX ); // pass the mouse pointer x position to set the menu position
					});
			}
			return this.$el;
		},
		addBindings: function() {
			var _this = this;
		},
		toggleMenu: function(x) {
			if ( this.isDisabled ){return};
			if ( this.menuOpened ){
				this.closeMenu();
			}else{
				this.openMenu(x);
			}
		},

		openMenu: function(x){
			// set menu position
			var rightPosition = this.embedPlayer.getVideoHolder().width() - x - 20; // set right position for the menu according to the mouse click x position
			var bottomPosition = 0; // set the menu bottom to the video holder bottom
			if  ( this.embedPlayer.getKalturaConfig( "controlBarContainer", "hover" ) === true ){
				bottomPosition = this.embedPlayer.getInterface().find(".controlsContainer").height(); // for hovering controls, update the menu bottom to the controls bar height
			}
			this.getMenu().css({"bottom": bottomPosition, "right": rightPosition}).show();
			this.menuOpened = true;
			this.getPlayer().triggerHelper( 'onDisableKeyboardBinding' );
		},

		closeMenu: function(){
			this.getMenu().hide();
			this.menuOpened = false;
			this.getPlayer().triggerHelper( 'onEnableKeyboardBinding' );
		},

		getMenu: function(){
			if ( !this.$menu ){
				var _this = this;
				// add menu DIV
				this.$menu = $('

').width(this.getConfig("width"));
				var config = this.getConfig('config');

				// set menu height
				var menuHeight = this.calculateMenuHeight(config);
				if ( menuHeight > this.embedPlayer.getVideoHolder().height() - 20 ){
					this.$menu.height(this.embedPlayer.getVideoHolder().height() - 20);
					this.$menu.css("overflow-y","scroll");
				}else{
					this.$menu.height(this.calculateMenuHeight(config));
				}
				this.$menu.close = function(){
					_this.closeMenu();
				}
				// render menu
				this.renderMenu(config);
				this.embedPlayer.getVideoHolder().append( this.$menu.hide());

			}
			return this.$menu;
		},

		calculateMenuHeight: function(config){
			var menuHeight = 50 + config.plugins.length * 40; // give each plugin header 40 px and 50px for the title
			config.plugins.forEach(function (plugin, index) {
				menuHeight += plugin.properties.length * 30; // give each plugin property 30 px
			});
			return menuHeight;
		},

		renderMenu: function(config){
			var _this = this;
			this.$menu.append('
' + this.getConfig("title") + '
');
			config.plugins.forEach(function (plugin, index) {
				_this.$menu.append('
' + plugin.displayName + '
');
				plugin.properties.forEach(function (property, index) {
					var initialValue = _this.embedPlayer.getKalturaConfig( plugin.pluginName, property.property );
					switch (property.type){
						case 'boolean':
							var propField = $('<input class="pluginProperty pluginPropertyLabel checkbox" type="checkbox">')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).is(":checked") );
								});
							if ( initialValue !== undefined ){
								propField.prop( "checked", initialValue ); // set checkbox value according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									propField.prop( "checked", data.value ); // set checkbox value according to value passed on the updatePropertyEvent event
								}
							});
							var wrapper = $('
' + property.label + '
');
							_this.$menu.append(wrapper.find("label").prepend(propField));
							break;
						case 'enum':
							var propField = $('<select class="pluginProperty pluginPropertyLabel"></select>')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).get(0).selectedIndex );
								});
							var addOptions = function(items){
								$.each(items, function (i, item) {
									propField.append($('<option>', {
										value: item.value,
										text : item.label
									}));
								});
							}
							if ( initialValue !== undefined && initialValue.length ){
								addOptions( initialValue ); // set combobox options according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									addOptions(data.items); // set combobox options according to value passed on the updatePropertyEvent event
									if ( data.selectedItem ){
										propField.val(data.selectedItem); // support selected item change
									}
								}
							});
							var elm = $("

").append('' + property.label + '').append(propField);
							_this.$menu.append(elm);
							break;
						case 'string':
						case 'number':
						case 'float':
							var propField = $('<input class="pluginProperty pluginPropertyLabel" type="text"/>')
								.on("change", function(){
									_this.propertyChanged(plugin.pluginName, property.property, property.type, $(this).val() )
								});
							if ( initialValue !== undefined ){
								propField.val( initialValue ); // set field value according to property value
							}
							_this.embedPlayer.bindHelper( "updatePropertyEvent", function(e, data){
								if ( data.plugin === plugin.pluginName && data.property === property.property){
									propField.val( data.value ); // set field value according to value passed on the updatePropertyEvent event
								}
							});
							var elm = $("

").append('' + property.label + '').append(propField);
							_this.$menu.append(elm);
							break;
						default:
							break;
					}
				});
			});
			this.$menu.find(".pluginProperty").not(".checkbox").width(this.getConfig("width")-70);
		},

		propertyChanged: function(plugin, property, type, value){
			if (type == "number"){
				value = parseInt(value);
			}
			if (type == "float"){
				value = parseFloat(value);
			}
			this.embedPlayer.triggerHelper("propertyChangedEvent",{"plugin": plugin, "property": property, "value": value})
		}
	}));

} )( window.mw, window.jQuery );<|endoftext|>


<commit_before>"use strict";

var assert = require('assert');

var MovesEnum = {
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3
};

// Canned fisher yates shuffle from bost.ocks.org/mike/shuffle
var shuffle = function(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle
  while (m) {

    // Pick a remaining element
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
};

var fillGrid = function(size, fill, isBlank) {
  var grid = [];
  for (var i=0;i<size;++i) {
    var row = [];
    for (var j=0;j<size;++j) {
      if (isBlank(i,j)) {
        row.push('*');
      } else {
        row.push(fill(i,j));
      }
    }
    grid.push(row);
  }
  return grid;
};

var createElementsOfGrid = function(size) {
  var elements = [];
  for (var i=1;i<size*size;++i) {
    elements.push(i);
  }
  return elements;
};

var MagicSquare = function(size) {

  var isBlank = function(x,y) { return x === (size-1) && y === (size-1); };

  var elements = createElementsOfGrid(size);
  var fill = function(x,y) { var n = elements.shift(); return n; };

  var grid = fillGrid(size, fill, isBlank);

  var onNearEdge = function(i) { return (i === size-1); };
  var onFarEdge =  function(i) { return i === 0; };

  var findBlank = function() {
    for (var i=0;i<size;++i) {
      for (var j=0;j<size;++j) {
        if (grid[i][j] === '*') {
          return { x: i, y: j };
        }
      }
    }
  };

  return {

    display: function() {
      var s = '';
      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          s += grid[i][j];
        }
        s+='\n';
      }
      return s;
    },

    makeMove: function(move) {
      var blankPos = findBlank();

      switch (move) {
        case MovesEnum.UP:
          swap(blankPos, { x: blankPos.x, y: blankPos.y - 1});
          break;
        case MovesEnum.DOWN:
          swap(blankPos, { x: blankPos.x, y: blankPos.y + 1});
          break;
        case MovesEnum.LEFT:
        case MovesEnum.RIGHT:
      }
    },

    shuffle: function() {
      var blankX = (Math.random() * size)|0;
      var blankY = (Math.random() * size)|0;

      var isBlank = function(x,y) { return x === blankX && y === blankY; };
      shuffle(elements);

      grid = fillGrid(size, fill, isBlank);
    },

    solved: function() {
      var counter = 1;
      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          if (i === (size-1) && j === (size-1)) {
            return grid[i][j] === '*';
          }
          if (grid[i][j] !== counter) {
            return false;
          }
          counter++;
        }
      }
      return true;
    },

    validMoves: function() {
      var validMoves = [];

      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          if (grid[i][j] === '*') {
            if (onFarEdge(j)) {
              validMoves.push(MovesEnum.UP);
            }

            if (onNearEdge(j)) {
              validMoves.push(MovesEnum.DOWN);
            }

            if (onNearEdge(i)) {
              validMoves.push(MovesEnum.LEFT);
            }

            if (onFarEdge(i)) {
              validMoves.push(MovesEnum.RIGHT);
            }
            break;
          }
        }
      }
      return validMoves;
    }
  };
};

describe('magic square', function() {
  it('exists', function() {
    assert(new MagicSquare(3));
  });

  it('can be shuffled', function() {
    assert(new MagicSquare(3).shuffle);
  });

  it('can be display', function() {
    assert.equal('123\n456\n78*\n',new MagicSquare(3).display());
  });

  it('is solved without shuffling', function() {
    var square = new MagicSquare(3);
    assert(square.solved());
  });

  it('is not solved after shuffling', function() {
    var square = new MagicSquare(3);

    // Small chance the shuffle could magically come back?
    square.shuffle();
    assert(!square.solved());
  });

  it('can define valid moves', function() {
    var sq = new MagicSquare(3);

    assert.equal(2, sq.validMoves().length);
  });

  it('moves make sense', function() {
    var sq = new MagicSquare(3);

    assert(sq.validMoves().indexOf(MovesEnum.UP) !== -1);
    assert(sq.validMoves().indexOf(MovesEnum.RIGHT) !== -1);
  });

  it('can make a move', function() {
    var sq = new MagicSquare(3);
    sq.makeMove(MovesEnum.UP);
    assert.equal('123\n45*\n786\n', sq.display());
  });
});<commit_msg>woo, move works<commit_after>"use strict";

var assert = require('assert');

var MovesEnum = {
  Up: 0,
  Down: 1,
  Left: 2,
  Right: 3
};

// Canned fisher yates shuffle from bost.ocks.org/mike/shuffle
var shuffle = function(array) {
  var m = array.length, t, i;

  // While there remain elements to shuffle
  while (m) {

    // Pick a remaining element
    i = Math.floor(Math.random() * m--);

    // And swap it with the current element.
    t = array[m];
    array[m] = array[i];
    array[i] = t;
  }

  return array;
};

var fillGrid = function(size, fill, isBlank) {
  var grid = [];
  for (var i=0;i<size;++i) {
    var row = [];
    for (var j=0;j<size;++j) {
      if (isBlank(i,j)) {
        row.push('*');
      } else {
        row.push(fill(i,j));
      }
    }
    grid.push(row);
  }
  return grid;
};

var createElementsOfGrid = function(size) {
  var elements = [];
  for (var i=1;i<size*size;++i) {
    elements.push(i);
  }
  return elements;
};

var MagicSquare = function(size) {

  var isBlank = function(x,y) { return x === (size-1) && y === (size-1); };

  var elements = createElementsOfGrid(size);
  var fill = function(x,y) { var n = elements.shift(); return n; };

  var grid = fillGrid(size, fill, isBlank);

  var onNearEdge = function(i) { return (i === size-1); };
  var onFarEdge =  function(i) { return i === 0; };

  var findBlank = function() {
    for (var i=0;i<size;++i) {
      for (var j=0;j<size;++j) {
        if (grid[i][j] === '*') {
          return { x: j, y: i };
        }
      }
    }
  };

  return {

    display: function() {
      var s = '';
      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          s += grid[i][j];
        }
        s+='\n';
      }
      return s;
    },

    makeMove: function(move) {
      var blankPos = findBlank();

      switch (move) {
        case MovesEnum.UP:
          this.swap(blankPos, { x: blankPos.x, y: blankPos.y - 1});
          break;
        case MovesEnum.DOWN:
          this.swap(blankPos, { x: blankPos.x, y: blankPos.y + 1});
          break;
        case MovesEnum.LEFT:
        case MovesEnum.RIGHT:
      }
    },

    shuffle: function() {
      var blankX = (Math.random() * size)|0;
      var blankY = (Math.random() * size)|0;

      var isBlank = function(x,y) { return x === blankX && y === blankY; };
      shuffle(elements);

      grid = fillGrid(size, fill, isBlank);
    },

    solved: function() {
      var counter = 1;
      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          if (i === (size-1) && j === (size-1)) {
            return grid[i][j] === '*';
          }
          if (grid[i][j] !== counter) {
            return false;
          }
          counter++;
        }
      }
      return true;
    },

    swap: function(p, q) {
      var temp = grid[p.y][p.x];
      grid[p.y][p.x] = grid[q.y][q.x];
      grid[q.y][q.x] = temp;
    },

    validMoves: function() {
      var validMoves = [];

      for (var i=0;i<size;++i) {
        for (var j=0;j<size;++j) {
          if (grid[i][j] === '*') {
            if (onFarEdge(j)) {
              validMoves.push(MovesEnum.UP);
            }

            if (onNearEdge(j)) {
              validMoves.push(MovesEnum.DOWN);
            }

            if (onNearEdge(i)) {
              validMoves.push(MovesEnum.LEFT);
            }

            if (onFarEdge(i)) {
              validMoves.push(MovesEnum.RIGHT);
            }
            break;
          }
        }
      }
      return validMoves;
    }
  };
};

describe('magic square', function() {
  it('exists', function() {
    assert(new MagicSquare(3));
  });

  it('can be shuffled', function() {
    assert(new MagicSquare(3).shuffle);
  });

  it('can be display', function() {
    assert.equal('123\n456\n78*\n',new MagicSquare(3).display());
  });

  it('is solved without shuffling', function() {
    var square = new MagicSquare(3);
    assert(square.solved());
  });

  it('is not solved after shuffling', function() {
    var square = new MagicSquare(3);

    // Small chance the shuffle could magically come back?
    square.shuffle();
    assert(!square.solved());
  });

  it('can define valid moves', function() {
    var sq = new MagicSquare(3);

    assert.equal(2, sq.validMoves().length);
  });

  it('moves make sense', function() {
    var sq = new MagicSquare(3);

    assert(sq.validMoves().indexOf(MovesEnum.UP) !== -1);
    assert(sq.validMoves().indexOf(MovesEnum.RIGHT) !== -1);
  });

  it('can make a move', function() {
    var sq = new MagicSquare(3);
    sq.makeMove(MovesEnum.UP);
    assert.equal('123\n45*\n786\n', sq.display());
  });
});<|endoftext|>


<commit_before>/*
This module contains functions for:

	- structure comparison
	- array manipulation
	- object caching
	- data acquisition
*/

CT.data = {
	map: {},

	// data comparison
	"sameList": function(list1, list2) {
		if (list1.length != list2.length)
			return false;
		for (var i = 0; i < list1.length; i++) {
			if (list1[i] != list2[i])
				return false;
		}
		return true;
	},
	"copyList": function(oldlist) {
		var newlist = [];
		for (var i = 0; i < oldlist.length; i++)
			newlist.push(oldlist[i]);
		return newlist;
	},
	"diff": function(dold, dnew, required, compdicts, submap, complists) {
		var ddiff = required || {};
		compdicts = compdicts || [];
		complists = complists || [];
		submap = submap || {};
		for (var k in dnew) {
			if (compdicts.indexOf(k) != -1) {
				for (var j in dnew[k]) {
					if (dnew[k][j] != dold[k][j]) {
						ddiff[k] = dnew[k];
						break;
					}
				}
			}
			else if (complists.indexOf(k) != -1) {
				if (!CT.data.sameList(dnew[k], dold[k]))
					ddiff[k] = dnew[k];
			}
			else if (k in submap) {
				if (dnew[k] != dold[k][submap[k]])
					ddiff[k] = dnew[k];
			}
			else if (dnew[k] != dold[k])
				ddiff[k] = dnew[k];
		}
		return ddiff;
	},

	// array stuff
	"append": function(arr, el) {
		if (arr.indexOf(el) == -1)
			arr.push(el);
	},
	"remove": function(arr, el) {
		var elindex = arr.indexOf(el);
		if (elindex != -1)
			return arr.splice(elindex, 1);
	},
	"sum": function(arr) {
		return arr.length ? arr.reduce(function(a, b) {
			if (Array.isArray(a)) {
				return a.map(function(v, i) {
					return v + b[i];
				});
			}
			return a + b;
		}) : arr;
	},
	"alpha": function(arr, prop) {
		return arr.sort(function(a, b) {
			if (prop) {
				a = a[prop];
				b = b[prop];
			}
			return (a < b) ? -1 : (a > b) ? 1 : 0;
		});
	},

	// cache
	"has": function(key) {
		return !!CT.data.map[key];
	},
	"get": function(key) {
		return CT.data.map[key];
	},
	"add": function(d) {
		if (CT.data.map[d.key]) {
			for (var k in d)
				CT.data.map[d.key][k] = d[k];
		}
		else
			CT.data.map[d.key] = d;
	},
	"addSet": function(dlist) {
		for (var i = 0; i < dlist.length; i++)
			CT.data.add(dlist[i]);
	},
	"getSet": function(klist) {
		return klist.map(CT.data.get);
	},
	"uniquify": function(items, exceptions) {
		exceptions = exceptions || [];
		items = CT.data.copyList(items); // preserve original list!!
		items.sort();
		var newitems = [];
		var latestitem = "";
		for (var i = 0; i < items.length; i++) {
			if (items[i] != latestitem && exceptions.indexOf(items[i]) == -1) {
				latestitem = items[i];
				newitems.push(latestitem);
			}
		}
		return newitems;
	},

	// cheap trick
	"copy": function(str) {
		var f = CT.dom.field(null, str, "transparent");
		document.body.appendChild(f);
		f.select();
		if (document.execCommand('copy')) {
			alert("Link saved to clipboard. Great!");
			f.remove();
		} else {
			f.className = "";
			CT.modal.modal(CT.dom.div([
				"Ctr-C to Copy URL", f
			], "centered"));
			setTimeout(function() { // wait a tick for modal
				f.select();
			});
		}
	},

	// random stuff
	"numstr": function(len) {
		var s = "", chunk;
		while (len) {
			chunk = Math.min(len, 16);
			s += "" + CT.data.random(Math.pow(10, chunk));
			len -= chunk;
		}
		return s;
	},
	"random": function(max, noRound) {
		var r = Math.random() * max;
		return noRound ? r : Math.floor(r);
	},
	"choice": function(arr) {
		return arr[CT.data.random(arr.length)];
	},

	// data acquisition functions -- require backend integration
	"checkAndDo": function(keys, cb, nlcb, eb, req, getpath, getparams) {
		var needed = [];
		keys = CT.data.uniquify(keys);
		for (var i = 0; i < keys.length; i++) {
			if (CT.data.map[keys[i]] == null || req && CT.data.map[keys[i]][req] == null)
				needed.push(keys[i]);
		}
		if (needed.length == 0)
			return cb();
		getparams = getparams || {"gtype": "data"};
		getparams.keys = needed;
		CT.net.post(getpath || "/get", getparams,
		"error retrieving data", function(rawdata) {
			CT.data.addSet(rawdata);
			if (nlcb) nlcb(needed);
			cb();
		}, eb);
	},
	"requirePrep": function() {}, // override!
	"itemReady": function(key, plist) {
		var isready = key in CT.data.map;
		plist && plist.forEach(function(p) {
			isready = isready && p in CT.data.map[key];
		});
		return isready;
	},
	"require": function(key, cb, plist, getpath, getparams, getprop) {
		CT.data.requirePrep(key);
		if (CT.data.itemReady(key, plist))
			cb(CT.data.get(key));
		else {
			getparams = getparams || {"gtype": "user", "chat": 1};
			getparams[getprop || "uid"] = key;
			CT.net.post(getpath || "/get", getparams,
				"error retrieving data", function(rawdata) {
					CT.data.add(rawdata);
					cb(CT.data.get(key));
				});
		}
	},
	"requireAll": function(keys, cb, uid, plist, getpath, getparams, getprop) {
		keys.forEach(CT.data.requirePrep);
		var needed = [];
		for (var i = 0; i < keys.length; i++) {
			if (!CT.data.itemReady(keys[i], plist))
				needed.push(keys[i]);
		}
		if (needed.length == 0)
			cb(keys);
		else {
			getparams = getparams || {"gtype": "user", "chat": 1};
			getparams[getprop || "uids"] = needed;
			CT.net.post(getpath || "/get", getparams,
				"error retrieving data", function(rawdata) {
					CT.data.addSet(rawdata);
					cb(keys);
				});
		}
	}
};<commit_msg>CT.data.random(): no args = coin flip<commit_after>/*
This module contains functions for:

	- structure comparison
	- array manipulation
	- object caching
	- data acquisition
*/

CT.data = {
	map: {},

	// data comparison
	"sameList": function(list1, list2) {
		if (list1.length != list2.length)
			return false;
		for (var i = 0; i < list1.length; i++) {
			if (list1[i] != list2[i])
				return false;
		}
		return true;
	},
	"copyList": function(oldlist) {
		var newlist = [];
		for (var i = 0; i < oldlist.length; i++)
			newlist.push(oldlist[i]);
		return newlist;
	},
	"diff": function(dold, dnew, required, compdicts, submap, complists) {
		var ddiff = required || {};
		compdicts = compdicts || [];
		complists = complists || [];
		submap = submap || {};
		for (var k in dnew) {
			if (compdicts.indexOf(k) != -1) {
				for (var j in dnew[k]) {
					if (dnew[k][j] != dold[k][j]) {
						ddiff[k] = dnew[k];
						break;
					}
				}
			}
			else if (complists.indexOf(k) != -1) {
				if (!CT.data.sameList(dnew[k], dold[k]))
					ddiff[k] = dnew[k];
			}
			else if (k in submap) {
				if (dnew[k] != dold[k][submap[k]])
					ddiff[k] = dnew[k];
			}
			else if (dnew[k] != dold[k])
				ddiff[k] = dnew[k];
		}
		return ddiff;
	},

	// array stuff
	"append": function(arr, el) {
		if (arr.indexOf(el) == -1)
			arr.push(el);
	},
	"remove": function(arr, el) {
		var elindex = arr.indexOf(el);
		if (elindex != -1)
			return arr.splice(elindex, 1);
	},
	"sum": function(arr) {
		return arr.length ? arr.reduce(function(a, b) {
			if (Array.isArray(a)) {
				return a.map(function(v, i) {
					return v + b[i];
				});
			}
			return a + b;
		}) : arr;
	},
	"alpha": function(arr, prop) {
		return arr.sort(function(a, b) {
			if (prop) {
				a = a[prop];
				b = b[prop];
			}
			return (a < b) ? -1 : (a > b) ? 1 : 0;
		});
	},

	// cache
	"has": function(key) {
		return !!CT.data.map[key];
	},
	"get": function(key) {
		return CT.data.map[key];
	},
	"add": function(d) {
		if (CT.data.map[d.key]) {
			for (var k in d)
				CT.data.map[d.key][k] = d[k];
		}
		else
			CT.data.map[d.key] = d;
	},
	"addSet": function(dlist) {
		for (var i = 0; i < dlist.length; i++)
			CT.data.add(dlist[i]);
	},
	"getSet": function(klist) {
		return klist.map(CT.data.get);
	},
	"uniquify": function(items, exceptions) {
		exceptions = exceptions || [];
		items = CT.data.copyList(items); // preserve original list!!
		items.sort();
		var newitems = [];
		var latestitem = "";
		for (var i = 0; i < items.length; i++) {
			if (items[i] != latestitem && exceptions.indexOf(items[i]) == -1) {
				latestitem = items[i];
				newitems.push(latestitem);
			}
		}
		return newitems;
	},

	// cheap trick
	"copy": function(str) {
		var f = CT.dom.field(null, str, "transparent");
		document.body.appendChild(f);
		f.select();
		if (document.execCommand('copy')) {
			alert("Link saved to clipboard. Great!");
			f.remove();
		} else {
			f.className = "";
			CT.modal.modal(CT.dom.div([
				"Ctr-C to Copy URL", f
			], "centered"));
			setTimeout(function() { // wait a tick for modal
				f.select();
			});
		}
	},

	// random stuff
	"numstr": function(len) {
		var s = "", chunk;
		while (len) {
			chunk = Math.min(len, 16);
			s += "" + CT.data.random(Math.pow(10, chunk));
			len -= chunk;
		}
		return s;
	},
	"random": function(max, noRound) {
		var r = Math.random() * (max || 2);
		return noRound ? r : Math.floor(r);
	},
	"choice": function(arr) {
		return arr[CT.data.random(arr.length)];
	},

	// data acquisition functions -- require backend integration
	"checkAndDo": function(keys, cb, nlcb, eb, req, getpath, getparams) {
		var needed = [];
		keys = CT.data.uniquify(keys);
		for (var i = 0; i < keys.length; i++) {
			if (CT.data.map[keys[i]] == null || req && CT.data.map[keys[i]][req] == null)
				needed.push(keys[i]);
		}
		if (needed.length == 0)
			return cb();
		getparams = getparams || {"gtype": "data"};
		getparams.keys = needed;
		CT.net.post(getpath || "/get", getparams,
		"error retrieving data", function(rawdata) {
			CT.data.addSet(rawdata);
			if (nlcb) nlcb(needed);
			cb();
		}, eb);
	},
	"requirePrep": function() {}, // override!
	"itemReady": function(key, plist) {
		var isready = key in CT.data.map;
		plist && plist.forEach(function(p) {
			isready = isready && p in CT.data.map[key];
		});
		return isready;
	},
	"require": function(key, cb, plist, getpath, getparams, getprop) {
		CT.data.requirePrep(key);
		if (CT.data.itemReady(key, plist))
			cb(CT.data.get(key));
		else {
			getparams = getparams || {"gtype": "user", "chat": 1};
			getparams[getprop || "uid"] = key;
			CT.net.post(getpath || "/get", getparams,
				"error retrieving data", function(rawdata) {
					CT.data.add(rawdata);
					cb(CT.data.get(key));
				});
		}
	},
	"requireAll": function(keys, cb, uid, plist, getpath, getparams, getprop) {
		keys.forEach(CT.data.requirePrep);
		var needed = [];
		for (var i = 0; i < keys.length; i++) {
			if (!CT.data.itemReady(keys[i], plist))
				needed.push(keys[i]);
		}
		if (needed.length == 0)
			cb(keys);
		else {
			getparams = getparams || {"gtype": "user", "chat": 1};
			getparams[getprop || "uids"] = needed;
			CT.net.post(getpath || "/get", getparams,
				"error retrieving data", function(rawdata) {
					CT.data.addSet(rawdata);
					cb(keys);
				});
		}
	}
};<|endoftext|>


<commit_before>import React from 'react';
import { connect } from 'react-redux';
import Seguidor from './Seguidor';

const mapStateToProps = (state) => {
  return {
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
  }
}

const Seguidor = connect(
  mapStateToProps,
  mapDispatchToProps
)(Seguidor)

export default Seguidor;
<commit_msg>Container.<commit_after>import React from 'react';
import { connect } from 'react-redux';
import Seguidor from './Seguidor';

const mapStateToProps = (state) => {
  return {
  }
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
  }
}

const SeguidorContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(Seguidor)

export default SeguidorContainer;
<|endoftext|>


<commit_before>import React from 'react';
import {StyleSheet, Text, View, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';

var Page = () => (
    <NavigationContext.Consumer>
        {({stateNavigator}) => (
            <View style={styles.container}>
                <Text style={styles.text}>
                    {`Scene ${stateNavigator.stateContext.crumbs.length}`}
                </Text>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#fff"
                    onPress={() => stateNavigator.navigate('scene')}>
                    <Text>Next</Text>
                </TouchableHighlight>
            </View>
        )}
    </NavigationContext.Consumer>
);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    button: {
        alignItems: 'center',
        backgroundColor: '#DDDDDD',
        padding: 10
    },
    text: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
});

export default Page;<commit_msg>Added navigation back button<commit_after>import React from 'react';
import {StyleSheet, Text, View, TouchableHighlight} from 'react-native';
import {NavigationContext} from 'navigation-react';

var Page = () => (
    <NavigationContext.Consumer>
        {({stateNavigator}) => (
            <View style={styles.container}>
                <Text style={styles.text}>
                    {`Scene ${stateNavigator.stateContext.crumbs.length}`}
                </Text>
                <TouchableHighlight
                    style={styles.button}
                    underlayColor="#fff"
                    onPress={() => stateNavigator.navigate('scene')}>
                    <Text>Next</Text>
                </TouchableHighlight>
                {!!stateNavigator.stateContext.crumbs.length &&
                    <TouchableHighlight
                        style={styles.button}
                        underlayColor="#fff"
                        onPress={() => stateNavigator.navigateBack(1)}>
                        <Text>Back</Text>
                    </TouchableHighlight>
                }
            </View>
        )}
    </NavigationContext.Consumer>
);

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF',
    },
    button: {
        alignItems: 'center',
        backgroundColor: '#DDDDDD',
        padding: 10
    },
    text: {
        fontSize: 20,
        textAlign: 'center',
        margin: 10,
    },
});

export default Page;<|endoftext|>


<commit_before>import React from 'react';
import { StyleSheet, Text, Image, View, ListView, TouchableHighlight } from 'react-native';

export default ({ tweets, stateNavigator }) => {
  const dataSource = new ListView
    .DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    .cloneWithRows(tweets);
  return (
    <View style={styles.view}>
      <Text style={styles.home}>Home</Text>
      <ListView
        dataSource={dataSource}
        renderRow={tweet => <Tweet {...tweet} stateNavigator={stateNavigator} />} />
    </View>);
};

const Tweet = ({ id, name, logo, text, stateNavigator }) => (
  <TouchableHighlight underlayColor="white" onPress={() => {
    stateNavigator.navigate('tweet', { id: id });
  }}>
    <View style={styles.tweet}>
      <Image
        style={styles.logo}
        source={{uri: logo}}
      />
      <View style={{flex: 1}}>
        <Text style={styles.name}>{name}</Text>
        <Text>{text}</Text>
      </View>
    </View>
  </TouchableHighlight>
);

const styles = StyleSheet.create({
  home: {
    paddingTop: 10,
    fontSize: 50,
    marginTop: 50,
  },
  tweet: {
    flexDirection: 'row',
    padding: 10,
    borderBottomColor: '#ccd6dd',
    borderBottomWidth: 1,
  },
  name: {
    fontWeight: 'bold',
  },
  logo: {
    width: 50,
    height: 50,
    borderRadius: 8,
    marginRight: 8,
  },
});
<commit_msg>Tweaked format<commit_after>import React from 'react';
import { StyleSheet, Text, Image, View, ListView, TouchableHighlight } from 'react-native';

export default ({tweets, stateNavigator}) => {
  const dataSource = new ListView
    .DataSource({rowHasChanged: (r1, r2) => r1 !== r2})
    .cloneWithRows(tweets);
  return (
    <View style={styles.view}>
      <Text style={styles.home}>Home</Text>
      <ListView
        dataSource={dataSource}
        renderRow={tweet => <Tweet {...tweet} stateNavigator={stateNavigator} />} />
    </View>);
};

const Tweet = ({id, name, logo, text, stateNavigator}) => (
  <TouchableHighlight underlayColor="white" onPress={() => {
    stateNavigator.navigate('tweet', {id});
  }}>
    <View style={styles.tweet}>
      <Image
        style={styles.logo}
        source={{uri: logo}}
      />
      <View style={{flex: 1}}>
        <Text style={styles.name}>{name}</Text>
        <Text>{text}</Text>
      </View>
    </View>
  </TouchableHighlight>
);

const styles = StyleSheet.create({
  home: {
    paddingTop: 10,
    fontSize: 50,
    marginTop: 50,
  },
  tweet: {
    flexDirection: 'row',
    padding: 10,
    borderBottomColor: '#ccd6dd',
    borderBottomWidth: 1,
  },
  name: {
    fontWeight: 'bold',
  },
  logo: {
    width: 50,
    height: 50,
    borderRadius: 8,
    marginRight: 8,
  },
});
<|endoftext|>


<commit_before>'use strict';
const fs = require('fs');
const webpack = require('webpack');
const Config = require('webpack-config').Config;
const CommonsChunkPlugin = require("webpack/lib/optimize/CommonsChunkPlugin");

const TrlHtmlWebpackPlugin = require('../trl/trl-html-webpack-plugin');
const fetchLanguages = require("../loader/fetch-languages");
const fetchKwfConfig = require("./fetch-kwf-config");

const kwfConfig = fetchKwfConfig();

const devBuild = !!process.env.KWF_BUILD_DEV;

let entry = {
    Admin: [
        require.resolve('../loader/ini-loader')+'?dep=AdminMain!'
    ],
    Frontend: [
        'core-js/es6/promise',
        require.resolve('../loader/ini-loader')+'?dep=Frontend!',
    ]
};
if (kwfConfig['webpack-dev-server-url'] && devBuild) {
    entry.Frontend.push('webpack-dev-server/client?'+kwfConfig['webpack-dev-server-url']);
}

const languages = fetchLanguages();

let plugins = [];

languages.forEach(language => {
    plugins.push(new TrlHtmlWebpackPlugin({
        filename: 'Frontend.'+language+'.html',
        chunks: ['Frontend'],
        templateContent: '',
        inject: 'head',
        language: language,
        hash: true
    }));

    plugins.push(new TrlHtmlWebpackPlugin({
        filename: 'Admin.'+language+'.html',
        chunks: ['Frontend', 'Admin'],
        templateContent: '',
        inject: 'head',
        language: language,
        hash: true
    }));
});

module.exports = new Config().extend(require.resolve('./webpack.kwf.config')).merge({
    entry: entry,
    plugins: plugins
});
<commit_msg>reactived CommonsChunkPlugin for webpack, Frontend deps should not be loaded twice in Admin<commit_after>'use strict';
const fs = require('fs');
const webpack = require('webpack');
const Config = require('webpack-config').Config;

const TrlHtmlWebpackPlugin = require('../trl/trl-html-webpack-plugin');
const fetchLanguages = require("../loader/fetch-languages");
const fetchKwfConfig = require("./fetch-kwf-config");

const kwfConfig = fetchKwfConfig();

const devBuild = !!process.env.KWF_BUILD_DEV;

let entry = {
    Admin: [
        require.resolve('../loader/ini-loader')+'?dep=AdminMain!'
    ],
    Frontend: [
        'core-js/es6/promise',
        require.resolve('../loader/ini-loader')+'?dep=Frontend!',
    ]
};
if (kwfConfig['webpack-dev-server-url'] && devBuild) {
    entry.Frontend.push('webpack-dev-server/client?'+kwfConfig['webpack-dev-server-url']);
}

const languages = fetchLanguages();

let plugins = [
    new webpack.optimize.CommonsChunkPlugin({
        name: "Frontend",
        chunk: ["Admin"],
        minChunks: Infinity
    })
];

languages.forEach(language => {
    plugins.push(new TrlHtmlWebpackPlugin({
        filename: 'Frontend.'+language+'.html',
        chunks: ['Frontend'],
        templateContent: '',
        inject: 'head',
        language: language,
        hash: true
    }));

    plugins.push(new TrlHtmlWebpackPlugin({
        filename: 'Admin.'+language+'.html',
        chunks: ['Frontend', 'Admin'],
        templateContent: '',
        inject: 'head',
        language: language,
        hash: true
    }));
});

module.exports = new Config().extend(require.resolve('./webpack.kwf.config')).merge({
    entry: entry,
    plugins: plugins
});
<|endoftext|>


<commit_before>'use strict';
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const os = require('os');
const ini = require('ini');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackConfig = require('webpack-config');
const BowerResolvePlugin = require("bower-resolve-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

const loadTranslations = require('../trl/load-translations');
const lookupVendorPoFiles = require('../trl/lookup-vendor-po-files');
const lookupSassIncludePaths = require('../loader/lookup-sass-include-paths');
const lookupAliasPaths = require('../loader/lookup-alias-paths');
const TrlPlugin = require("../trl/trl-plugin");
const fetchLanguages = require("../loader/fetch-languages");
const fetchKwfConfig = require("./fetch-kwf-config");

var extractCssPlugin = new ExtractTextPlugin("./[name].css");
const kwfConfig = fetchKwfConfig();

const langauges = fetchLanguages();

const configIni = ini.parse(fs.readFileSync('config.ini', 'utf-8'));
const webCodeLangauge = configIni.production.webCodeLanguage;
const uniquePrefix = configIni.production['application.uniquePrefix'];

const devBuild = !!process.env.KWF_BUILD_DEV;

let plugins = [
    new TrlPlugin({
        uniquePrefix: uniquePrefix,
        languages: langauges,
        webCodeLanguage: webCodeLangauge,
        translations: {
            web: loadTranslations(['trl/[language].po'], langauges),
            kwf: loadTranslations(lookupVendorPoFiles(), langauges),
        }
    }),
    extractCssPlugin,
    new webpack.DefinePlugin({
        KWF_BASE_URL: '__webpack_require__.KWF_BASE_URL'
    })
];
if (!devBuild) {
    plugins.push(new UglifyJSPlugin());
}

module.exports = {
    //devtool: "source-map", // or "inline-source-map"
    output: {
        path: process.cwd()+"/build/assets",
        publicPath: (kwfConfig['webpack-dev-server-url'] ? kwfConfig['webpack-dev-server-url'] : '/') + "assets/build/",
        filename: '[name].js',
        chunkFilename: "[id].js",
        jsonpFunction: uniquePrefix+'webpackJsonp',
        pathinfo: devBuild //Include comments with information about the modules
    },
    module: {
        rules: [{
            test: /\.underscore\.tpl$/,
            loader: "underscore-template-loader",
            options: {
                engine: 'underscore'
            }
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: extractCssPlugin.extract({
                use: {
                    loader: "css-loader",
                    options: {
                        minimize: !devBuild,
                        import: false
                    }
                },
                fallback: "style-loader"
            })
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: "postcss-loader",
            options: {
                plugins: function() {
                    return [
                        require('autoprefixer')({
                            browsers: '> 0.05%',
                            remove: true,
                            add: true
                        })
                    ];
                }
            }
        },{
            enforce: 'post',
            test: /\.(s?css|underscore\.tpl|jsx?)$/,
            loader: path.resolve(__dirname, "../loader/kwfup-loader")+"?uniquePrefix="+uniquePrefix,
        },{
            enforce: 'post',
            test: /vendor\/koala-framework\/extjs2\/.*\.css$/,
            loader: require.resolve('../loader/ext2-css-loader')

        }, {
            enforce: 'post',
            test: /\.scss$/,
            loader: "sass-loader",
            options: {
                includePaths: lookupSassIncludePaths(),
                data: "@import \"config/global-settings\";"
            }
            /*
             },{
             enforce: 'post',
             test: /\.scss$/,
             use: [{
             loader:  require.resolve('../loader/caching-loader') //to avoid same scss getting built twice when extractCssPlugin is used
             }, {
             loader: "sass-loader",
             options: {
             includePaths: lookupSassIncludePaths(),
             data: "@import \"config/global-settings\";"
             }
             }]
             */

        }, {
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            loader: 'file-loader',
            options: {
                publicPath: '/assets/build/',
                name: '[path][name].[ext]'
            }
        }]
    },
    resolve: {
        modules: ["node_modules", "vendor/bower_components"],
        descriptionFiles: ['bower.json', 'package.json'],
        mainFields: ['browser', 'module', 'main'],
        plugins: [new BowerResolvePlugin()],
        alias: lookupAliasPaths(),
        extensions: ['.js', '.json']
    },
    resolveLoader: {
        modules: ["node_modules", "vendor/koala-framework/koala-framework/node_modules_build"]
    },
    stats: {
        children: false
    },
    plugins: plugins,
    devServer: {
        stats: {
            children: false
        },
        proxy: {
            '/assets': {
                target: kwfConfig['webpack-dev-server-proxy'],
                secure: false,
                changeOrigin: true
            }
        },
        setup: function(app) {
            app.use(function (req, res, next) {
                //required for fonts loaded thru proxy
                res.setHeader("Access-Control-Allow-Origin", "*");
                next();
            });
        }
    }
};
<commit_msg>resolve package.json before bower.json on webpack build<commit_after>'use strict';
const webpack = require('webpack');
const path = require('path');
const fs = require('fs');
const os = require('os');
const ini = require('ini');

const ExtractTextPlugin = require("extract-text-webpack-plugin");
const WebpackConfig = require('webpack-config');
const BowerResolvePlugin = require("bower-resolve-webpack-plugin");
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');

const loadTranslations = require('../trl/load-translations');
const lookupVendorPoFiles = require('../trl/lookup-vendor-po-files');
const lookupSassIncludePaths = require('../loader/lookup-sass-include-paths');
const lookupAliasPaths = require('../loader/lookup-alias-paths');
const TrlPlugin = require("../trl/trl-plugin");
const fetchLanguages = require("../loader/fetch-languages");
const fetchKwfConfig = require("./fetch-kwf-config");

var extractCssPlugin = new ExtractTextPlugin("./[name].css");
const kwfConfig = fetchKwfConfig();

const langauges = fetchLanguages();

const configIni = ini.parse(fs.readFileSync('config.ini', 'utf-8'));
const webCodeLangauge = configIni.production.webCodeLanguage;
const uniquePrefix = configIni.production['application.uniquePrefix'];

const devBuild = !!process.env.KWF_BUILD_DEV;

let plugins = [
    new TrlPlugin({
        uniquePrefix: uniquePrefix,
        languages: langauges,
        webCodeLanguage: webCodeLangauge,
        translations: {
            web: loadTranslations(['trl/[language].po'], langauges),
            kwf: loadTranslations(lookupVendorPoFiles(), langauges),
        }
    }),
    extractCssPlugin,
    new webpack.DefinePlugin({
        KWF_BASE_URL: '__webpack_require__.KWF_BASE_URL'
    })
];
if (!devBuild) {
    plugins.push(new UglifyJSPlugin());
}

module.exports = {
    //devtool: "source-map", // or "inline-source-map"
    output: {
        path: process.cwd()+"/build/assets",
        publicPath: (kwfConfig['webpack-dev-server-url'] ? kwfConfig['webpack-dev-server-url'] : '/') + "assets/build/",
        filename: '[name].js',
        chunkFilename: "[id].js",
        jsonpFunction: uniquePrefix+'webpackJsonp',
        pathinfo: devBuild //Include comments with information about the modules
    },
    module: {
        rules: [{
            test: /\.underscore\.tpl$/,
            loader: "underscore-template-loader",
            options: {
                engine: 'underscore'
            }
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: extractCssPlugin.extract({
                use: {
                    loader: "css-loader",
                    options: {
                        minimize: !devBuild,
                        import: false
                    }
                },
                fallback: "style-loader"
            })
        },{
            enforce: 'post',
            test: /\.s?css$/,
            loader: "postcss-loader",
            options: {
                plugins: function() {
                    return [
                        require('autoprefixer')({
                            browsers: '> 0.05%',
                            remove: true,
                            add: true
                        })
                    ];
                }
            }
        },{
            enforce: 'post',
            test: /\.(s?css|underscore\.tpl|jsx?)$/,
            loader: path.resolve(__dirname, "../loader/kwfup-loader")+"?uniquePrefix="+uniquePrefix,
        },{
            enforce: 'post',
            test: /vendor\/koala-framework\/extjs2\/.*\.css$/,
            loader: require.resolve('../loader/ext2-css-loader')

        }, {
            enforce: 'post',
            test: /\.scss$/,
            loader: "sass-loader",
            options: {
                includePaths: lookupSassIncludePaths(),
                data: "@import \"config/global-settings\";"
            }
            /*
             },{
             enforce: 'post',
             test: /\.scss$/,
             use: [{
             loader:  require.resolve('../loader/caching-loader') //to avoid same scss getting built twice when extractCssPlugin is used
             }, {
             loader: "sass-loader",
             options: {
             includePaths: lookupSassIncludePaths(),
             data: "@import \"config/global-settings\";"
             }
             }]
             */

        }, {
            test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/,
            loader: 'file-loader',
            options: {
                publicPath: '/assets/build/',
                name: '[path][name].[ext]'
            }
        }]
    },
    resolve: {
        modules: ["node_modules", "vendor/bower_components"],
        descriptionFiles: ['package.json', 'bower.json'],
        mainFields: ['browser', 'module', 'main'],
        plugins: [new BowerResolvePlugin()],
        alias: lookupAliasPaths(),
        extensions: ['.js', '.json']
    },
    resolveLoader: {
        modules: ["node_modules", "vendor/koala-framework/koala-framework/node_modules_build"]
    },
    stats: {
        children: false
    },
    plugins: plugins,
    devServer: {
        stats: {
            children: false
        },
        proxy: {
            '/assets': {
                target: kwfConfig['webpack-dev-server-proxy'],
                secure: false,
                changeOrigin: true
            }
        },
        setup: function(app) {
            app.use(function (req, res, next) {
                //required for fonts loaded thru proxy
                res.setHeader("Access-Control-Allow-Origin", "*");
                next();
            });
        }
    }
};
<|endoftext|>


<commit_before>var _        = require('underscore')._,
          es = require('elasticsearch');
var NewEventDetector = require('./events');

function Giver() {
  this.ned         = new NewEventDetector();
  this.index       = 'instagram_remap';
  this.scrape_name = 'hajj';
  this.event_client = new es.Client({hosts : ['http://52.90.177.87:9200/'],requestTimeout: 600000});

}

Giver.prototype.load_ned = function(start_date, end_date, cb) {
    var _this = this;

    this.ned.reset();

    if ( start_date == null || end_date == null ) {
      start_date = new Date('2010-01-01 01:00:00').getTime(); // before instagram existed.
      end_date = new Date().getTime();
    }
    start_date/=1000;
    end_date/=1000;

    var query = {
      "size"    : 3000,
      "_source" : ['id', 'created_time', 'location', 'sims'],
      "sort"    : [
        {
          "created_time": { "order": "asc" }
        }
      ],
      "query": {
        "range": {
          "created_time": {
            "from" : start_date,
            "to"   : (+ end_date + (24 * 60 * 60))
          }
        }
      }
    };

    this.event_client.search({
        index : 'events',
        type  : this.scrape_name,
        body  : query
    }).then(function(response) {
        console.log('load_ned :: got response');
        _.map(response.hits.hits, function(x) {
            _this.ned.update({
                'target'       : x['_source']['id'],
                'created_time' : x['_source']['created_time'],
                'location'     : x['_source']['location'],
                'cands'        : x['_source']['sims']
            })
        });

        cb({ 'events' : _this.ned.summarize() });
    }).catch(function(reason){
    console.log(reason);
  });
};

// ---- Helper functions -----

module.exports = Giver;
<commit_msg>rm unused file<commit_after><|endoftext|>