<commit_before>/**
 * Imports.
 */
var Controller    = require('microscope-web').Controller;
var commonFltrs   = require('../filters/commons');
var securityFltrs = require('../filters/security');
var csrfFltrs     = require('../filters/csrf');
var OfferTypeDao  = require('../dao/OfferTypeDao');
var _             = require('lodash');
var fs            = require('fs');

/**
 * CategoryController class.
 */
module.exports = OfferTypeController = Controller.extend({

  baseUrl: "/offertype",

  initialize: function () {
    this.offerTypeDao = new OfferTypeDao();
  },

  filters: [
    securityFltrs.authorize,
    csrfFltrs.csrf
  ],

  routes: {
    'get /'           : 'index',
    'get /_index'     : '_index',
    'get /show/:id'   : 'show',
    'get /new'        : { filters:[ csrfFltrs.antiForgeryToken ], action: 'new' },
    'post /create'    : 'create',
    'get /edit/:id'   : { filters:[ csrfFltrs.antiForgeryToken ], action: 'edit' },
    'post /update'    : { filters:[ csrfFltrs.antiForgeryToken ], action: 'update' },
    'get /delete/:id' : { filters:[ csrfFltrs.antiForgeryToken ], action: 'delete' },
    'post /destroy'   : 'destroy'
  },

  index: function(request, response) {
    this.offerTypeDao.getAll().success(function (offertypes) {
      response.render('offerType/index', {'offertypes': offertypes});
    });
  },

  _index: function(request, response) {
    this.offerTypeDao.getAll().success(function (offertypes) {
      response.render('offerType/_index', {'offertypes': offertypes});
    });
  },

  show: function(request, response) {
    var self = this;
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      if(!offertype){
        request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + id);
        response.redirect(self.baseUrl+'/_index');
      }else{
        response.render('offerType/show', {'offertype': offertype});
      }
    });
  },

  new: function (request, response) {
    response.render('offertype/new');
  },

  create: function (request, response) {
    var self = this;
    var offertype = request.body.offertype;
    this.offerTypeDao.save(offertype, function(modelError, offertype){
      if(modelError){
        request.flash('danger', self._parseValidationError(modelError));
        response.redirect('/offertype/new');
      }else{
        request.flash('success', 'Type d\'offre sauvegardée');
        response.redirect(self.baseUrl+'/_index');
      }
    });
  },

  edit: function (request, response) {
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      response.render('offerType/edit', {'offertype': offertype, 'errors': null });
    });
  },

  update: function (request, response) {
    var self = this;
    var properties = request.body.offertype;
    this.offerTypeDao.update(properties, function (modelError, offertype) {
      if(offertype){
        if(modelError){
          request.flash('danger', self._parseValidationError(modelError));
          response.redirect('/offertype/edit/' + properties.id);
        }else{
          request.flash('success', 'Type d\'offre mis à jour');
          response.redirect(self.baseUrl+'/_index');
        }
      }else{
        request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + properties.id);
        response.redirect(self.baseUrl+'/_index');
      }
    });
  },

  delete: function (request, response) {
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      response.render('offerType/delete', { 'offertype': offertype });
    }).error(function (error) {
      request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + id);
      response.redirect(self.baseUrl);
    });
  },

  destroy: function (request, response) {
    var self = this;
    var id = request.body.id;
    self.offerTypeDao.delete(id, function () {
      request.flash('success', 'Type d\'offre supprimée');
      response.redirect(self.baseUrl+'/_index');
    });
  },

  _parseValidationError: function (modelError) {
    if(_.isString(modelError)){ return modelError; }

    var errors = [];
    for (var key in modelError) {
      errors.push(modelError[key]);
    }
    return errors.join('
');
  }
});
<commit_msg>ajout des actions backend<commit_after>/**
 * Imports.
 */
var Controller    = require('microscope-web').Controller;
var commonFltrs   = require('../filters/commons');
var securityFltrs = require('../filters/security');
var csrfFltrs     = require('../filters/csrf');
var OfferTypeDao  = require('../dao/OfferTypeDao');
var _             = require('lodash');
var fs            = require('fs');

/**
 * CategoryController class.
 */
module.exports = OfferTypeController = Controller.extend({

  baseUrl: "/offertype",

  initialize: function () {
    this.offerTypeDao = new OfferTypeDao();
  },

  filters: [
    securityFltrs.authorize,
    csrfFltrs.csrf
  ],

  routes: {
    'get /'           : 'index',
    'get /_index'     : '_index',
    'get /show/:id'   : 'show',
    'get /new'        : { filters:[ csrfFltrs.antiForgeryToken ], action: 'new' },
    'post /create'    : 'create',
    'get /edit/:id'   : { filters:[ csrfFltrs.antiForgeryToken ], action: 'edit' },
    'post /update'    : { filters:[ csrfFltrs.antiForgeryToken ], action: 'update' },
    'get /delete/:id' : { filters:[ csrfFltrs.antiForgeryToken ], action: 'delete' },
    'post /destroy'   : 'destroy'
  },

  index: function(request, response) {
    this.offerTypeDao.getAll().success(function (offertypes) {
      response.render('offerType/index', {'offertypes': offertypes});
    });
  },

  _index: function(request, response) {
    this.offerTypeDao.getAll().success(function (offertypes) {
      response.render('offerType/_index', {'offertypes': offertypes});
    });
  },

  show: function(request, response) {
    var self = this;
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      if(!offertype){
        request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + id);
        response.redirect(self.baseUrl+'/_index');
      }else{
        response.render('offerType/show', {'offertype': offertype});
      }
    });
  },

  new: function (request, response) {
    response.render('offerType/new');
  },

  create: function (request, response) {
    var self = this;
    var offertype = request.body.offertype;
    this.offerTypeDao.save(offertype, function(modelError, offertype){
      if(modelError){
        request.flash('danger', self._parseValidationError(modelError));
        response.redirect('/offertype/new');
      }else{
        request.flash('success', 'Type d\'offre sauvegardée');
        response.redirect(self.baseUrl+'/_index');
      }
    });
  },

  edit: function (request, response) {
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      response.render('offerType/edit', {'offertype': offertype, 'errors': null });
    });
  },

  update: function (request, response) {
    var self = this;
    var properties = request.body.offertype;
    this.offerTypeDao.update(properties, function (modelError, offertype) {
      if(offertype){
        if(modelError){
          request.flash('danger', self._parseValidationError(modelError));
          response.redirect('/offertype/edit/' + properties.id);
        }else{
          request.flash('success', 'Type d\'offre mis à jour');
          response.redirect(self.baseUrl+'/_index');
        }
      }else{
        request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + properties.id);
        response.redirect(self.baseUrl+'/_index');
      }
    });
  },

  delete: function (request, response) {
    var id = request.params.id;
    this.offerTypeDao.get(id).success(function (offertype) {
      response.render('offerType/delete', { 'offertype': offertype });
    }).error(function (error) {
      request.flash('danger', 'Aucun type d\'offre avec l\'id : ' + id);
      response.redirect(self.baseUrl);
    });
  },

  destroy: function (request, response) {
    var self = this;
    var id = request.body.id;
    self.offerTypeDao.delete(id, function () {
      request.flash('success', 'Type d\'offre supprimée');
      response.redirect(self.baseUrl+'/_index');
    });
  },

  _parseValidationError: function (modelError) {
    if(_.isString(modelError)){ return modelError; }

    var errors = [];
    for (var key in modelError) {
      errors.push(modelError[key]);
    }
    return errors.join('
');
  }
});
<|endoftext|>


<commit_before>// npm install rem read clarinet
var rem = require('rem');
var read = require('read');
var clarinet = require('clarinet');

// Create Twitter API, prompting for key/secret.
// NOTE: Requires Twitter API 1.1
var tw = rem.connect('twitter', 1.1).prompt();

// Authenticate user via the console.
rem.console(tw, function (err, user) {

  // Pass the statuses/sample stream to a JSON parser and print only the tweets.
  user.stream('user').get(function (err, stream) {
    stream.pipe(clarinet.createStream()).on('key', function (key) {
      if (key == 'text') {
        this.once('value', function (tweet) {
          console.log(String(tweet));
        })
      }
    });
  });
});<commit_msg>Update twitter-userstream.js<commit_after>// npm install rem read clarinet
var rem = require('rem');
var read = require('read');
var clarinet = require('clarinet');

// Create Twitter API, prompting for key/secret.
// NOTE: Requires Twitter API 1.1
var tw = rem.connect('twitter.com', 1.1).prompt();

// Authenticate user via the console.
rem.console(tw, function (err, user) {

  // Pass the statuses/sample stream to a JSON parser and print only the tweets.
  user.stream('user').get(function (err, stream) {
    stream.pipe(clarinet.createStream()).on('key', function (key) {
      if (key == 'text') {
        this.once('value', function (tweet) {
          console.log(String(tweet));
        })
      }
    });
  });
});
<|endoftext|>


<commit_before>game.ShapeObject = me.Entity.extend({
     /**
     * constructor
     */
    init: function (x, y, settings) {
        // ensure we do not create a default shape
        settings.shapes = [];
        // call the super constructor
        this._super(me.Entity, "init", [x, y, settings]);
        this.hover = false;
        this.handler = me.event.subscribe(me.event.POINTERMOVE, this.mouseMove.bind(this));

        // to memorize where we grab the shape
        this.grabOffset = new me.Vector2d(0,0);

        //register on mouse/touch event
        me.input.registerPointerEvent("pointerdown", this, this.onSelect.bind(this));
        me.input.registerPointerEvent("pointerup", this, this.onRelease.bind(this));
    },

    /**
     * mousemove function
     */
    mouseMove: function (event) {
        this.hover = false;

        // the pointer event system will use the object bounding rect, check then with with all defined shapes
        if (this.inViewport && this.getBounds().containsPoint(event.gameX, event.gameY)) {
            for (var i = this.body.shapes.length, shape; i--, (shape = this.body.shapes[i]);) {
                if (shape.containsPoint(event.gameX - this.pos.x, event.gameY - this.pos.y)) {
                    this.hover = true;
                    break;
                }
            }
        }

        if (this.canMove) {
            // follow the mouse/finger
            me.game.world.moveToTop(this);
            this.pos.set(event.gameX, event.gameY, this.pos.z);
            this.pos.sub(this.grabOffset);
        }
    },

    // mouse down function
    onSelect : function (event) {
        if (this.hover === true) {
            // the pointer event system will use the object bounding rect, check then with with all defined shapes
            for (var i = this.body.shapes.length, shape; i--, (shape = this.body.shapes[i]);) {
                if (shape.containsPoint(event.gameX - this.pos.x, event.gameY - this.pos.y)) {
                    this.grabOffset.set(event.gameX, event.gameY);
                    this.grabOffset.sub(this.pos);
                    this.canMove = true;
                    // don"t propagate the event furthermore
                    return false;
                }
            }
            return true;
        }
    },

    // mouse up function
    onRelease : function (/*event*/) {
        this.canMove = false;
        // don"t propagate the event furthermore
        return false;
    },

    /**
     * update function
     */
    update: function () {
        return true;
    },

    /**
     * draw the square
     */
    draw: function (renderer) {
        renderer.setGlobalAlpha(this.hover ? 1.0 : 0.5);
        this._super(me.Entity, "draw", [renderer]);
        renderer.setGlobalAlpha(1.0);
    }
});

game.Circle = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add an ellipse shape
        this.body.addShape(new me.Ellipse(this.width/2, this.height/2, this.width, this.height));

        // tomato
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage("orange")});
    }
});

game.Poly = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add all PE shapes to the body
        this.body.addShapesFromJSON(me.loader.getJSON("shapesdef1"), settings.sprite);

        // add the star sprite
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage(settings.sprite)});
    },
});

 game.Poly2 = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add all PE shapes to the body
        this.body.addShapesFromJSON(me.loader.getJSON("shapesdef2"), settings.sprite, settings.width);

        // add the star sprite
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage(settings.sprite)});
    }
});
<commit_msg>Optimized the shape example entity code<commit_after>game.ShapeObject = me.Entity.extend({
     /**
     * constructor
     */
    init: function (x, y, settings) {
        // ensure we do not create a default shape
        settings.shapes = [];
        // call the super constructor
        this._super(me.Entity, "init", [x, y, settings]);

        // status flags
        this.selected = false;
        this.hover = false;
        // to memorize where we grab the shape
        this.grabOffset = new me.Vector2d(0,0);

        //register on mouse/touch event
        me.input.registerPointerEvent("pointerdown", this, this.onSelect.bind(this));
        me.input.registerPointerEvent("pointerup", this, this.onRelease.bind(this));
        me.input.registerPointerEvent("pointercancel", this, this.onRelease.bind(this));

        // register on the global pointermove event
        this.handler = me.event.subscribe(me.event.POINTERMOVE, this.pointerMove.bind(this));
    },

    /**
     * pointermove function
     */
    pointerMove: function (event) {
        this.hover = false;

        // the pointer event system will use the object bounding rect, check then with with all defined shapes
        if (this.getBounds().containsPoint(event.gameX, event.gameY)) {
            for (var i = this.body.shapes.length, shape; i--, (shape = this.body.shapes[i]);) {
                if (shape.containsPoint(event.gameX - this.pos.x, event.gameY - this.pos.y)) {
                    this.hover = true;
                    break;
                }
            }
        }

        if (this.selected) {
            // follow the pointer
            me.game.world.moveToTop(this);
            this.pos.set(event.gameX, event.gameY, this.pos.z);
            this.pos.sub(this.grabOffset);
        }
    },

    // mouse down function
    onSelect : function (event) {
        if (this.hover === true) {
            this.grabOffset.set(event.gameX, event.gameY);
            this.grabOffset.sub(this.pos);
            this.selected = true;
            // don"t propagate the event furthermore
            return false;
        }
        return true;
    },

    // mouse up function
    onRelease : function (/*event*/) {
        this.selected = false;
        // don"t propagate the event furthermore
        return false;
    },

    /**
     * update function
     */
    update: function () {
        return this.selected || this.hover;
    },

    /**
     * draw the square
     */
    draw: function (renderer) {
        renderer.setGlobalAlpha(this.hover ? 1.0 : 0.5);
        this._super(me.Entity, "draw", [renderer]);
        renderer.setGlobalAlpha(1.0);
    }
});

game.Circle = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add an ellipse shape
        this.body.addShape(new me.Ellipse(this.width/2, this.height/2, this.width, this.height));

        // tomato
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage("orange")});
    }
});

game.Poly = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add all PE shapes to the body
        this.body.addShapesFromJSON(me.loader.getJSON("shapesdef1"), settings.sprite);

        // add the star sprite
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage(settings.sprite)});
    },
});

 game.Poly2 = game.ShapeObject.extend({
    /**
     * constructor
     */
    init: function (x, y, settings) {
        // call the super constructor
        this._super(game.ShapeObject, "init", [x, y, settings]);

        // add all PE shapes to the body
        this.body.addShapesFromJSON(me.loader.getJSON("shapesdef2"), settings.sprite, settings.width);

        // add the star sprite
        this.renderable = new me.Sprite(0, 0, {image: me.loader.getImage(settings.sprite)});
    }
});
<|endoftext|>


<commit_before>const edge = require('edge');
const md = require('marked');
const getCompilerController = ({ tasks }) => {
    const getTasksList = (req, res) => {
        tasks.getAll()
            .then((data) => {
                const context = {
                    tasks: data,
                };
                res.render('tasks', context);
            });
    };
    const getCompilerForm = (req, res) => {
        const id = req.params.id;
        tasks.findById(id)
            .then((task) => {
                const context = {
                    task: task,
                    md: md,
                };
                return context;
            })
            .then((context) => {
                return res.render('compiler', context);
            });
    };
    const postTaskSolution = (req, res) => {
        const id = req.params.id;
        tasks.findById(id)
            .then((task) => {
                const boilerplate = edge.func(
                    `using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

public class Startup
{
    static void FakeInput(object input)
    {
        Console.SetIn(new StringReader(input.ToString()));
    }

    public async Task<object> Invoke(object input)
    {
        FakeInput(input);
        using(var writer = new StringWriter())
        {
            Console.SetOut(writer);
            Console.Out.NewLine = "\\n";
            var sw = new Stopwatch();
            Process proc = Process.GetCurrentProcess();
            var task = Task.Factory.StartNew(() => Program.Main());
            sw.Start();
            task.Wait(${+task.timelimit});
            if (task.IsCompleted)
            {
                sw.Stop();
                writer.Flush();
                var result = writer.GetStringBuilder().ToString();
                return String.Format("{0} {1} {2:F2}",
                sw.Elapsed, result, (proc.WorkingSet64 / (1024.0 * 1024) - 55));
            }
            else
            {
                sw.Stop();
                throw new TimeoutException(sw.Elapsed.ToString());
            }
        }
    }
    ${req.body}
}`);
                const results = [];
                for (let i = 0; i < task.input.length; i++) {
                    boilerplate(task.input[i].trim(), (error, result) => {
                        if (error) {
                            results.push({
                                status: 'failed',
                                reason: error.name,
                                message: error.message,
                            });
                        } else {
                            const current = result.trim().split(' ');
                            const message = `Time: ${current[0]} Memory: ${current[2]}MB`;
                            if (task.results[i].trim() === current[1].trim() &&
                            +task.memorylimit > +current[2]) {
                                results.push({
                                    status: 'passed',
                                    reason: '',
                                    message: message,
                                });
                            } else {
                                results.push({
                                    status: 'failed',
                                    reason: 'wrong result',
                                    message: message,
                                });
                            }
                        }
                    });
                }
                return results;
            })
            .then((results) => {
                res.send(results);
            })
            .catch((error) => {
                const message = error.message
                    .substring(0, error.message.indexOf('---->') - 1);
                res.send([{
                    status: 'failed',
                    reason: error.name,
                    message: message,
                }]);
            });
    };

    return {
        getTasksList,
        getCompilerForm,
        postTaskSolution,
    };
};

module.exports = { getCompilerController };
<commit_msg>fixing lint error<commit_after>const edge = require('edge');
const md = require('marked');
const getCompilerController = ({ tasks }) => {
    const getTasksList = (req, res) => {
        tasks.getAll()
            .then((data) => {
                const context = {
                    tasks: data,
                };
                res.render('tasks', context);
            });
    };
    const getCompilerForm = (req, res) => {
        const id = req.params.id;
        tasks.findById(id)
            .then((task) => {
                const context = {
                    task: task,
                    md: md,
                };
                return context;
            })
            .then((context) => {
                return res.render('compiler', context);
            });
    };
    const postTaskSolution = (req, res) => {
        const id = req.params.id;
        tasks.findById(id)
            .then((task) => {
                const boilerplate = edge.func(
                    `using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

public class Startup
{
    static void FakeInput(object input)
    {
        Console.SetIn(new StringReader(input.ToString()));
    }

    public async Task<object> Invoke(object input)
    {
        FakeInput(input);
        using(var writer = new StringWriter())
        {
            Console.SetOut(writer);
            Console.Out.NewLine = "\\n";
            var sw = new Stopwatch();
            Process proc = Process.GetCurrentProcess();
            var task = Task.Factory.StartNew(() => Program.Main());
            sw.Start();
            task.Wait(${+task.timelimit});
            if (task.IsCompleted)
            {
                sw.Stop();
                writer.Flush();
                var result = writer.GetStringBuilder().ToString();
                return String.Format("{0} {1} {2:F2}",
                sw.Elapsed, result, (proc.WorkingSet64 / (1024.0 * 1024) - 55));
            }
            else
            {
                sw.Stop();
                throw new TimeoutException(sw.Elapsed.ToString());
            }
        }
    }
    ${req.body}
}`);
                const results = [];
                for (let i = 0; i < task.input.length; i++) {
                    boilerplate(task.input[i].trim(), (error, result) => {
                        if (error) {
                            results.push({
                                status: 'failed',
                                reason: error.name,
                                message: error.message,
                            });
                        } else {
                            const current = result.trim().split(' ');
                            const message = `Time: ${current[0]}
                            Memory: ${current[2]}MB`;
                            if (task.results[i].trim() === current[1].trim() &&
                                +task.memorylimit > +current[2]) {
                                results.push({
                                    status: 'passed',
                                    reason: '',
                                    message: message,
                                });
                            } else {
                                results.push({
                                    status: 'failed',
                                    reason: 'wrong result',
                                    message: message,
                                });
                            }
                        }
                    });
                }
                return results;
            })
            .then((results) => {
                res.send(results);
            })
            .catch((error) => {
                const message = error.message
                    .substring(0, error.message.indexOf('---->') - 1);
                res.send([{
                    status: 'failed',
                    reason: error.name,
                    message: message,
                }]);
            });
    };

    return {
        getTasksList,
        getCompilerForm,
        postTaskSolution,
    };
};

module.exports = { getCompilerController };
<|endoftext|>


<commit_before>var RippleTransaction = require('../models/ripple_transaction.js');
var User = require('../models/user.js');
var errorResponse = require("../../lib/utils.js").errorResponse;
var util = require('util');

module.exports = (function(){
  function index(req, res) {
    req.user.rippleTransactions(function(err, payments) {
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payments: (payments || []) });
      }
    });
  }

  function update(req, res){
    req.checkBody('txHash', 'Invalid txHash').notEmpty()
    req.checkBody('txState', 'Invalid txStatus').notEmpty()
    if (errors = req.validationErrors()) {
      res.send(500, { error: errors });
    }

    RippleTransaction.find(req.params.id).complete(function(err, payment){
      if (err) {
        res.send(500, { error: err});
      } else {
        payment.tx_hash = req.body.txHash
        payment.tx_state = req.body.txState
        payment.save().complete(function(err, tx){
          if (err) {
            res.send(500, { error: err});
          } else {
            res.send({ payment: payment });
          }
        })
      }
    })
  }

  function show(req, res) {
    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payment: payment })
      }
    })
  }

	function create(req, res) {
    req.checkBody('to_address', 'Invalid to_address').notNull();
    req.checkBody('to_amount', 'Invalid to_amount').notNull();
    req.checkBody('to_currency', 'Invalid to_currency').notNull();
    req.checkBody('to_isser', 'Invalid to_issuer').notNull();
    req.checkBody('from_address', 'Invalid from_address').notNull();
    req.checkBody('from_amount', 'Invalid from_amount').notNull();
    req.checkBody('from_currency', 'Invalid from_currency').notNull();
    req.checkBody('from_issuer', 'Invalid from_issuer').notNull();

    var errors = req.validationErrors();
    if (errors) { res.send(500, errors); return }

    RippleTransaction.create(req.body).complete(function(err, payment){
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payment: payment })
      }
    })
  }

  return {
    update: update,
    create: create,
		index: index,
    show: show
	}
})();
<commit_msg>[FEATURE] Ensure that parameters are decimals.<commit_after>var RippleTransaction = require('../models/ripple_transaction.js');
var User = require('../models/user.js');
var errorResponse = require("../../lib/utils.js").errorResponse;
var util = require('util');

module.exports = (function(){
  function index(req, res) {
    req.user.rippleTransactions(function(err, payments) {
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payments: (payments || []) });
      }
    });
  }

  function update(req, res){
    req.checkBody('txHash', 'Invalid txHash').notEmpty()
    req.checkBody('txState', 'Invalid txStatus').notEmpty()
    if (errors = req.validationErrors()) {
      res.send(500, { error: errors });
    }

    RippleTransaction.find(req.params.id).complete(function(err, payment){
      if (err) {
        res.send(500, { error: err});
      } else {
        payment.tx_hash = req.body.txHash
        payment.tx_state = req.body.txState
        payment.save().complete(function(err, tx){
          if (err) {
            res.send(500, { error: err});
          } else {
            res.send({ payment: payment });
          }
        })
      }
    })
  }

  function show(req, res) {
    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payment: payment })
      }
    })
  }

	function create(req, res) {
    req.checkBody('to_address', 'Invalid to_address').notNull();
    req.checkBody('to_amount', 'Invalid to_amount').isDecimal();
    req.checkBody('to_currency', 'Invalid to_currency').notNull();
    req.checkBody('to_issuer', 'Invalid to_issuer').notNull();
    req.checkBody('from_address', 'Invalid from_address').notNull();
    req.checkBody('from_amount', 'Invalid from_amount').isDecimal();
    req.checkBody('from_currency', 'Invalid from_currency').notNull();
    req.checkBody('from_issuer', 'Invalid from_issuer').notNull();
    req.checkBody('ripple_address_id', 'Invalid from_issuer').isInt();

    var errors = req.validationErrors();
    if (errors) { res.send(500, errors); return }

    RippleTransaction.create(req.body).complete(function(err, payment){
      if (err) {
        res.send(500, { error: err });
      } else {
        res.send({ payment: payment })
      }
    })
  }

  return {
    update: update,
    create: create,
		index: index,
    show: show
	}
})();
<|endoftext|>


<commit_before>var RippleTransaction = require('../models/ripple_transaction.js');
var User = require('../models/user.js');
var errorResponse = require("../../lib/utils.js").errorResponse;
var util = require('util');

module.exports = (function(){
  function index(req, res) {
    User.find(req.params.id).complete(function(err, user) {
      user.rippleTransactions(function(err, transactions) {
        res.send({ ripple_transactions: (transactions || []) });
      });
    });
  }

  function update(req, res){
    req.checkBody('txHash', 'Invalid txHash').notEmpty()
    req.checkBody('txState', 'Invalid txStatus').notEmpty()
    if (errors = req.validationErrors()) {
			errorResponse(res)(util.inspect(errors));
    }

    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) { res.send({ success: false, error: err}); return false }
      tx.txHash = req.body.txHash
      tx.txState = req.body.txState
      tx.save().complete(function(err, tx){
        if (err) { res.send({ success: false, error: err}); return false }
        res.send({ success: true, transaction: tx })
      })
    })
  }

  function show(req, res) {
    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) { res.send({ success: false, error: err}); return false }
      res.send({ success: true, transaction: tx })
    })
  }

	function create(req, res) {
    req.checkBody('to_currency', 'Invalid to_currency')
      .notEmpty().isAlphanumeric()
    req.checkBody('from_currency', 'Invalid from_currency')
      .notEmpty().isAlphanumeric()
    req.checkBody('to_amount', 'Invalid to_amount')
      .notEmpty().isDecimal()
    req.checkBody('from_amount', 'Invalid from_amount')
      .notEmpty().isDecimal()
    req.checkBody('to_address', 'Invalid to_address')
      .notEmpty().isAlphanumeric()
    req.checkBody('from_address', 'Invalid from_address')
      .notEmpty().isAlphanumeric()
    req.checkBody('to_issuer', 'Invalid to_isser')
      .notEmpty().isAlphanumeric()
    req.checkBody('from_issuer', 'Invalid from_isser')
      .notEmpty().isAlphanumeric()
    req.checkBody('ripple_address_id', 'Invalid ripple_address_id')
      .notEmpty().isAlphanumeric()
    req.sanitize('issuance').toBoolean()

    var errors = req.validationErrors();
    if (errors) { res.send(util.inspect(errors)); return }

    RippleTransaction.create(req.body).complete(function(err, tx){
      res.send({ ripple_transaction: tx, error: err })
    })
  }

  return {
    update: update,
    create: create,
		index: index,
    show: show
	}
})();
<commit_msg>[FEATURE] Swithc ripple_transactions controller to strong parameters.<commit_after>var RippleTransaction = require('../models/ripple_transaction.js');
var User = require('../models/user.js');
var errorResponse = require("../../lib/utils.js").errorResponse;
var util = require('util');

module.exports = (function(){
  function index(req, res) {
    User.find(req.params.id).complete(function(err, user) {
      user.rippleTransactions(function(err, transactions) {
        res.send({ ripple_transactions: (transactions || []) });
      });
    });
  }

  function update(req, res){
    req.checkBody('txHash', 'Invalid txHash').notEmpty()
    req.checkBody('txState', 'Invalid txStatus').notEmpty()
    if (errors = req.validationErrors()) {
			errorResponse(res)(util.inspect(errors));
    }

    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) { res.send({ success: false, error: err}); return false }
      tx.txHash = req.body.txHash
      tx.txState = req.body.txState
      tx.save().complete(function(err, tx){
        if (err) { res.send({ success: false, error: err}); return false }
        res.send({ success: true, transaction: tx })
      })
    })
  }

  function show(req, res) {
    RippleTransaction.find(req.params.id).complete(function(err, tx){
      if (err) { res.send({ success: false, error: err}); return false }
      res.send({ success: true, transaction: tx })
    })
  }

	function create(req, res) {
    req.validate('to_address', 'isAlphanumeric');
    req.validate('to_amount', 'isAlphanumeric');
    req.validate('to_currency', 'isAlphanumeric');
    req.validate('to_isser', 'isAlphanumeric');
    req.validate('from_address', 'isAlphanumeric');
    req.validate('from_amount', 'isAlphanumeric');
    req.validate('from_currency', 'isAlphanumeric');
    req.validate('from_issuer', 'isAlphanumeric');
    req.validate('ripple_address_id', 'isAlphanumeric');

    req.sanitize('issuance').toBoolean()

    var errors = req.validationErrors();
    if (errors) { res.send(util.inspect(errors)); return }

    RippleTransaction.create(req.body).complete(function(err, tx){
      res.send({ ripple_transaction: tx, error: err })
    })
  }

  return {
    update: update,
    create: create,
		index: index,
    show: show
	}
})();
<|endoftext|>


<commit_before>'use strict';
/* Controller for Fragment Sankey Diagram View */
angular.module('lcaApp.fragment.sankey',
                ['ui.router', 'lcaApp.sankey', 'lcaApp.resources.service', 'lcaApp.status.service',
                 'lcaApp.format', 'lcaApp.fragmentNavigation.service', 'lcaApp.models.scenario',
                    'lcaApp.selection.service'])
    .controller('FragmentSankeyCtrl',
        ['$scope', '$stateParams', '$state', 'StatusService', '$q', '$log',
        'ScenarioModelService', 'FragmentService', 'FragmentFlowService', 'FlowForFragmentService', 'ProcessService',
        'FlowPropertyForFragmentService', 'FormatService', 'FragmentNavigationService',
        function ($scope, $stateParams, $state, StatusService, $q, $log, ScenarioModelService, FragmentService,
                  FragmentFlowService, FlowForFragmentService, ProcessService, FlowPropertyForFragmentService,
                  FormatService, FragmentNavigationService) {
            var fragmentID = 0,
                scenarioID = ScenarioModelService.getBaseCaseID(),
                topLevelFragmentID = 0,
            //
                graph = {},
                reverseIndex = {},  // map fragmentFlowID to graph.nodes and graph.links
                baseValue = 1E-14,  // sankey link base value (replaces 0).
                magFormat = FormatService.format();

            $scope.color = { domain: (["Fragment", "InputOutput", "Cutoff", "Process", "Background"]), range: colorbrewer.Set3[5], property: "nodeType" };
            $scope.selectedFlowProperty = null;
            $scope.selectedNode = null;
            $scope.mouseOverNode = null;
            $scope.fragment = null;
            $scope.scenario = null;
            $scope.$watch("selectedNode", onNodeSelectionChange);
            $scope.$watch("mouseOverNode", onMouseOverNode);

            $scope.onScenarioChange = function() {
                scenarioID = $scope.scenario.scenarioID;
                topLevelFragmentID = $scope.scenario.topLevelFragmentID;
                ScenarioModelService.setActiveID(scenarioID);
                getData();
            };

            /**
             * Temporary workaround for flows with problem properties. Hide them
             * @param fpID
             * @returns {boolean}
             */
            function showFlowProperty(fpID) {
                var fp = FlowPropertyForFragmentService.get(fpID);
                return fp &&
                    !(fp["referenceUnit"] === "kgP" || fp["referenceUnit"] === "kg-Av" || fp["referenceUnit"] === "MJ-Av");
            }

            function filterFragmentFlow(ff) {
                return ff.nodeType !== "Cutoff" && ff.flowPropertyMagnitudes &&
                    showFlowProperty(ff.flowPropertyMagnitudes[0]["flowPropertyID"]);
            }

            /**
             * Build sankey graph from loaded data
             * @param {Boolean} makeNew  Indicates if new graph should be created. False means update existing graph.
             */
            function buildGraph(makeNew) {
                try {
                    var ff = FragmentFlowService.getAll(),
                        fragmentFlows = ff.filter (filterFragmentFlow);
                    graph.isNew = makeNew;
                    if (makeNew) {
                        reverseIndex = {};
                        graph.nodes = [];
                        graph.nodes.push(createRootNode());
                        // Add a node for every flow
                        fragmentFlows.forEach(addGraphNode);
                    }
                    // Add a link for every flow. source and target are indexes into nodes array.
                    graph.links = [];
                    fragmentFlows.forEach(addGraphLink);
                    $scope.graph = graph;
                }
                catch (err) {
                    StatusService.handleFailure(err);
                }
            }

            /**
             * Get magnitude of link with a flow property
             * @param {{fragmentFlowID:Number, parentFragmentFlowID:Number, direction: String, flowPropertyMagnitudes:Array}}  link
             * @param {Number}  flowPropertyID    flow property key
             * @return {Number} The magnitude, if link has the flow property. Otherwise, null.
             */
            function getMagnitude(link, flowPropertyID) {
                var magnitude = null, flowPropertyMagnitudes = [];
                if ("flowPropertyMagnitudes" in link) {
                    flowPropertyMagnitudes = link.flowPropertyMagnitudes.filter(
                        /**
                         * @param {{flowPropertyID:number}}  lm
                         */
                            function (lm) {
                            return +lm.flowPropertyID === flowPropertyID;
                        });
                }
                if (flowPropertyMagnitudes && flowPropertyMagnitudes.length > 0) {
                    magnitude = flowPropertyMagnitudes[0].magnitude *  $scope.fragment.activityLevel;
                }
                return magnitude;
            }

            function createRootNode() {
                return {
                    nodeType: "InputOutput",
                    nodeID: 0,
                    nodeName: "Reference Flow",
                    toolTip: "InputOutput"
                }
            }

            /**
             * Add graph node for fragment flow element
             * @param {{fragmentFlowID:number}} element
             */
            function addGraphNode(element) {
                var node = {
                        nodeType: element.nodeType,
                        nodeID: element.fragmentFlowID,
                        nodeName: "",
                        toolTip: ""
                    },
                    fragFlow = FragmentFlowService.get(element.fragmentFlowID),
                    refObj , selectTip
                    ;

                if (fragFlow) {
                    node.nodeName = fragFlow["shortName"];
                }
                if (node.nodeType) {
                    node.toolTip = "" + node.nodeType + "";
                }
                if ("processID" in element) {
                    refObj = ProcessService.get(element.processID);
                    node.selectable = true;
                    selectTip = "Click to view process instance";
                } else if ("subFragmentID" in element) {
                    refObj = FragmentService.get(element.subFragmentID);
                    node.selectable = true;
                    selectTip = "Click to descend";
                }
                if (refObj) {
                    node.toolTip = node.toolTip + "
" + refObj.name + "
";
                }
                if (selectTip) {
                    node.toolTip = node.toolTip + "" + selectTip + "";
                }

                reverseIndex[element.fragmentFlowID] = graph.nodes.push(node) - 1;
            }

            /**
             * Add graph link for fragmentflow element
             * @param {{fragmentFlowID:Number, parentFragmentFlowID:Number, direction:String, flowPropertyMagnitudes:Array}} element
             * @exception Error thrown if referenced flow not found
             */
            function addGraphLink(element) {
                var link, parentIndex,
                    nodeIndex = reverseIndex[element.fragmentFlowID],
                    magnitude = getMagnitude(element, $scope.selectedFlowProperty["flowPropertyID"]),
                    value = (magnitude === null || magnitude <= 0) ? baseValue : baseValue + magnitude,
                    flow = FlowForFragmentService.get(element.flowID),
                    unit = $scope.selectedFlowProperty["referenceUnit"];

                if ("parentFragmentFlowID" in element) {
                    if (element.parentFragmentFlowID in reverseIndex) {
                        parentIndex = reverseIndex[element.parentFragmentFlowID];
                    }
                    else {
                        return;
                    }
                } else {
                    parentIndex = 0;
                }
                link = {
                    nodeID: element.fragmentFlowID,
                    flowID: element.flowID,
                    value: value
                };
                if (flow) {
                    if (magnitude) {
                        link.magnitude = magnitude;
                        link.toolTip = flow.name + " : " + magFormat(magnitude) + " " + unit;
                    } else {
                        link.toolTip = flow.name + " does not have property : " + $scope.selectedFlowProperty["name"];
                    }
                } else {
                    throw new Error ("Flow with ID, " + flowID + ", was not found.");
                }
                if (element.direction === "Input") {
                    link.source = nodeIndex;
                    link.target = parentIndex;
                } else {
                    link.source = parentIndex;
                    link.target = nodeIndex;
                }
                graph.links.push(link);
            }

            /**
             * Prepare fragment data for visualization
             */
            function visualizeFragment() {
                setFlowProperties();
                buildGraph(true);
                StatusService.stopWaiting();
            }

            /**
             * If returning from another view, restore last fragment in navigation stack.
             * Otherwise, set to top-level fragment, activity level derived from scenario.
             */
            function initScopeFragment() {
                var fragState = FragmentNavigationService.getLast();
                if (fragState) {
                    $scope.fragment = fragState;
                    fragmentID = $scope.fragment.fragmentID;
                } else {
                    $scope.fragment = FragmentService.get(fragmentID);
                    if ($scope.fragment) {
                        $scope.fragment.activityLevel = $scope.scenario["activityLevel"];
                        FragmentNavigationService.add($scope.fragment);
                    } else {
                        StatusService.handleFailure("Invalid fragment ID : " + fragmentID);
                    }
                }
                return $scope.fragment;
            }

            /**
             * Prepare to display sub-fragment
             * Calculate sub-fragment activity level, push current fragment on breadcrumb stack
             * @param {{subFragmentID: Number, nodeWeight: Number}} fragmentFlow  containing selected sub-fragment
             */
            function navigateSubFragment( fragmentFlow) {
                var subFragment = FragmentService.get(fragmentFlow.subFragmentID);
                if (subFragment) {
                    subFragment.activityLevel = $scope.fragment.activityLevel * fragmentFlow.nodeWeight;
                    fragmentID = fragmentFlow.subFragmentID;
                    $scope.fragment = subFragment;
                    FragmentNavigationService.add($scope.fragment);
                    getDataForFragment();
                } else {
                    StatusService.handleFailure("Invalid sub-fragment ID : " + fragmentFlow.subFragmentID);
                }
            }

            /**
             * Function called after requests for resources have been fulfilled.
             */
            function displayLoadedData() {
                var scenario;
                $scope.scenarios = ScenarioModelService.getAll();

                scenario = ScenarioModelService.get(scenarioID);
                if (!scenario) {
                    // Active scenario may have been deleted
                    // Grab first one in list
                    if ($scope.scenarios.length > 0) {
                        scenario = $scope.scenarios[0];
                        scenarioID = scenario.scenarioID;
                    }
                }
                if (scenario) {
                    if (topLevelFragmentID === 0) {
                        topLevelFragmentID = scenario.topLevelFragmentID;
                    } else if (scenario.topLevelFragmentID !== topLevelFragmentID) {
                        var newScenario = null;
                        //
                        // If topLevelFragmentID comes from Fragment LCIA, then it may not be the top-level fragment of the
                        // current scenario. In this case, activate first scenario selected in Fragment LCIA,
                        // if one exists. Otherwise, set topLevelFragmentID to top-level fragment ID of current scenario.
                        //
                        var selectedScenarios = ScenarioModelService.getSelectedScenarioIDs();
                        if (selectedScenarios.length > 0) {
                            newScenario = ScenarioModelService.get(selectedScenarios[0]);
                        }
                        if (newScenario === null) {
                            topLevelFragmentID = scenario.topLevelFragmentID;
                        } else {
                            scenario = newScenario;
                            scenarioID = scenario.scenarioID;
                        }
                    }
                    fragmentID = topLevelFragmentID;
                    $scope.scenario = scenario;
                    ScenarioModelService.setActiveID(scenarioID);
                    $scope.navigationService = FragmentNavigationService.setContext(scenarioID, topLevelFragmentID);
                    initScopeFragment();
                    getDataForFragment();
                } else {
                    StatusService.handleFailure("Invalid scenarioID: " + scenarioID);
                }
            }

            /**
             * Update scope with flow properties and select one
             */
            function setFlowProperties() {
                //
                //  If the last flow property selection is not in the current list, reset to the default flow property,
                //  if that is in the list. Otherwise, set to first element in resource payload.
                //
                var selectedFlowProperty = $scope.selectedFlowProperty,
                    flowProperties = FlowPropertyForFragmentService.getAll();
                flowProperties.sort(FlowPropertyForFragmentService.compareByName);
                if (flowProperties) {
                    if (selectedFlowProperty) {
                        selectedFlowProperty = flowProperties.find(function (element) {
                            return (element["flowPropertyID"] === selectedFlowProperty["flowPropertyID"]);
                        });
                    }
                    if (!selectedFlowProperty) {
                        selectedFlowProperty = flowProperties.find(function (element) {
                            return (element.name === "Mass");
                        });
                        if (!selectedFlowProperty) {
                            selectedFlowProperty = flowProperties[0];
                        }
                    }
                } else {
                    selectedFlowProperty = null;
                }
                $scope.flowProperties = flowProperties;
                $scope.selectedFlowProperty = selectedFlowProperty;
            }

            /**
             * Get all data resources
             */
            function getData() {
                StatusService.startWaiting();
                $q.all([ScenarioModelService.load(), FragmentService.load(), ProcessService.load()])
                    .then(displayLoadedData,
                    StatusService.handleFailure);
            }

            /**
             * Get data resources that are filtered by fragment.
             * Called after fragment selection changes.
             * If successful, visualize selected fragment.
             */
            function getDataForFragment() {
                StatusService.startWaiting();
                $q.all([FlowPropertyForFragmentService.load({fragmentID: fragmentID}),
                    FragmentFlowService.load({scenarioID: scenarioID, fragmentID: fragmentID}),
                    FlowForFragmentService.load({fragmentID: fragmentID})])
                    .then(visualizeFragment,
                    StatusService.handleFailure);
            }

            /**
             * Called when flow property selection changes.
             * Updates existing sankey graph.
             */
            $scope.onFlowPropertyChange = function () {
                buildGraph(false);
            };

            /**
             * Called when a parent fragment is selected from fragment breadcrumbs.
             * Updates fragment breadcrumbs and gets new fragment data.
             * @param fragment  Fragment selected
             * @param index     Breadcrumb index
             */
            $scope.onParentFragmentSelected = function (fragment, index) {
                fragmentID = fragment.fragmentID;
                $scope.fragment = fragment;
                FragmentNavigationService.setLast(index);
                getDataForFragment();
            };

            /**
             * Called when a node in sankey directive is selected.
             * The node can represent either a fragment or a process.
             * @param newVal    The selected node
             */
            function onNodeSelectionChange(newVal) {
                if (newVal) {
                    var fragmentFlow = FragmentFlowService.get(newVal.nodeID);
                    $log.info("Clicked on node with weight = " + fragmentFlow.nodeWeight);
                    switch (newVal.nodeType) {
                        case "Process" :
                            $state.go("fragment-sankey.process-instance", {
                                    scenarioID: scenarioID,
                                    fragmentID: fragmentID,
                                    fragmentFlowID: fragmentFlow.fragmentFlowID,
                                    activity: $scope.fragment.activityLevel *
                                    fragmentFlow.nodeWeight
                                }
                            );
                            break;
                        case "Fragment" :
                            navigateSubFragment(fragmentFlow);
                            break;
                    }
                }
            }

            /**
             * Get flow table content
             * For each Sankey link provided, get
             * flow name, magnitude and unit associated with selected flow property.
             * If the link does have the selected flow property, display
             * magnitude and unit for the
             * reference flow property.
             *
             * @param {Array}  nodeLinks     Sankey links
             * @return {Array}  Data for display in table
             */
            function getFlowRows(nodeLinks) {
                var flowData = [];

                nodeLinks.forEach( function (l) {
                    if ("flowID" in l) {
                        var flow = FlowForFragmentService.get(l.flowID),
                            flowPropertyID = $scope.selectedFlowProperty["flowPropertyID"],
                            magnitude = l.magnitude,
                            unit = "";
                        if (magnitude) {
                            unit = $scope.selectedFlowProperty["referenceUnit"];
                        } else  {
                            var fp, ff;
                            ff = FragmentFlowService.get(l.nodeID);
                            flowPropertyID = flow["referenceFlowPropertyID"];
                            magnitude = getMagnitude(ff, flowPropertyID);
                            fp = FlowPropertyForFragmentService.get(flowPropertyID);
                            if (fp) {
                               unit = fp["referenceUnit"];
                            }
                        }
                        flowData.push({ name: flow.name, magnitude: magnitude, unit: unit });
                    }
                });
                return flowData;
            }

            function onMouseOverNode(node) {
                if (node) {
                    $scope.inputFlows = getFlowRows(node.targetLinks);
                    $scope.outputFlows = getFlowRows(node.sourceLinks);
                }
            }

            function getSelectedFragmentID() {
                var selectedTopLevelFragmentID = ScenarioModelService.getSelectedTopLevelFragmentID();
                if (selectedTopLevelFragmentID) {
                    topLevelFragmentID = selectedTopLevelFragmentID;
                }
            }

            function getActiveScenarioID() {
                var activeID = ScenarioModelService.getActiveID();
                if (activeID) {
                    scenarioID = activeID;
                }
            }

            function getStateParams() {
                if ( $stateParams.hasOwnProperty("scenarioID") && $stateParams.scenarioID !== undefined) {
                    scenarioID = +$stateParams.scenarioID;
                }
                if ($stateParams.hasOwnProperty("fragmentID") && $stateParams.fragmentID !== undefined) {
                    topLevelFragmentID = +$stateParams.fragmentID;
                }
            }

            getSelectedFragmentID();
            getActiveScenarioID();
            getStateParams();
            getData();
        }]);<commit_msg>Vis: Fragment Sankey: Simplify controller  (#198)<commit_after>'use strict';
/* Controller for Fragment Sankey Diagram View */
angular.module('lcaApp.fragment.sankey',
                ['ui.router', 'lcaApp.sankey', 'lcaApp.resources.service', 'lcaApp.status.service',
                 'lcaApp.format', 'lcaApp.fragmentNavigation.service', 'lcaApp.models.scenario',
                    'lcaApp.selection.service'])
    .controller('FragmentSankeyCtrl',
        ['$scope', '$stateParams', '$state', 'StatusService', '$q', '$log',
        'ScenarioModelService', 'FragmentService', 'FragmentFlowService', 'FlowForFragmentService', 'ProcessService',
        'FlowPropertyForFragmentService', 'FormatService', 'FragmentNavigationService',
        function ($scope, $stateParams, $state, StatusService, $q, $log, ScenarioModelService, FragmentService,
                  FragmentFlowService, FlowForFragmentService, ProcessService, FlowPropertyForFragmentService,
                  FormatService, FragmentNavigationService) {
            var defaultScenarioID = ScenarioModelService.getBaseCaseID(),
                defaultFragmentID = 0,
            //
                graph = {},
                reverseIndex = {},  // map fragmentFlowID to graph.nodes and graph.links
                baseValue = 1E-14,  // sankey link base value (replaces 0).
                magFormat = FormatService.format();

            $scope.color = { domain: (["Fragment", "InputOutput", "Cutoff", "Process", "Background"]), range: colorbrewer.Set3[5], property: "nodeType" };
            $scope.selectedFlowProperty = null;
            $scope.selectedNode = null;
            $scope.mouseOverNode = null;
            $scope.fragment = null;
            $scope.scenario = null;
            $scope.$watch("selectedNode", onNodeSelectionChange);
            $scope.$watch("mouseOverNode", onMouseOverNode);

            $scope.onScenarioChange = function() {
                getData();
            };

            /**
             * Temporary workaround for flows with problem properties. Hide them
             * @param fpID
             * @returns {boolean}
             */
            function showFlowProperty(fpID) {
                var fp = FlowPropertyForFragmentService.get(fpID);
                if (!fp) {
                    StatusService.handleFailure("Unable to get data for flow property with ID: " + fpID);
                }
                return fp &&
                    !(fp["referenceUnit"] === "kgP" || fp["referenceUnit"] === "kg-Av" || fp["referenceUnit"] === "MJ-Av");
            }

            function filterFragmentFlow(ff) {
                return ff.nodeType !== "Cutoff" && ff.flowPropertyMagnitudes &&
                    showFlowProperty(ff.flowPropertyMagnitudes[0]["flowPropertyID"]);
            }

            /**
             * Build sankey graph from loaded data
             * @param {Boolean} makeNew  Indicates if new graph should be created. False means update existing graph.
             */
            function buildGraph(makeNew) {
                try {
                    var ff = FragmentFlowService.getAll(),
                        fragmentFlows = ff.filter (filterFragmentFlow);
                    graph.isNew = makeNew;
                    if (makeNew) {
                        reverseIndex = {};
                        graph.nodes = [];
                        graph.nodes.push(createRootNode());
                        // Add a node for every flow
                        fragmentFlows.forEach(addGraphNode);
                    }
                    // Add a link for every flow. source and target are indexes into nodes array.
                    graph.links = [];
                    fragmentFlows.forEach(addGraphLink);
                    $scope.graph = graph;
                }
                catch (err) {
                    StatusService.handleFailure(err);
                }
            }

            /**
             * Get magnitude of link with a flow property
             * @param {{fragmentFlowID:Number, parentFragmentFlowID:Number, direction: String, flowPropertyMagnitudes:Array}}  link
             * @param {Number}  flowPropertyID    flow property key
             * @return {Number} The magnitude, if link has the flow property. Otherwise, null.
             */
            function getMagnitude(link, flowPropertyID) {
                var magnitude = null, flowPropertyMagnitudes = [];
                if ("flowPropertyMagnitudes" in link) {
                    flowPropertyMagnitudes = link.flowPropertyMagnitudes.filter(
                        /**
                         * @param {{flowPropertyID:number}}  lm
                         */
                            function (lm) {
                            return +lm.flowPropertyID === flowPropertyID;
                        });
                }
                if (flowPropertyMagnitudes && flowPropertyMagnitudes.length > 0) {
                    magnitude = flowPropertyMagnitudes[0].magnitude *  $scope.fragment.activityLevel;
                }
                return magnitude;
            }

            function createRootNode() {
                return {
                    nodeType: "InputOutput",
                    nodeID: 0,
                    nodeName: "Reference Flow",
                    toolTip: "InputOutput"
                }
            }

            /**
             * Add graph node for fragment flow element
             * @param {{fragmentFlowID:number}} element
             */
            function addGraphNode(element) {
                var node = {
                        nodeType: element.nodeType,
                        nodeID: element.fragmentFlowID,
                        nodeName: "",
                        toolTip: ""
                    },
                    fragFlow = FragmentFlowService.get(element.fragmentFlowID),
                    refObj , selectTip
                    ;

                if (fragFlow) {
                    node.nodeName = fragFlow["shortName"];
                }
                if (node.nodeType) {
                    node.toolTip = "" + node.nodeType + "";
                }
                if ("processID" in element) {
                    refObj = ProcessService.get(element.processID);
                    node.selectable = true;
                    selectTip = "Click to view process instance";
                } else if ("subFragmentID" in element) {
                    refObj = FragmentService.get(element.subFragmentID);
                    node.selectable = true;
                    selectTip = "Click to descend";
                }
                if (refObj) {
                    node.toolTip = node.toolTip + "
" + refObj.name + "
";
                }
                if (selectTip) {
                    node.toolTip = node.toolTip + "" + selectTip + "";
                }

                reverseIndex[element.fragmentFlowID] = graph.nodes.push(node) - 1;
            }

            /**
             * Add graph link for fragmentflow element
             * @param {{fragmentFlowID:Number, parentFragmentFlowID:Number, direction:String, flowPropertyMagnitudes:Array}} element
             * @exception Error thrown if referenced flow not found
             */
            function addGraphLink(element) {
                var link, parentIndex,
                    nodeIndex = reverseIndex[element.fragmentFlowID],
                    magnitude = getMagnitude(element, $scope.selectedFlowProperty["flowPropertyID"]),
                    value = (magnitude === null || magnitude <= 0) ? baseValue : baseValue + magnitude,
                    flow = FlowForFragmentService.get(element.flowID),
                    unit = $scope.selectedFlowProperty["referenceUnit"];

                if ("parentFragmentFlowID" in element) {
                    if (element.parentFragmentFlowID in reverseIndex) {
                        parentIndex = reverseIndex[element.parentFragmentFlowID];
                    }
                    else {
                        return;
                    }
                } else {
                    parentIndex = 0;
                }
                link = {
                    nodeID: element.fragmentFlowID,
                    flowID: element.flowID,
                    value: value
                };
                if (flow) {
                    if (magnitude) {
                        link.magnitude = magnitude;
                        link.toolTip = flow.name + " : " + magFormat(magnitude) + " " + unit;
                    } else {
                        link.toolTip = flow.name + " does not have property : " + $scope.selectedFlowProperty["name"];
                    }
                } else {
                    throw new Error ("Flow with ID, " + flowID + ", was not found.");
                }
                if (element.direction === "Input") {
                    link.source = nodeIndex;
                    link.target = parentIndex;
                } else {
                    link.source = parentIndex;
                    link.target = nodeIndex;
                }
                graph.links.push(link);
            }

            /**
             * Prepare fragment data for visualization
             */
            function visualizeFragment() {
                setFlowProperties();
                buildGraph(true);
                StatusService.stopWaiting();
            }

            /**
             * If returning from another view, restore last fragment in navigation stack.
             * Otherwise, set to top-level fragment, activity level derived from scenario.
             */
            function initScopeFragment() {
                var fragState = FragmentNavigationService.getLast();
                if (fragState) {
                    $scope.fragment = fragState;
                } else {
                    $scope.fragment = FragmentService.get($scope.scenario.topLevelFragmentID);
                    if ($scope.fragment) {
                        $scope.fragment.activityLevel = $scope.scenario["activityLevel"];
                        FragmentNavigationService.add($scope.fragment);
                    } else {
                        StatusService.handleFailure("Scenario, " + $scope.scenario.name + ", has invalid fragment ID : "
                        + $scope.scenario.topLevelFragmentID);
                    }
                }
                return $scope.fragment;
            }

            /**
             * Prepare to display sub-fragment
             * Calculate sub-fragment activity level, push current fragment on breadcrumb stack
             * @param {{subFragmentID: Number, nodeWeight: Number}} fragmentFlow  containing selected sub-fragment
             */
            function navigateSubFragment( fragmentFlow) {
                var subFragment = FragmentService.get(fragmentFlow.subFragmentID);
                if (subFragment) {
                    subFragment.activityLevel = $scope.fragment.activityLevel * fragmentFlow.nodeWeight;
                    $scope.fragment = subFragment;
                    FragmentNavigationService.add($scope.fragment);
                    getDataForFragment();
                } else {
                    StatusService.handleFailure("Invalid sub-fragment ID : " + fragmentFlow.subFragmentID);
                }
            }

            /**
             * Initialize scenario selection
             */
            function initScopeScenario() {
                var scenario;

                $scope.scenarios = ScenarioModelService.getAll();

                scenario = ScenarioModelService.get(defaultScenarioID);
                if (!scenario) {
                    // Active scenario may have been deleted
                    // Grab first one in list
                    if ($scope.scenarios.length > 0) {
                        scenario = $scope.scenarios[0];
                    }
                }
                if (scenario) {
                    if (defaultFragmentID && scenario.topLevelFragmentID !== defaultFragmentID) {
                        //
                        // Previously selected fragmentID  may no longer be the top-level fragment of the
                        // current scenario. In this case, activate first scenario selected in Fragment LCIA,
                        // if one exists.
                        //
                        var selectedScenarios = ScenarioModelService.getSelectedScenarioIDs();
                        if (selectedScenarios.length > 0) {
                            var newScenario = ScenarioModelService.get(selectedScenarios[0]);
                            if (newScenario) {
                                scenario = newScenario;
                            }
                        }
                    }
                    $scope.scenario = scenario;
                }
            }

            /**
             * Function called after requests for resources have been fulfilled.
             */
            function displayLoadedData() {
                if (!$scope.scenario) {
                    initScopeScenario();
                }
                if ($scope.scenario) {
                    ScenarioModelService.setActiveID($scope.scenario.scenarioID);
                    $scope.navigationService =
                        FragmentNavigationService.setContext($scope.scenario.scenarioID, $scope.scenario.topLevelFragmentID);
                    initScopeFragment();
                    getDataForFragment();
                }
            }

            /**
             * Update scope with flow properties and select one
             */
            function setFlowProperties() {
                //
                //  If the last flow property selection is not in the current list, reset to the default flow property,
                //  if that is in the list. Otherwise, set to first element in resource payload.
                //
                var selectedFlowProperty = $scope.selectedFlowProperty,
                    flowProperties = FlowPropertyForFragmentService.getAll();
                flowProperties.sort(FlowPropertyForFragmentService.compareByName);
                if (flowProperties) {
                    if (selectedFlowProperty) {
                        selectedFlowProperty = flowProperties.find(function (element) {
                            return (element["flowPropertyID"] === selectedFlowProperty["flowPropertyID"]);
                        });
                    }
                    if (!selectedFlowProperty) {
                        selectedFlowProperty = flowProperties.find(function (element) {
                            return (element.name === "Mass");
                        });
                        if (!selectedFlowProperty) {
                            selectedFlowProperty = flowProperties[0];
                        }
                    }
                } else {
                    selectedFlowProperty = null;
                }
                $scope.flowProperties = flowProperties;
                $scope.selectedFlowProperty = selectedFlowProperty;
            }

            /**
             * Get all data resources
             */
            function getData() {
                StatusService.startWaiting();
                $q.all([ScenarioModelService.load(), FragmentService.load(), ProcessService.load()])
                    .then(displayLoadedData,
                    StatusService.handleFailure);
            }

            /**
             * Get data resources that are filtered by fragment.
             * Called after fragment selection changes.
             * If successful, visualize selected fragment.
             */
            function getDataForFragment() {
                var fragmentID = $scope.fragment.fragmentID;
                StatusService.startWaiting();
                $q.all([FlowPropertyForFragmentService.load({fragmentID: fragmentID}),
                    FragmentFlowService.load({scenarioID: $scope.scenario.scenarioID, fragmentID: fragmentID}),
                    FlowForFragmentService.load({fragmentID: fragmentID})])
                    .then(visualizeFragment,
                    StatusService.handleFailure);
            }

            /**
             * Called when flow property selection changes.
             * Updates existing sankey graph.
             */
            $scope.onFlowPropertyChange = function () {
                buildGraph(false);
            };

            /**
             * Called when a parent fragment is selected from fragment breadcrumbs.
             * Updates fragment breadcrumbs and gets new fragment data.
             * @param fragment  Fragment selected
             * @param index     Breadcrumb index
             */
            $scope.onParentFragmentSelected = function (fragment, index) {
                $scope.fragment = fragment;
                FragmentNavigationService.setLast(index);
                getDataForFragment();
            };

            /**
             * Called when a node in sankey directive is selected.
             * The node can represent either a fragment or a process.
             * @param newVal    The selected node
             */
            function onNodeSelectionChange(newVal) {
                if (newVal) {
                    var fragmentFlow = FragmentFlowService.get(newVal.nodeID);
                    $log.info("Clicked on node with weight = " + fragmentFlow.nodeWeight);
                    switch (newVal.nodeType) {
                        case "Process" :
                            $state.go("fragment-sankey.process-instance", {
                                    scenarioID: $scope.scenario.scenarioID,
                                    fragmentID: $scope.fragment.fragmentID,
                                    fragmentFlowID: fragmentFlow.fragmentFlowID,
                                    activity: $scope.fragment.activityLevel *
                                    fragmentFlow.nodeWeight
                                }
                            );
                            break;
                        case "Fragment" :
                            navigateSubFragment(fragmentFlow);
                            break;
                    }
                }
            }

            /**
             * Get flow table content
             * For each Sankey link provided, get
             * flow name, magnitude and unit associated with selected flow property.
             * If the link does have the selected flow property, display
             * magnitude and unit for the
             * reference flow property.
             *
             * @param {Array}  nodeLinks     Sankey links
             * @return {Array}  Data for display in table
             */
            function getFlowRows(nodeLinks) {
                var flowData = [];

                nodeLinks.forEach( function (l) {
                    if ("flowID" in l) {
                        var flow = FlowForFragmentService.get(l.flowID),
                            flowPropertyID = $scope.selectedFlowProperty["flowPropertyID"],
                            magnitude = l.magnitude,
                            unit = "";
                        if (magnitude) {
                            unit = $scope.selectedFlowProperty["referenceUnit"];
                        } else  {
                            var fp, ff;
                            ff = FragmentFlowService.get(l.nodeID);
                            flowPropertyID = flow["referenceFlowPropertyID"];
                            magnitude = getMagnitude(ff, flowPropertyID);
                            fp = FlowPropertyForFragmentService.get(flowPropertyID);
                            if (fp) {
                               unit = fp["referenceUnit"];
                            }
                        }
                        flowData.push({ name: flow.name, magnitude: magnitude, unit: unit });
                    }
                });
                return flowData;
            }

            function onMouseOverNode(node) {
                if (node) {
                    $scope.inputFlows = getFlowRows(node.targetLinks);
                    $scope.outputFlows = getFlowRows(node.sourceLinks);
                }
            }

            function getSelectedFragmentID() {
                var selectedTopLevelFragmentID = ScenarioModelService.getSelectedTopLevelFragmentID();
                if (selectedTopLevelFragmentID) {
                    defaultFragmentID = selectedTopLevelFragmentID;
                }
            }

            function getActiveScenarioID() {
                var activeID = ScenarioModelService.getActiveID();
                if (activeID) {
                    defaultScenarioID = activeID;
                }
            }

            function getStateParams() {
                if ( $stateParams.hasOwnProperty("scenarioID") && $stateParams.scenarioID !== undefined) {
                    defaultScenarioID = +$stateParams.scenarioID;
                }
                if ($stateParams.hasOwnProperty("fragmentID") && $stateParams.fragmentID !== undefined) {
                    defaultFragmentID = +$stateParams.fragmentID;
                }
            }

            getSelectedFragmentID();
            getActiveScenarioID();
            getStateParams();
            getData();
        }]);<|endoftext|>


<commit_before>var github = (function(){
  function render(target, repos){
    var i = 0, fragment = '', t = $(target)[0];

    for(i = 0; i < repos.length; i++) {
      fragment += '
'+repos[i].name+'
'+repos[i].description+'

';
    }
    t.innerHTML = fragment;
  }
  return {
    showRepos: function(options){
      var feed = new jXHR();
      feed.onerror = function (msg,url) {
        $(options.target + ' li.loading').addClass('error').text("Error loading feed");
      };
      feed.onreadystatechange = function(data) {
        if (feed.readyState === 4) {
          var repos = [];
          for (var i = 0; i < data.repositories.length; i++){
            if (options.skip_forks && data.repositories[i].fork) { continue; }
            repos.push(data.repositories[i]);
          }
          repos.sort(function(a, b) {
            var aDate = new Date(a.pushed_at).valueOf(),
                bDate = new Date(b.pushed_at).valueOf();

            if (aDate === bDate) { return 0; }
            return aDate > bDate ? -1 : 1;
          });

          if (options.count) { repos.splice(options.count); }
          render(options.target, repos);
        }
      };
      feed.open("GET","http://github.com/api/v2/json/repos/show/"+options.user+"?callback=?");
      feed.send();
    }
  };
})();<commit_msg>updated github.js to use reqwest.js with Ender<commit_after>var github = (function(){
  function render(target, repos){
    var i = 0, fragment = '', t = $(target)[0];

    for(i = 0; i < repos.length; i++) {
      fragment += '
'+repos[i].name+'
'+repos[i].description+'

';
    }
    t.innerHTML = fragment;
  }
  return {
    showRepos: function(options){
      $.ajax({
          url: "http://github.com/api/v2/json/repos/show/"+options.user+"?callback=?"
        , type: 'jsonp'
        , error: function (err) { $(options.target + ' li.loading').addClass('error').text("Error loading feed"); }
        , success: function(data) {
          var repos = [];
          for (var i = 0; i < data.repositories.length; i++){
            if (options.skip_forks && data.repositories[i].fork) { continue; }
            repos.push(data.repositories[i]);
          }
          repos.sort(function(a, b) {
            var aDate = new Date(a.pushed_at).valueOf(),
                bDate = new Date(b.pushed_at).valueOf();

            if (aDate === bDate) { return 0; }
            return aDate > bDate ? -1 : 1;
          });

          if (options.count) { repos.splice(options.count); }
          render(options.target, repos);
        }
      })
    }
  };
})();
<|endoftext|>


<commit_before>glu.defView('todo.todoitem', {
    xtype:'container',
    layout:'hbox',
    isHovered : '@{focused}',
    height :30,
    hidden : '@{!isVisible}',
    items:[
        {
            xtype : 'checkbox',
            value : '@{done}',
            width : 20
        },
        {
            xtype:'displayfield',
            width: 200,
            disabledCls : 'todo-list-done',
            disabled : '@{done}',
            value : {
                value:'@{text}',
                alignment : 'l-l?',
                field : {
                    xtype: 'textfield'
                }
            }
        },
        {
            xtype : 'button',
            hidden : '@{!removeIsVisible}',
            overCls : '',
            handler : '@{remove}'
        }
    ]
});<commit_msg>Playing around with todoitem layout<commit_after>glu.defView('todo.todoitem', {
    xtype:'container',
    layout:'hbox',
    isHovered : '@{focused}',
    height :30,
    hidden : '@{!isVisible}',
    items:[
        {
            xtype : 'checkbox',
            value : '@{done}',
            width : 20
        },
        {
            xtype:'displayfield',
            width:300,  //flex isn't working for some reason...
            disabledCls : 'todo-list-done',
            disabled : '@{done}',
            value : {
                value:'@{text}',
                alignment : 'l-l?',
                field : {
                    xtype: 'textfield'
                }
            }
        },
        {
            xtype : 'button',
            width : 20,
            hidden : '@{!removeIsVisible}',
            overCls : '',
            handler : '@{remove}'
        }
    ]
});<|endoftext|>