<commit_before>/*
  This function traverses the folder tree and recreates the folder structure
    in the new folder

  arguments:

     folderId is the ID of the root src folder

     newFolderName is a string representing the name of the new (copied) folder

     folderTree is an array
        each object is an array with two elements
        first element is original folder Id
        second element is new folder Id, corresponding to original
        third element is the path name for the folder

     copyPermissions is a boolean indicating whether or not to copy original sharing permissions

*/

var $ = jQuery = require('jquery');
var copyFiles = require('./copyFiles.js');
var picker = require('./picker');

exports.create = function() {

  var selectedFolder = picker.getSelectedFolder();
  var folderId = selectedFolder.id;
  var parentId = selectedFolder.parentId;

  var folderTree = [];
  var newFolderName = $("#newFolder").val();
  var copyPermissions = $("#permissions-group input:checked").val() == "yes" ? true : false;
  var dest = $("#destination-group input:checked").val();

  return google.script.run
    .withSuccessHandler(function(results) {
        // folder tree is an array
        // each object is an array with two elements
        // first element is original folder Id
        // second element is new folder Id, corresponding to original
        var folderId = results[0];
        var folderTree = results[1];
        var copyPermissions = results[2];
        var added = results[3];
        var statusTable = "";

        // Update status for user
        $("#status-title").html("Folders structure copied successfully. Copying files ");

        // build status-table
        for (i = 0; i < folderTree.length; i++) {
          statusTable += "
";
          statusTable += "" + folderTree[i][2] + "	";
          statusTable += "Waiting...	";
          statusTable += "
";
        }
        $(statusTable).hide().appendTo("#status-table").show('blind');
        // $("#status-table").append(statusTable);

        // When complete, begin copyFiles routine
        copyFiles.copy(folderTree, folderId, copyPermissions, added);
    })
    .withFailureHandler(function(msg) {
      var errormsg = "
Error: There was an error creating folder structure.
";
      errormsg += "Error message: " + msg + ".
";
      errormsg += "Please try again. Make sure you have correct permissions to copy this folder, and please input the entire sharing URL, not just the folder ID
";
      $("#errors").append(errormsg);
      $("#status-title").html("Error");
    })
    .createFolders(folderId, newFolderName, parentId, folderTree, copyPermissions, [], dest);
}<commit_msg>adjusted variable declarations to handle results as an object instead of array<commit_after>/*
  This function traverses the folder tree and recreates the folder structure
    in the new folder

  arguments:

     folderId is the ID of the root src folder

     newFolderName is a string representing the name of the new (copied) folder

     folderTree is an array
        each object is an array with two elements
        first element is original folder Id
        second element is new folder Id, corresponding to original
        third element is the path name for the folder

     copyPermissions is a boolean indicating whether or not to copy original sharing permissions

*/

var $ = jQuery = require('jquery');
var copyFiles = require('./copyFiles.js');
var picker = require('./picker');

exports.create = function() {

  var selectedFolder = picker.getSelectedFolder();
  var folderId = selectedFolder.id;
  var parentId = selectedFolder.parentId;

  var folderTree = [];
  var newFolderName = $("#newFolder").val();
  var copyPermissions = $("#permissions-group input:checked").val() == "yes" ? true : false;
  var dest = $("#destination-group input:checked").val();

  return google.script.run
    .withSuccessHandler(function(results) {
        // folder tree is an array
        // each object is an array with two elements
        // first element is original folder Id
        // second element is new folder Id, corresponding to original
        var folderId = results.folderId;
        var folderTree = results.folderTree;
        var copyPermissions = results.copyPermissions;
        var added = results.added;
        var statusTable = "";

        // Update status for user
        $("#status-title").html("Folders structure copied successfully. Copying files ");

        // build status-table
        for (i = 0; i < folderTree.length; i++) {
          statusTable += "
";
          statusTable += "" + folderTree[i][2] + "	";
          statusTable += "Waiting...	";
          statusTable += "
";
        }
        $(statusTable).hide().appendTo("#status-table").show('blind');

        // When complete, begin copyFiles routine
        copyFiles.copy(folderTree, folderId, copyPermissions, added);
    })
    .withFailureHandler(function(msg) {
      var errormsg = "
Error: There was an error creating folder structure.
";
      errormsg += "Error message: " + msg + ".
";
      errormsg += "Please try again. Make sure you have correct permissions to copy this folder, and please input the entire sharing URL, not just the folder ID
";
      $("#errors").append(errormsg);
      $("#status-title").html("Error");
    })
    .createFolders(folderId, newFolderName, parentId, folderTree, copyPermissions, [], dest);
}<|endoftext|>


<commit_before>/**
 * Each section of the site has its own module. It probably also has
 * submodules, though this boilerplate is too simple to demonstrate it. Within
 * `src/app/home`, however, could exist several additional folders representing
 * additional modules that would then be listed as dependencies of this one.
 * For example, a `note` section could have the submodules `note.create`,
 * `note.delete`, `note.edit`, etc.
 *
 * Regardless, so long as dependencies are managed correctly, the build process
 * will automatically take take of the rest.
 *
 * The dependencies block here is also where component dependencies should be
 * specified, as shown below.
 */
angular.module( 'ngRuter.home', [
  'ui.router'
])

/**
 * Each section or module of the site can also have its own routes. AngularJS
 * will handle ensuring they are all available at run-time, but splitting it
 * this way makes each module more "self-contained".
 */
.config(function config( $stateProvider ) {
  $stateProvider.state( 'home', {
    url: '/home',
    views: {
      "main": {
        controller: 'HomeCtrl',
        templateUrl: 'home/home.tpl.html'
      }
    },
    data:{ pageTitle: 'Train RealTime' }
  });
})

.filter('fromNow', function() {
        return function(dateString) {
            //moment.lang('nb');
            return moment(dateString).fromNow();
        };
 })

 .filter('isoInterval', function() {
    return function(isoInterval) {
      var delay = moment.duration(isoInterval);
      if (delay.asSeconds() === 0) {
        return "On time";
      } else {
        return delay.humanize();
      }
    };
 })

 .filter('deviations', function() {
    return function(deviations) {
      if (deviations.length > 0) {
        return deviations.length;
      } else {
        return "";
      }
    };
 })

/**
 * And of course we define a controller for our route.
 */
.controller( 'HomeCtrl', function HomeController( $scope, $http ) {
})

/**
 * Controller for real time info.
 */
.controller( 'myBusStopCtrl', function myBusStopCtrl( $scope, $http, $timeout ) {
  $scope.realTimeData = [{name : "a"}, {name:"b"}];
  $scope.currentStation = {name : "Lysaker[tog]", id : "3012550"};

  getStationUrl = function(id) {
    return "http://reis.trafikanten.no/reisrest/realtime/getrealtimedata/" + id + "?callback=JSON_CALLBACK";
  };

  getRealTimeData = function() {
    $http.jsonp(getStationUrl($scope.currentStation.id))
          .success(function(data){
              $scope.realTimeData = data;
          });
  };
  $scope.timeInMs = 1;

  var interval = 5000;
  var countUp = function() {
          getRealTimeData();
          $scope.timeInMs+= interval;
          $timeout(countUp, interval);
  };

  $timeout(countUp, interval);
  getRealTimeData();

})

;

<commit_msg>Fixed error if deviations was not defined<commit_after>/**
 * Each section of the site has its own module. It probably also has
 * submodules, though this boilerplate is too simple to demonstrate it. Within
 * `src/app/home`, however, could exist several additional folders representing
 * additional modules that would then be listed as dependencies of this one.
 * For example, a `note` section could have the submodules `note.create`,
 * `note.delete`, `note.edit`, etc.
 *
 * Regardless, so long as dependencies are managed correctly, the build process
 * will automatically take take of the rest.
 *
 * The dependencies block here is also where component dependencies should be
 * specified, as shown below.
 */
angular.module( 'ngRuter.home', [
  'ui.router'
])

/**
 * Each section or module of the site can also have its own routes. AngularJS
 * will handle ensuring they are all available at run-time, but splitting it
 * this way makes each module more "self-contained".
 */
.config(function config( $stateProvider ) {
  $stateProvider.state( 'home', {
    url: '/home',
    views: {
      "main": {
        controller: 'HomeCtrl',
        templateUrl: 'home/home.tpl.html'
      }
    },
    data:{ pageTitle: 'Train RealTime' }
  });
})

.filter('fromNow', function() {
        return function(dateString) {
            //moment.lang('nb');
            return moment(dateString).fromNow();
        };
 })

 .filter('isoInterval', function() {
    return function(isoInterval) {
      var delay = moment.duration(isoInterval);
      if (delay.asSeconds() === 0) {
        return "On time";
      } else {
        return delay.humanize();
      }
    };
 })

 .filter('deviations', function() {
    return function(deviations) {
      if (deviations != null && deviations.length > 0) {
        return deviations.length;
      } else {
        return "";
      }
    };
 })

/**
 * And of course we define a controller for our route.
 */
.controller( 'HomeCtrl', function HomeController( $scope, $http ) {
})

/**
 * Controller for real time info.
 */
.controller( 'myBusStopCtrl', function myBusStopCtrl( $scope, $http, $timeout ) {
  $scope.realTimeData = [{name : "a"}, {name:"b"}];
  $scope.currentStation = {name : "Lysaker[tog]", id : "3012550"};

  getStationUrl = function(id) {
    return "http://reis.trafikanten.no/reisrest/realtime/getrealtimedata/" + id + "?callback=JSON_CALLBACK";
  };

  getRealTimeData = function() {
    $http.jsonp(getStationUrl($scope.currentStation.id))
          .success(function(data){
              $scope.realTimeData = data;
          });
  };
  $scope.timeInMs = 1;

  var interval = 5000;
  var countUp = function() {
          getRealTimeData();
          $scope.timeInMs+= interval;
          $timeout(countUp, interval);
  };

  $timeout(countUp, interval);
  getRealTimeData();

})

;

<|endoftext|>


<commit_before>var moment = require('moment');
require('moment-timezone');

exports.index = function (req, res) {
  res.render(res.locals.brigade.theme.slug + '/views/matching', {
    view: 'matching',
    title: 'Matching Hat',
    brigade: res.locals.brigade,
  });
}
<commit_msg>Change to the matching controller<commit_after>var moment = require('moment');
require('moment-timezone');

exports.index = function (req, res) {
  res.render(res.locals.brigade.theme.slug + '/views/matching', {
    view: 'matching',
    title: 'Matching Hat',
/**
/* send the matching output object back to matching.jade
   using "projects"                                     */
    projects: res.locals.output,
  });
}
<|endoftext|>


<commit_before>'use strict';

var crypto = require('crypto'),
    http = require('http');

function AvatarCache(options) {
    this.core = options.core;
    this.avatars = {};

    this.get = this.get.bind(this);
    this.add = this.add.bind(this);
}

AvatarCache.prototype.get = function(userId) {
    return this.avatars[userId];
};

AvatarCache.prototype.add = function(user) {
    var userId = (user.id || user._id).toString();
    var url = 'http://www.gravatar.com/avatar/' + user.avatar + '?s=64';

    http.get(url, function(response) {
        if (response.statusCode !== 200) {
            return;
        }

        var buffers = [];

        response.on('data', function(buffer) {
            buffers.push(buffer);
        });

        response.on('end', function() {
            var buffer = Buffer.concat(buffers);

            this.avatars[userId] = {
                base64: buffer.toString('base64'),
                sha1: crypto.createHash('sha1').update(buffer).digest('hex')
            };

            this.core.emit('avatar-cache:update', user);
        }.bind(this));
    }.bind(this));
};

module.exports = AvatarCache;
<commit_msg>Handling error when on Avatar caching. Ignoring Exception as lack of Avatar in cache is handled by calls to cache itseld<commit_after>'use strict';

var crypto = require('crypto'),
    http = require('http');

function AvatarCache(options) {
    this.core = options.core;
    this.avatars = {};

    this.get = this.get.bind(this);
    this.add = this.add.bind(this);
}

AvatarCache.prototype.get = function(userId) {
    return this.avatars[userId];
};

AvatarCache.prototype.add = function(user) {
    var userId = (user.id || user._id).toString();
    var url = 'http://www.gravatar.com/avatar/' + user.avatar + '?s=64';

    http.get(url, function(response) {
        if (response.statusCode !== 200) {
            return;
        }

        var buffers = [];

        response.on('data', function(buffer) {
            buffers.push(buffer);
        });

        response.on('end', function() {
            var buffer = Buffer.concat(buffers);

            this.avatars[userId] = {
                base64: buffer.toString('base64'),
                sha1: crypto.createHash('sha1').update(buffer).digest('hex')
            };

            this.core.emit('avatar-cache:update', user);
        }.bind(this));
    }.bind(this)).on('error', function(e){
    });
};

module.exports = AvatarCache;
<|endoftext|>


<commit_before>import GLBoost from './../globals'
import Vector3 from './Vector3'

export default class Matrix33 {

  constructor() {
    this.m = [];
    if (arguments.length >= 9) {
      this.setComponents.apply(this, arguments);
    }
    else {
      this.identity();
    }
  }

  setComponents(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
    this.m00 = m00; this.m01 = m01; this.m02 = m02;
    this.m10 = m10; this.m11 = m11; this.m12 = m12;
    this.m20 = m20; this.m21 = m21; this.m22 = m22;

    return this;
  }

  /**
   * 単位行列にする
   */
  identity() {
    this.setComponents(
      1, 0, 0,
      0, 1, 0,
      0, 0, 1
    );
    return this;
  }

  /**
   * 単位行列にする（static版）
   */
  static identity() {
    return new Matrix33(
      1, 0, 0,
      0, 1, 0,
      0, 0, 1
    );
  }

  /**
   * Create X oriented Rotation Matrix
   */
  rotateX(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return this.setComponents(
      1, 0, 0,
      0, cos, -sin,
      0, sin, cos
    );
  }
  /**
   * Create X oriented Rotation Matrix
   */
  static rotateX(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      1, 0, 0,
      0, cos, -sin,
      0, sin, cos
    );
  }

  /**
   * Create Y oriented Rotation Matrix
   */
  rotateY(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    this.setComponents(
      cos, 0, sin,
      0, 1, 0,
      -sin, 0, cos
    );
    return this;
  }
  /**
   * Create Y oriented Rotation Matrix
   */
  static rotateY(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      cos, 0, sin,
      0, 1, 0,
      -sin, 0, cos
    );
  }

  /**
   * Create Z oriented Rotation Matrix
   */
  rotateZ(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return this.setComponents(
      cos, -sin, 0,
      sin, cos, 0,
      0, 0, 1
    );
  }
  /**
   * Create Z oriented Rotation Matrix
   */
  static rotateZ(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      cos, -sin, 0,
      sin, cos, 0,
      0, 0, 1
    );
  }

  /**
   * ゼロ行列
   */
  zero() {
    this.setComponents(0, 0, 0, 0, 0, 0, 0, 0, 0);
    return this;
  }

  static zero() {
    return new Matrix33(0, 0, 0, 0, 0, 0, 0, 0, 0);
  }

  flatten() {
    return this.m;
  }

  _swap(l, r) {
    this.m[r] = [this.m[l], this.m[l] = this.m[r]][0]; // Swap
  }

  /**
   * 転置
   */
  transpose() {
    this._swap(1, 3);
    this._swap(2, 6);
    this._swap(5, 8);

    return this;
  }

  /**
   * 転置（static版）
   */
  static transpose(mat) {

    var mat_t = new Matrix33(
      mat.m00, mat.m10, mat.m20,
      mat.m01, mat.m11, mat.m21,
      mat.m02, mat.m12, mat.m22
    );

    return mat_t;
  }

  multiplyVector(vec) {
    var x = this.m00*vec.x + this.m01*vec.y + this.m02*vec.z;
    var y = this.m10*vec.x + this.m11*vec.y + this.m12*vec.z;
    var z = this.m20*vec.x + this.m21*vec.y + this.m22*vec.z;

    return new Vector3(x, y, z);
  }

  /**
   * 行列同士の乗算
   */
  multiply(mat) {
    var m00 = this.m00*mat.m00 + this.m01*mat.m10 + this.m02*mat.m20;
    var m01 = this.m00*mat.m01 + this.m01*mat.m11 + this.m02*mat.m21;
    var m02 = this.m00*mat.m02 + this.m01*mat.m12 + this.m02*mat.m22;

    var m10 = this.m10*mat.m00 + this.m11*mat.m10 + this.m12*mat.m20;
    var m11 = this.m10*mat.m01 + this.m11*mat.m11 + this.m12*mat.m21;
    var m12 = this.m10*mat.m02 + this.m11*mat.m12 + this.m12*mat.m22;

    var m20 = this.m20*mat.m00 + this.m21*mat.m10 + this.m22*mat.m20;
    var m21 = this.m20*mat.m01 + this.m21*mat.m11 + this.m22*mat.m21;
    var m22 = this.m20*mat.m02 + this.m21*mat.m12 + this.m22*mat.m22;

    return this.setComponents(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  /**
   * 行列同士の乗算（static版）
   */
  static multiply(l_m, r_m) {
    var m00 = l_m.m00*r_m.m00 + l_m.m01*r_m.m10 + l_m.m02*r_m.m20;
    var m10 = l_m.m10*r_m.m00 + l_m.m11*r_m.m10 + l_m.m12*r_m.m20;
    var m20 = l_m.m20*r_m.m00 + l_m.m21*r_m.m10 + l_m.m22*r_m.m20;

    var m01 = l_m.m00*r_m.m01 + l_m.m01*r_m.m11 + l_m.m02*r_m.m21;
    var m11 = l_m.m10*r_m.m01 + l_m.m11*r_m.m11 + l_m.m12*r_m.m21;
    var m21 = l_m.m20*r_m.m01 + l_m.m21*r_m.m11 + l_m.m22*r_m.m21;

    var m02 = l_m.m00*r_m.m02 + l_m.m01*r_m.m12 + l_m.m02*r_m.m22;
    var m12 = l_m.m10*r_m.m02 + l_m.m11*r_m.m12 + l_m.m12*r_m.m22;
    var m22 = l_m.m20*r_m.m02 + l_m.m21*r_m.m12 + l_m.m22*r_m.m22;

    return new Matrix33(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  determinant() {
    return this.m00*this.m11*this.m22 + this.m10*this.m21*this.m02 + this.m20*this.m01*this.m12
      - this.m00*this.m21*this.m12 - this.m20*this.m11*this.m02 - this.m10*this.m01*this.m22;
  }

  static determinant(mat) {
    return mat.m00*mat.m11*mat.m22 + mat.m10*mat.m21*mat.m02 + mat.m20*mat.m01*mat.m12
      - mat.m00*mat.m21*mat.m12 - mat.m20*mat.m11*mat.m02 - mat.m10*mat.m01*mat.m22;
  }

  invert() {
    var det = this.determinant();
    var m00 = (this.m11*this.m22 - this.m12*this.m21) / det;
    var m01 = (this.m02*this.m21 - this.m01*this.m22) / det;
    var m02 = (this.m01*this.m12 - this.m02*this.m11) / det;
    var m10 = (this.m12*this.m20 - this.m10*this.m22) / det;
    var m11 = (this.m00*this.m22 - this.m02*this.m20) / det;
    var m12 = (this.m02*this.m10 - this.m00*this.m12) / det;
    var m20 = (this.m10*this.m21 - this.m11*this.m20) / det;
    var m21 = (this.m01*this.m20 - this.m00*this.m21) / det;
    var m22 = (this.m00*this.m11 - this.m01*this.m10) / det;

    return new Matrix33(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  static invert(mat) {
    var det = mat.determinant();
    var m00 = (mat.m11*mat.m22 - mat.m12*mat.m21) / det;
    var m01 = (mat.m02*mat.m21 - mat.m01*mat.m22) / det;
    var m02 = (mat.m01*mat.m12 - mat.m02*mat.m11) / det;
    var m10 = (mat.m12*mat.m20 - mat.m10*mat.m22) / det;
    var m11 = (mat.m00*mat.m22 - mat.m02*mat.m20) / det;
    var m12 = (mat.m02*mat.m10 - mat.m00*mat.m12) / det;
    var m20 = (mat.m10*mat.m21 - mat.m11*mat.m20) / det;
    var m21 = (mat.m01*mat.m20 - mat.m00*mat.m21) / det;
    var m22 = (mat.m00*mat.m11 - mat.m01*mat.m10) / det;

    return new Matrix33(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  set m00(val) {
    this.m[0] = val;
  }

  get m00() {
    return this.m[0];
  }

  set m01(val) {
    this.m[1] = val;
  }

  get m01() {
    return this.m[1];
  }

  set m02(val) {
    this.m[2] = val;
  }

  get m02() {
    return this.m[2];
  }

  set m10(val) {
    this.m[3] = val;
  }

  get m10() {
    return this.m[3];
  }

  set m11(val) {
    this.m[4] = val;
  }

  get m11() {
    return this.m[4];
  }

  set m12(val) {
    this.m[5] = val;
  }

  get m12() {
    return this.m[5];
  }

  set m20(val) {
    this.m[6  ] = val;
  }

  get m20() {
    return this.m[6];
  }

  set m21(val) {
    this.m[7] = val;
  }

  get m21() {
    return this.m[7];
  }

  set m22(val) {
    this.m[8] = val;
  }

  get m22() {
    return this.m[8];
  }

}

GLBoost["Matrix33"] = Matrix33;
<commit_msg>fix a bit of Matrix33.<commit_after>import GLBoost from './../globals'
import Vector3 from './Vector3'

export default class Matrix33 {

  constructor() {
    this.m = [];
    if (arguments.length >= 9) {
      this.setComponents.apply(this, arguments);
    }
    else {
      this.identity();
    }
  }

  setComponents(m00, m01, m02, m10, m11, m12, m20, m21, m22) {
    this.m00 = m00; this.m01 = m01; this.m02 = m02;
    this.m10 = m10; this.m11 = m11; this.m12 = m12;
    this.m20 = m20; this.m21 = m21; this.m22 = m22;

    return this;
  }

  /**
   * 単位行列にする
   */
  identity() {
    this.setComponents(
      1, 0, 0,
      0, 1, 0,
      0, 0, 1
    );
    return this;
  }

  /**
   * 単位行列にする（static版）
   */
  static identity() {
    return new Matrix33(
      1, 0, 0,
      0, 1, 0,
      0, 0, 1
    );
  }

  /**
   * Create X oriented Rotation Matrix
   */
  rotateX(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return this.setComponents(
      1, 0, 0,
      0, cos, -sin,
      0, sin, cos
    );
  }
  /**
   * Create X oriented Rotation Matrix
   */
  static rotateX(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      1, 0, 0,
      0, cos, -sin,
      0, sin, cos
    );
  }

  /**
   * Create Y oriented Rotation Matrix
   */
  rotateY(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    this.setComponents(
      cos, 0, sin,
      0, 1, 0,
      -sin, 0, cos
    );
    return this;
  }
  /**
   * Create Y oriented Rotation Matrix
   */
  static rotateY(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      cos, 0, sin,
      0, 1, 0,
      -sin, 0, cos
    );
  }

  /**
   * Create Z oriented Rotation Matrix
   */
  rotateZ(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return this.setComponents(
      cos, -sin, 0,
      sin, cos, 0,
      0, 0, 1
    );
  }
  /**
   * Create Z oriented Rotation Matrix
   */
  static rotateZ(radian) {
    var cos = Math.cos(radian);
    var sin = Math.sin(radian);
    return new Matrix33(
      cos, -sin, 0,
      sin, cos, 0,
      0, 0, 1
    );
  }

  /**
   * ゼロ行列
   */
  zero() {
    this.setComponents(0, 0, 0, 0, 0, 0, 0, 0, 0);
    return this;
  }

  static zero() {
    return new Matrix33(0, 0, 0, 0, 0, 0, 0, 0, 0);
  }

  flatten() {
    return this.m;
  }

  _swap(l, r) {
    this.m[r] = [this.m[l], this.m[l] = this.m[r]][0]; // Swap
  }

  /**
   * 転置
   */
  transpose() {
    this._swap(1, 3);
    this._swap(2, 6);
    this._swap(5, 8);

    return this;
  }

  /**
   * 転置（static版）
   */
  static transpose(mat) {

    var mat_t = new Matrix33(
      mat.m00, mat.m10, mat.m20,
      mat.m01, mat.m11, mat.m21,
      mat.m02, mat.m12, mat.m22
    );

    return mat_t;
  }

  multiplyVector(vec) {
    var x = this.m00*vec.x + this.m01*vec.y + this.m02*vec.z;
    var y = this.m10*vec.x + this.m11*vec.y + this.m12*vec.z;
    var z = this.m20*vec.x + this.m21*vec.y + this.m22*vec.z;

    return new Vector3(x, y, z);
  }

  /**
   * 行列同士の乗算
   */
  multiply(mat) {
    var m00 = this.m00*mat.m00 + this.m01*mat.m10 + this.m02*mat.m20;
    var m01 = this.m00*mat.m01 + this.m01*mat.m11 + this.m02*mat.m21;
    var m02 = this.m00*mat.m02 + this.m01*mat.m12 + this.m02*mat.m22;

    var m10 = this.m10*mat.m00 + this.m11*mat.m10 + this.m12*mat.m20;
    var m11 = this.m10*mat.m01 + this.m11*mat.m11 + this.m12*mat.m21;
    var m12 = this.m10*mat.m02 + this.m11*mat.m12 + this.m12*mat.m22;

    var m20 = this.m20*mat.m00 + this.m21*mat.m10 + this.m22*mat.m20;
    var m21 = this.m20*mat.m01 + this.m21*mat.m11 + this.m22*mat.m21;
    var m22 = this.m20*mat.m02 + this.m21*mat.m12 + this.m22*mat.m22;

    return this.setComponents(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  /**
   * 行列同士の乗算（static版）
   */
  static multiply(l_m, r_m) {
    var m00 = l_m.m00*r_m.m00 + l_m.m01*r_m.m10 + l_m.m02*r_m.m20;
    var m10 = l_m.m10*r_m.m00 + l_m.m11*r_m.m10 + l_m.m12*r_m.m20;
    var m20 = l_m.m20*r_m.m00 + l_m.m21*r_m.m10 + l_m.m22*r_m.m20;

    var m01 = l_m.m00*r_m.m01 + l_m.m01*r_m.m11 + l_m.m02*r_m.m21;
    var m11 = l_m.m10*r_m.m01 + l_m.m11*r_m.m11 + l_m.m12*r_m.m21;
    var m21 = l_m.m20*r_m.m01 + l_m.m21*r_m.m11 + l_m.m22*r_m.m21;

    var m02 = l_m.m00*r_m.m02 + l_m.m01*r_m.m12 + l_m.m02*r_m.m22;
    var m12 = l_m.m10*r_m.m02 + l_m.m11*r_m.m12 + l_m.m12*r_m.m22;
    var m22 = l_m.m20*r_m.m02 + l_m.m21*r_m.m12 + l_m.m22*r_m.m22;

    return new Matrix33(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  determinant() {
    return this.m00*this.m11*this.m22 + this.m10*this.m21*this.m02 + this.m20*this.m01*this.m12
      - this.m00*this.m21*this.m12 - this.m20*this.m11*this.m02 - this.m10*this.m01*this.m22;
  }

  static determinant(mat) {
    return mat.m00*mat.m11*mat.m22 + mat.m10*mat.m21*mat.m02 + mat.m20*mat.m01*mat.m12
      - mat.m00*mat.m21*mat.m12 - mat.m20*mat.m11*mat.m02 - mat.m10*mat.m01*mat.m22;
  }

  invert() {
    var det = this.determinant();
    var m00 = (this.m11*this.m22 - this.m12*this.m21) / det;
    var m01 = (this.m02*this.m21 - this.m01*this.m22) / det;
    var m02 = (this.m01*this.m12 - this.m02*this.m11) / det;
    var m10 = (this.m12*this.m20 - this.m10*this.m22) / det;
    var m11 = (this.m00*this.m22 - this.m02*this.m20) / det;
    var m12 = (this.m02*this.m10 - this.m00*this.m12) / det;
    var m20 = (this.m10*this.m21 - this.m11*this.m20) / det;
    var m21 = (this.m01*this.m20 - this.m00*this.m21) / det;
    var m22 = (this.m00*this.m11 - this.m01*this.m10) / det;

    return this.setComponents(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  static invert(mat) {
    var det = mat.determinant();
    var m00 = (mat.m11*mat.m22 - mat.m12*mat.m21) / det;
    var m01 = (mat.m02*mat.m21 - mat.m01*mat.m22) / det;
    var m02 = (mat.m01*mat.m12 - mat.m02*mat.m11) / det;
    var m10 = (mat.m12*mat.m20 - mat.m10*mat.m22) / det;
    var m11 = (mat.m00*mat.m22 - mat.m02*mat.m20) / det;
    var m12 = (mat.m02*mat.m10 - mat.m00*mat.m12) / det;
    var m20 = (mat.m10*mat.m21 - mat.m11*mat.m20) / det;
    var m21 = (mat.m01*mat.m20 - mat.m00*mat.m21) / det;
    var m22 = (mat.m00*mat.m11 - mat.m01*mat.m10) / det;

    return new Matrix33(
      m00, m01, m02,
      m10, m11, m12,
      m20, m21, m22
    );
  }

  set m00(val) {
    this.m[0] = val;
  }

  get m00() {
    return this.m[0];
  }

  set m01(val) {
    this.m[1] = val;
  }

  get m01() {
    return this.m[1];
  }

  set m02(val) {
    this.m[2] = val;
  }

  get m02() {
    return this.m[2];
  }

  set m10(val) {
    this.m[3] = val;
  }

  get m10() {
    return this.m[3];
  }

  set m11(val) {
    this.m[4] = val;
  }

  get m11() {
    return this.m[4];
  }

  set m12(val) {
    this.m[5] = val;
  }

  get m12() {
    return this.m[5];
  }

  set m20(val) {
    this.m[6  ] = val;
  }

  get m20() {
    return this.m[6];
  }

  set m21(val) {
    this.m[7] = val;
  }

  get m21() {
    return this.m[7];
  }

  set m22(val) {
    this.m[8] = val;
  }

  get m22() {
    return this.m[8];
  }

}

GLBoost["Matrix33"] = Matrix33;
<|endoftext|>


<commit_before>'use strict';

const {bundleTypes, moduleTypes} = require('./bundles');
const reactVersion = require('../../package.json').version;

const {
  UMD_DEV,
  UMD_PROD,
  UMD_PROFILING,
  NODE_DEV,
  NODE_PROD,
  NODE_PROFILING,
  FB_WWW_DEV,
  FB_WWW_PROD,
  FB_WWW_PROFILING,
  RN_OSS_DEV,
  RN_OSS_PROD,
  RN_OSS_PROFILING,
  RN_FB_DEV,
  RN_FB_PROD,
  RN_FB_PROFILING,
} = bundleTypes;

const {RECONCILER} = moduleTypes;

const license = ` * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.`;

const wrappers = {
  /***************** UMD_DEV *****************/
  [UMD_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

${source}`;
  },

  /***************** UMD_PROD *****************/
  [UMD_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${source}`;
  },

  /***************** UMD_PROFILING *****************/
  [UMD_PROFILING](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${source}`;
  },

  /***************** NODE_DEV *****************/
  [NODE_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}

if (process.env.NODE_ENV !== "production") {
  (function() {
${source}
  })();
}`;
  },

  /***************** NODE_PROD *****************/
  [NODE_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}
${source}`;
  },

  /***************** NODE_PROFILING *****************/
  [NODE_PROFILING](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}
${source}`;
  },

  /****************** FB_WWW_DEV ******************/
  [FB_WWW_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * @preserve-invariant-messages
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** FB_WWW_PROD ******************/
  [FB_WWW_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * @preserve-invariant-messages
 */

${source}`;
  },

  /****************** FB_WWW_PROFILING ******************/
  [FB_WWW_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * @preserve-invariant-messages
 */

${source}`;
  },

  /****************** RN_OSS_DEV ******************/
  [RN_OSS_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @providesModule ${globalName}-dev
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** RN_OSS_PROD ******************/
  [RN_OSS_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @providesModule ${globalName}-prod
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_OSS_PROFILING ******************/
  [RN_OSS_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @providesModule ${globalName}-profiling
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_FB_DEV ******************/
  [RN_FB_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** RN_FB_PROD ******************/
  [RN_FB_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_FB_PROFILING ******************/
  [RN_FB_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },
};

const reconcilerWrappers = {
  /***************** NODE_DEV (reconciler only) *****************/
  [NODE_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  module.exports = function $$$reconciler($$$hostConfig) {
${source}
    var $$$renderer = module.exports;
    module.exports = $$$reconciler;
    return $$$renderer;
  };
}`;
  },

  /***************** NODE_PROD (reconciler only) *****************/
  [NODE_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
module.exports = function $$$reconciler($$$hostConfig) {
${source}
    var $$$renderer = module.exports;
    module.exports = $$$reconciler;
    return $$$renderer;
};`;
  },
};

function wrapBundle(source, bundleType, globalName, filename, moduleType) {
  if (moduleType === RECONCILER) {
    // Standalone reconciler is only used by third-party renderers.
    // It is handled separately.
    const wrapper = reconcilerWrappers[bundleType];
    if (typeof wrapper !== 'function') {
      throw new Error(
        `Unsupported build type for the reconciler package: ${bundleType}.`
      );
    }
    return wrapper(source, globalName, filename, moduleType);
  }
  // All the other packages.
  const wrapper = wrappers[bundleType];
  if (typeof wrapper !== 'function') {
    throw new Error(`Unsupported build type: ${bundleType}.`);
  }
  return wrapper(source, globalName, filename, moduleType);
}

module.exports = {
  wrapBundle,
};
<commit_msg>Add @nolint to FB bundle headers (#18126)<commit_after>'use strict';

const {bundleTypes, moduleTypes} = require('./bundles');
const reactVersion = require('../../package.json').version;

const {
  UMD_DEV,
  UMD_PROD,
  UMD_PROFILING,
  NODE_DEV,
  NODE_PROD,
  NODE_PROFILING,
  FB_WWW_DEV,
  FB_WWW_PROD,
  FB_WWW_PROFILING,
  RN_OSS_DEV,
  RN_OSS_PROD,
  RN_OSS_PROFILING,
  RN_FB_DEV,
  RN_FB_PROD,
  RN_FB_PROFILING,
} = bundleTypes;

const {RECONCILER} = moduleTypes;

const license = ` * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.`;

const wrappers = {
  /***************** UMD_DEV *****************/
  [UMD_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

${source}`;
  },

  /***************** UMD_PROD *****************/
  [UMD_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${source}`;
  },

  /***************** UMD_PROFILING *****************/
  [UMD_PROFILING](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${source}`;
  },

  /***************** NODE_DEV *****************/
  [NODE_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}

if (process.env.NODE_ENV !== "production") {
  (function() {
${source}
  })();
}`;
  },

  /***************** NODE_PROD *****************/
  [NODE_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}
${source}`;
  },

  /***************** NODE_PROFILING *****************/
  [NODE_PROFILING](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
${
  globalName === 'ReactNoopRenderer' ||
  globalName === 'ReactNoopRendererPersistent'
    ? // React Noop needs regenerator runtime because it uses
      // generators but GCC doesn't handle them in the output.
      // So we use Babel for them.
      `const regeneratorRuntime = require("regenerator-runtime");`
    : ``
}
${source}`;
  },

  /****************** FB_WWW_DEV ******************/
  [FB_WWW_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * @preserve-invariant-messages
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** FB_WWW_PROD ******************/
  [FB_WWW_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * @preserve-invariant-messages
 */

${source}`;
  },

  /****************** FB_WWW_PROFILING ******************/
  [FB_WWW_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * @preserve-invariant-messages
 */

${source}`;
  },

  /****************** RN_OSS_DEV ******************/
  [RN_OSS_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @providesModule ${globalName}-dev
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** RN_OSS_PROD ******************/
  [RN_OSS_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @providesModule ${globalName}-prod
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_OSS_PROFILING ******************/
  [RN_OSS_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @providesModule ${globalName}-profiling
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_FB_DEV ******************/
  [RN_FB_DEV](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

'use strict';

if (__DEV__) {
  (function() {
${source}
  })();
}`;
  },

  /****************** RN_FB_PROD ******************/
  [RN_FB_PROD](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },

  /****************** RN_FB_PROFILING ******************/
  [RN_FB_PROFILING](source, globalName, filename, moduleType) {
    return `/**
${license}
 *
 * @noflow
 * @nolint
 * @preventMunge
 * ${'@gen' + 'erated'}
 */

${source}`;
  },
};

const reconcilerWrappers = {
  /***************** NODE_DEV (reconciler only) *****************/
  [NODE_DEV](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */

'use strict';

if (process.env.NODE_ENV !== "production") {
  module.exports = function $$$reconciler($$$hostConfig) {
${source}
    var $$$renderer = module.exports;
    module.exports = $$$reconciler;
    return $$$renderer;
  };
}`;
  },

  /***************** NODE_PROD (reconciler only) *****************/
  [NODE_PROD](source, globalName, filename, moduleType) {
    return `/** @license React v${reactVersion}
 * ${filename}
 *
${license}
 */
module.exports = function $$$reconciler($$$hostConfig) {
${source}
    var $$$renderer = module.exports;
    module.exports = $$$reconciler;
    return $$$renderer;
};`;
  },
};

function wrapBundle(source, bundleType, globalName, filename, moduleType) {
  if (moduleType === RECONCILER) {
    // Standalone reconciler is only used by third-party renderers.
    // It is handled separately.
    const wrapper = reconcilerWrappers[bundleType];
    if (typeof wrapper !== 'function') {
      throw new Error(
        `Unsupported build type for the reconciler package: ${bundleType}.`
      );
    }
    return wrapper(source, globalName, filename, moduleType);
  }
  // All the other packages.
  const wrapper = wrappers[bundleType];
  if (typeof wrapper !== 'function') {
    throw new Error(`Unsupported build type: ${bundleType}.`);
  }
  return wrapper(source, globalName, filename, moduleType);
}

module.exports = {
  wrapBundle,
};
<|endoftext|>


<commit_before>;(function(){//IFEE

angular.module('brewKeeper')
      .controller('recipeDetail', function($scope, $http, $location, $routeParams){
          // console.log("firing the recipeDetail controller")
          var id = $routeParams.id;
          var username = $routeParams.username;
          $scope.username = $routeParams.username;

          $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id)
            .then(function(response){
              $scope.detail = response.data;
              $scope.steps = response.data.steps;
              $scope.notes = response.data.brewnotes;
            })
          $scope.showSteps = function(stepId){
            stepId= "p." + stepId.toString()
            $(stepId).toggleClass("hidden")
          };

          $scope.showNotes = function(){
            $("div.notes").toggleClass("hidden")
          };
          })//recipeDetail controller

      .controller('createNewStep', function($scope, $http, $routeParams){
        var id = $routeParams.id;
        var username = $routeParams.username;
        $scope.username = $routeParams.username;
        $scope.step = { }//Might need to prepopulate this with empty strings for each key... Maybe...
        console.log($scope.step);
        $scope.submit=function(){
          $http.post("https://brew-keeper-api.herokuapp.com/api/users/don.pablo/recipes/12/steps/", $scope.step).then(function(){
            console.log("step posted")
            // $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id)
            //   .then(function(response){
            //     // $scope.detail = response.data;
            //     $scope.steps = response.data.steps;
            //     console.log($scope.steps)
            //     // $scope.notes = response.data.brewnotes;
            //   })
          })
          console.log($scope.step)
          // $scope.step= { };
        } //end new step submit function

        $scope.Eliminate = function() {
          if (window.confirm("Are you sure you want to delete " + $scope.detail.title + "?")){
            $http.delete('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id + '/').then(function(){
              $location.path('/users/'+ username);
            })
          };
        }; //end Eliminate function

        $scope.showAddSteps = function(){
          $("form.create-new-step").removeClass("hidden");
          $("button.done-adding").removeClass("hidden");
        };//Reveal "Add Step" when new recipe form is submitted.
        $scope.hideAddSteps = function(){
          $("form.create-new-step").addClass("hidden");
          $("button.done-adding").addClass("hidden");
        }; //hides the add step form
      }) //end createNewStep controller

})();//END Angular IFEE
<commit_msg>add steps posts to correct user and recipe<commit_after>;(function(){//IFEE

angular.module('brewKeeper')
      .controller('recipeDetail', function($scope, $http, $location, $routeParams){
          // console.log("firing the recipeDetail controller")
          var id = $routeParams.id;
          var username = $routeParams.username;
          $scope.username = $routeParams.username;

          $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id)
            .then(function(response){
              $scope.detail = response.data;
              $scope.steps = response.data.steps;
              $scope.notes = response.data.brewnotes;
            })
          $scope.showSteps = function(stepId){
            stepId= "p." + stepId.toString()
            $(stepId).toggleClass("hidden")
          };

          $scope.showNotes = function(){
            $("div.notes").toggleClass("hidden")
          };
          })//recipeDetail controller

      .controller('createNewStep', function($scope, $http, $routeParams){
        var id = $routeParams.id;
        var username = $routeParams.username;
        $scope.username = $routeParams.username;
        $scope.step = { }//Might need to prepopulate this with empty strings for each key... Maybe...
        console.log($scope.step);
        $scope.submit=function(){
          $http.post("https://brew-keeper-api.herokuapp.com/api/users/"+username+"/recipes/"+id+"/steps/", $scope.step).then(function(){
            console.log("step posted")
            // $http.get('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id)
            //   .then(function(response){
            //     // $scope.detail = response.data;
            //     $scope.steps = response.data.steps;
            //     console.log($scope.steps)
            //     // $scope.notes = response.data.brewnotes;
            //   })
          })
          console.log($scope.step)
          // $scope.step= { };
        } //end new step submit function

        $scope.Eliminate = function() {
          if (window.confirm("Are you sure you want to delete " + $scope.detail.title + "?")){
            $http.delete('https://brew-keeper-api.herokuapp.com/api/users/' + username + '/recipes/' + id + '/').then(function(){
              $location.path('/users/'+ username);
            })
          };
        }; //end Eliminate function

        $scope.showAddSteps = function(){
          $("form.create-new-step").removeClass("hidden");
          $("button.done-adding").removeClass("hidden");
        };//Reveal "Add Step" when new recipe form is submitted.
        $scope.hideAddSteps = function(){
          $("form.create-new-step").addClass("hidden");
          $("button.done-adding").addClass("hidden");
        }; //hides the add step form
      }) //end createNewStep controller

})();//END Angular IFEE
<|endoftext|>


<commit_before>"use strict";
var fluid  = fluid || require("infusion");
var gpii   = fluid.registerNamespace("gpii");

var request = require("request"); // TODO:  Replace this with a writable data source.

var path      = require("path");
var schemaDir = path.resolve(__dirname, "../../schemas");

require("./lib/datasource");
require("./lib/mailer");
require("./lib/password");
require("./lib/singleTemplateRouter");

fluid.registerNamespace("gpii.express.user.api.signup.post.handler");

// Check to see if the user exists.
gpii.express.user.api.signup.post.handler.lookupExistingUser = function (that) {
    that.reader.get(that.request.body).then(that.checkForExistingUser);
};

gpii.express.user.api.signup.post.handler.checkForExistingUser = function (that, response) {
    if (response && response.username) {
        that.sendResponse(403, { ok: false, message: "A user with this email or username already exists."});
        return;
    }

    // Encode the user's password
    var salt        = gpii.express.user.password.generateSalt(that.options.saltLength);
    var derived_key = gpii.express.user.password.encode(that.request.body.password, salt);
    var code        = gpii.express.user.password.generateSalt(that.options.verifyCodeLength);

    var combinedRecord                   = fluid.copy(that.request.body);
    // Set the "name" to the username for backward compatibility with CouchDB
    combinedRecord.name                  = combinedRecord.username;
    combinedRecord.salt                  = salt;
    combinedRecord.derived_key           = derived_key;
    combinedRecord[that.options.codeKey] = code;

    // Make sure we don't inadvertantly save the original password to the database.
    delete combinedRecord.password;
    delete combinedRecord.confirm;

    fluid.each(that.options.userDefaults, function (value, key) {
        combinedRecord[key] = value;
    });

    // Set the ID to match the CouchDB conventions, for backward compatibility
    combinedRecord._id = "org.couch.db.user:" + combinedRecord.username;

    // Write the record to couch.  TODO: Migrate this to a writable dataSource.
    var writeOptions = {
        url:    that.options.urls.write,
        method: "POST",
        json:   true,
        body:   combinedRecord
    };
    request(writeOptions, function (error, response, body) {
        if (error) {
            return that.sendResponse(500, {ok: false, message: error});
        }
        else if ([200, 201].indexOf(response.statusCode) === -1) {
            return that.sendResponse(response.statusCode, { ok: false, message: body});
        }

        var mailOptions = fluid.copy(that.options.mailDefaults);
        mailOptions.to  = that.request.body.email;

        var templateContext = fluid.copy(that.options.templateDefaultContext);
        templateContext.user = combinedRecord;
        that.mailer.sendMessage(mailOptions, templateContext); // The mailer listeners will take care of the response from here.
    });
};

fluid.defaults("gpii.express.user.api.signup.post.handler", {
    gradeNames: ["gpii.express.handler"],
    templateDefaultContext: {
        app: "{gpii.express}.options.config.app"
    },
    urls: "{gpii.express.user.api.signup.post}.options.urls",
    saltLength: "{gpii.express.user.api.signup.post}.options.saltLength",
    verifyCodeLength: "{gpii.express.user.api.signup.post}.options.verifyCodeLength",
    codeKey: "{gpii.express.user.api.signup.post}.options.codeKey",
    mailDefaults: "{gpii.express.user.api.signup.post}.options.mailDefaults",
    userDefaults: "{gpii.express.user.api.signup.post}.options.userDefaults",
    invokers: {
        handleRequest: {
            funcName: "gpii.express.user.api.signup.post.handler.lookupExistingUser",
            args:     ["{that}"]
        },
        "checkForExistingUser": {
            funcName: "gpii.express.user.api.signup.post.handler.checkForExistingUser",
            args:     ["{that}", "{arguments}.0"],
            priority: "last"
        }
    },
    components: {
        reader: {
            type: "gpii.express.user.couchdb.read",
            options: {
                rules: {
                    read: {
                        "": "rows.0.value"
                    }
                },
                url:     "{gpii.express.user.api.signup.post}.options.urls.read",
                termMap: "{gpii.express.user.api.signup.post}.options.termMaps.read"
            }
        },
        mailer: {
            type: "gpii.express.user.mailer.handlebars",
            options: {
                templateDir:     "{gpii.express.user.api.signup.post}.options.templateDir",
                htmlTemplateKey: "{gpii.express.user.api.signup.post}.options.htmlTemplateKey",
                textTemplateKey: "{gpii.express.user.api.signup.post}.options.textTemplateKey",
                listeners: {
                    "onSuccess.sendResponse": {
                        func: "{handler}.sendResponse",
                        args: [200, { ok: true, message: "Your account has been created, but must be verified.  Please check your email for details."}]
                    },
                    "onError.sendResponse": {
                        func: "{handler}.sendResponse",
                        args: [500, { ok: false, message: "Your account has been created, but a confirmation email could not be sent.  Contact an administrator."}]
                    }
                }
            }

        }
    }
});

fluid.defaults("gpii.express.user.api.signup.post", {
    gradeNames:       ["gpii.express.router.passthrough"],
    path:             "/",
    saltLength:       32,
    verifyCodeLength: 16,
    codeKey:          "verification_code",  // Must match the value in gpii.express.user.api.verify
    couchPath:        "/_design/lookup/_view/byUsernameOrEmail",
    textTemplateKey:  "email-verify-text",
    htmlTemplateKey:  "email-verify-html",
    templateDefaultContext: {},
    urls: {
        read:  {
            expander: {
                funcName: "fluid.stringTemplate",
                args: [ "%userDbUrl%path?keys=[\"%username\",\"%email\"]", { userDbUrl: "{that}.options.couch.userDbUrl", path: "{that}.options.couchPath"}]
            }
        },
        write: "{that}.options.couch.userDbUrl"
    },
    rules: {
        write: {
            "": "",
            "name": "username" // Default rules are designed to cater to CouchDB  and express-couchUser conventions, but can be overriden.
        }
    },
    distributeOptions: {
        source: "{that}.options.rules",
        target: "{that gpii.express.handler}.options.rules"
    },
    termMaps: {
        read: { username: "%username", email: "%email"}
    },
    mailDefaults: {
        from:    "test@localhost",
        subject: "Please verify your account..."
    },
    userDefaults: {
        roles:           [],
        type:            "user",
        password_scheme: "pbkdf2",
        iterations:      10,
        verified:        false
    },
    components: {
        schemaMiddleware: {
            type: "gpii.schema.middleware",
            options: {
                schemaDir: schemaDir,
                schemaKey: "user-signup"
            }
        },
        requestAwareRouter: {
            type: "gpii.express.requestAware.router",
            options: {
                method:           "post",
                path:             "/",
                handlerGrades:    ["gpii.express.user.api.signup.post.handler"]
            }
        }
    }
});

fluid.defaults("gpii.express.user.api.signup", {
    gradeNames: ["gpii.express.router.passthrough"],
    path:       "/signup",
    rules: {
        user: {
            "username": "name", // Default configuration is designed for CouchDB and express-couchUser field naming conventions.
            "email":    "email"
        }
    },
    distributeOptions: [
        {
            source: "{that}.options.couch",
            target: "{that gpii.express.router}.options.couch"
        },
        {
            source: "{that}.options.couch",
            target: "{that gpii.express.handler}.options.couch"
        },
        {
            source: "{that}.options.rules",
            target: "{that gpii.express.handler}.options.rules"
        }
    ],
    components: {
        getRouter: {
            type: "gpii.express.user.api.singleTemplateRouter",
            options: {
                templateKey: "pages/signup"
            }
        },
        postRouter: {
            type: "gpii.express.user.api.signup.post"
        }
    }
});<commit_msg>Tidied up typos and unclear passages in comments.<commit_after>"use strict";
var fluid  = fluid || require("infusion");
var gpii   = fluid.registerNamespace("gpii");

var request = require("request"); // TODO:  Replace this with a writable data source.

var path      = require("path");
var schemaDir = path.resolve(__dirname, "../../schemas");

require("./lib/datasource");
require("./lib/mailer");
require("./lib/password");
require("./lib/singleTemplateRouter");

fluid.registerNamespace("gpii.express.user.api.signup.post.handler");

// Check to see if the user exists.
gpii.express.user.api.signup.post.handler.lookupExistingUser = function (that) {
    that.reader.get(that.request.body).then(that.checkForExistingUser);
};

gpii.express.user.api.signup.post.handler.checkForExistingUser = function (that, response) {
    if (response && response.username) {
        that.sendResponse(403, { ok: false, message: "A user with this email or username already exists."});
        return;
    }

    // Encode the user's password
    var salt        = gpii.express.user.password.generateSalt(that.options.saltLength);
    var derived_key = gpii.express.user.password.encode(that.request.body.password, salt);
    var code        = gpii.express.user.password.generateSalt(that.options.verifyCodeLength);

    var combinedRecord                   = fluid.copy(that.request.body);
    // Set the "name" to the username for backward compatibility with CouchDB
    combinedRecord.name                  = combinedRecord.username;
    combinedRecord.salt                  = salt;
    combinedRecord.derived_key           = derived_key;
    combinedRecord[that.options.codeKey] = code;

    // Make sure we don't inadvertently save the original password to the database.
    delete combinedRecord.password;
    delete combinedRecord.confirm;

    fluid.each(that.options.userDefaults, function (value, key) {
        combinedRecord[key] = value;
    });

    // Set the ID to match the CouchDB conventions, for backward compatibility
    combinedRecord._id = "org.couch.db.user:" + combinedRecord.username;

    // Write the record to couch.  TODO: Migrate this to a writable dataSource.
    var writeOptions = {
        url:    that.options.urls.write,
        method: "POST",
        json:   true,
        body:   combinedRecord
    };
    request(writeOptions, function (error, response, body) {
        if (error) {
            return that.sendResponse(500, {ok: false, message: error});
        }
        else if ([200, 201].indexOf(response.statusCode) === -1) {
            return that.sendResponse(response.statusCode, { ok: false, message: body});
        }

        var mailOptions = fluid.copy(that.options.mailDefaults);
        mailOptions.to  = that.request.body.email;

        var templateContext = fluid.copy(that.options.templateDefaultContext);
        templateContext.user = combinedRecord;
        that.mailer.sendMessage(mailOptions, templateContext); // Our listeners will monitor the mailer and continue from there.
    });
};

fluid.defaults("gpii.express.user.api.signup.post.handler", {
    gradeNames: ["gpii.express.handler"],
    templateDefaultContext: {
        app: "{gpii.express}.options.config.app"
    },
    urls: "{gpii.express.user.api.signup.post}.options.urls",
    saltLength: "{gpii.express.user.api.signup.post}.options.saltLength",
    verifyCodeLength: "{gpii.express.user.api.signup.post}.options.verifyCodeLength",
    codeKey: "{gpii.express.user.api.signup.post}.options.codeKey",
    mailDefaults: "{gpii.express.user.api.signup.post}.options.mailDefaults",
    userDefaults: "{gpii.express.user.api.signup.post}.options.userDefaults",
    invokers: {
        handleRequest: {
            funcName: "gpii.express.user.api.signup.post.handler.lookupExistingUser",
            args:     ["{that}"]
        },
        "checkForExistingUser": {
            funcName: "gpii.express.user.api.signup.post.handler.checkForExistingUser",
            args:     ["{that}", "{arguments}.0"],
            priority: "last"
        }
    },
    components: {
        reader: {
            type: "gpii.express.user.couchdb.read",
            options: {
                rules: {
                    read: {
                        "": "rows.0.value"
                    }
                },
                url:     "{gpii.express.user.api.signup.post}.options.urls.read",
                termMap: "{gpii.express.user.api.signup.post}.options.termMaps.read"
            }
        },
        mailer: {
            type: "gpii.express.user.mailer.handlebars",
            options: {
                templateDir:     "{gpii.express.user.api.signup.post}.options.templateDir",
                htmlTemplateKey: "{gpii.express.user.api.signup.post}.options.htmlTemplateKey",
                textTemplateKey: "{gpii.express.user.api.signup.post}.options.textTemplateKey",
                listeners: {
                    "onSuccess.sendResponse": {
                        func: "{handler}.sendResponse",
                        args: [200, { ok: true, message: "Your account has been created, but must be verified.  Please check your email for details."}]
                    },
                    "onError.sendResponse": {
                        func: "{handler}.sendResponse",
                        args: [500, { ok: false, message: "Your account has been created, but a confirmation email could not be sent.  Contact an administrator."}]
                    }
                }
            }

        }
    }
});

fluid.defaults("gpii.express.user.api.signup.post", {
    gradeNames:       ["gpii.express.router.passthrough"],
    path:             "/",
    saltLength:       32,
    verifyCodeLength: 16,
    codeKey:          "verification_code",  // Must match the value in gpii.express.user.api.verify
    couchPath:        "/_design/lookup/_view/byUsernameOrEmail",
    textTemplateKey:  "email-verify-text",
    htmlTemplateKey:  "email-verify-html",
    templateDefaultContext: {},
    urls: {
        read:  {
            expander: {
                funcName: "fluid.stringTemplate",
                args: [ "%userDbUrl%path?keys=[\"%username\",\"%email\"]", { userDbUrl: "{that}.options.couch.userDbUrl", path: "{that}.options.couchPath"}]
            }
        },
        write: "{that}.options.couch.userDbUrl"
    },
    rules: {
        write: {
            "": "",
            "name": "username" // Default rules are designed to cater to CouchDB  and express-couchUser conventions, but can be overriden.
        }
    },
    distributeOptions: {
        source: "{that}.options.rules",
        target: "{that gpii.express.handler}.options.rules"
    },
    termMaps: {
        read: { username: "%username", email: "%email"}
    },
    mailDefaults: {
        from:    "test@localhost",
        subject: "Please verify your account..."
    },
    userDefaults: {
        roles:           [],
        type:            "user",
        password_scheme: "pbkdf2",
        iterations:      10,
        verified:        false
    },
    components: {
        schemaMiddleware: {
            type: "gpii.schema.middleware",
            options: {
                schemaDir: schemaDir,
                schemaKey: "user-signup"
            }
        },
        requestAwareRouter: {
            type: "gpii.express.requestAware.router",
            options: {
                method:           "post",
                path:             "/",
                handlerGrades:    ["gpii.express.user.api.signup.post.handler"]
            }
        }
    }
});

fluid.defaults("gpii.express.user.api.signup", {
    gradeNames: ["gpii.express.router.passthrough"],
    path:       "/signup",
    rules: {
        user: {
            "username": "name", // Default configuration is designed for CouchDB and express-couchUser field naming conventions.
            "email":    "email"
        }
    },
    distributeOptions: [
        {
            source: "{that}.options.couch",
            target: "{that gpii.express.router}.options.couch"
        },
        {
            source: "{that}.options.couch",
            target: "{that gpii.express.handler}.options.couch"
        },
        {
            source: "{that}.options.rules",
            target: "{that gpii.express.handler}.options.rules"
        }
    ],
    components: {
        getRouter: {
            type: "gpii.express.user.api.singleTemplateRouter",
            options: {
                templateKey: "pages/signup"
            }
        },
        postRouter: {
            type: "gpii.express.user.api.signup.post"
        }
    }
});<|endoftext|>


<commit_before>//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");

  shoestring.enUS = {
    errors: {
      'prev-selector' : "Shoestring does not support passing selectors into .prev, try .prev().filter(selector)",
			'hasClass' : "Shoestring does not support the hasClass method. Try using .is( '.klassname' ) instead"
    }
  };

  shoestring.error = function( id ) {
    throw new Error( shoestring.enUS.errors[id] );
  };

//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
<commit_msg>This project uses tabs not spaces<commit_after>//>>excludeStart("exclude", pragmas.exclude);
define([ "shoestring" ], function(){
//>>excludeEnd("exclude");

	shoestring.enUS = {
		errors: {
			'prev-selector' : "Shoestring does not support passing selectors into .prev, try .prev().filter(selector)",
			'hasClass' : "Shoestring does not support the hasClass method. Try using .is( '.klassname' ) instead"
		}
	};

	shoestring.error = function( id ) {
		throw new Error( shoestring.enUS.errors[id] );
	};

//>>excludeStart("exclude", pragmas.exclude);
});
//>>excludeEnd("exclude");
<|endoftext|>


<commit_before>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    checkoutNormalizer = require('./checkout-normalizer'),
    http = require('http-browser'),
    cssHack = require('../tools/css-hack'),
    isApp = typeof navigator !== 'undefined' && navigator.app,
    log = require('../tools/log');

function getBaseCheckout(options) {
  var baseCheckout = ( options.host === 'location' ? ( location.protocol + '//' + location.host + '/' ) : options.host ) || ( api.checkoutUrl || api.staticUrl ) + 'checkout/';

  // Append trailing slash if not exists.
  if (!/\/$/.test(baseCheckout)) {
    baseCheckout += '/';
  }

  return baseCheckout;
}

function checkout (options) {

  options = options || {};
  var baseCheckout = getBaseCheckout(options);

  var on = {},
      onError,
      iframeSrc = baseCheckout + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      errorMessage = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal'),
      viewPortHack = document.createElement('meta');

  viewPortHack.name = 'viewport';
  viewPortHack.content = 'width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';

  document.head.appendChild(viewPortHack);

  onError = options.onError || _.noop;
  delete options.onError;

  try {
    options = checkoutNormalizer(options, location, _.copy(api));
    on.success = options.merchant.onSuccess;
    on.pending = options.merchant.onPending;
    on.cancel = options.merchant.onError;
    on.dismiss = options.merchant.onDismiss;
  } catch (e) {
    errorMessage = e.message;
  }

  if (options.merchant) {
    // All functions must be removed as them can't be serialized by postMessage
    delete options.merchant.onSuccess;
    delete options.merchant.onPending;
    delete options.merchant.onError;
    delete options.merchant.onDismiss;
  }

  if( isApp ) {
    options.meta = options.meta || {};
    options.meta.is_app = true;
  }

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  return http( iframeSrc ).then(function (response) {
      var iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          }),
          httpCheckout = function () {
            var started = _.now();
            return http.apply(this, arguments).then(function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-success',
                started: started,
                elapsed: _.now() - started,
                response: http.plainResponse(response)
              }, '*');
              return response;
            }, function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-error',
                started: started,
                elapsed: _.now() - started,
                response: http.plainResponse(response)
              }, '*');
              throw response;
            });
          };

      iframe.className = 'aplazame-modal';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if (errorMessage) {
        throw new Error(errorMessage);
      }

      var onMessage = function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = _.remove_style;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'open-link':
            if( isApp )
              navigator.app.loadUrl(message.href, { openExternal: true });
            else
              window.open(message.href, '_system');
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              cssBlur.hack(false);
              _.removeClass(document.body, 'aplazame-blur');
              _.removeClass(document.body, 'aplazame-unblur');
            }, 600);
            break;
          case 'confirm':
          case 'success':
            _.log('aplazame.checkout:confirm', message);

            httpCheckout( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: _.extend(message.params || {}, {
                order_id: message.data.checkout_token,
                checkout_token: message.data.checkout_token
              })
            }).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;
              document.head.removeChild(viewPortHack);

              _.onMessage.off('checkout', onMessage);

              if( on[message.result] ) on[message.result]();
            }
            break;
        }
      };

      _.onMessage('checkout', onMessage);

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseCheckout);
      errorLoading = true;

      log('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      onError(reason);
    });

}

module.exports = checkout;
<commit_msg>Iframe (#74)<commit_after>'use strict';

var api = require('../core/api'),
    _ = require('../tools/tools'),
    checkoutNormalizer = require('./checkout-normalizer'),
    http = require('http-browser'),
    cssHack = require('../tools/css-hack'),
    isApp = typeof navigator !== 'undefined' && navigator.app,
    log = require('../tools/log');

function getBaseCheckout(options) {
  var baseCheckout = ( options.host === 'location' ? ( location.protocol + '//' + location.host + '/' ) : options.host ) || ( api.checkoutUrl || api.staticUrl ) + 'checkout/';

  // Append trailing slash if not exists.
  if (!/\/$/.test(baseCheckout)) {
    baseCheckout += '/';
  }

  return baseCheckout;
}

function checkout (options) {

  options = options || {};
  var baseCheckout = getBaseCheckout(options);

  var on = {},
      onError,
      iframeSrc = baseCheckout + 'iframe.html?' + new Date().getTime(),
      errorLoading = false,
      errorMessage = false,
      tmpOverlay = document.createElement('div'),
      cssOverlay = cssHack('overlay'),
      cssBlur = cssHack('blur'),
      cssLogo = cssHack('logo'),
      cssModal = cssHack('modal'),
      viewPortHack = document.createElement('meta');

  viewPortHack.name = 'viewport';
  viewPortHack.content = 'width=device-width, height=device-height, initial-scale=1.0, maximum-scale=1.0, user-scalable=no';

  document.head.appendChild(viewPortHack);

  onError = options.onError || _.noop;
  delete options.onError;

  try {
    options = checkoutNormalizer(options, location, _.copy(api));
    on.success = options.merchant.onSuccess;
    on.pending = options.merchant.onPending;
    on.cancel = options.merchant.onError;
    on.dismiss = options.merchant.onDismiss;
  } catch (e) {
    errorMessage = e.message;
  }

  if (options.merchant) {
    // All functions must be removed as them can't be serialized by postMessage
    delete options.merchant.onSuccess;
    delete options.merchant.onPending;
    delete options.merchant.onError;
    delete options.merchant.onDismiss;
  }

  if( isApp ) {
    options.meta = options.meta || {};
    options.meta.is_app = true;
  }

  tmpOverlay.className = 'aplazame-overlay aplazame-overlay-show';

  cssOverlay.hack(true);
  cssLogo.hack(true);
  cssBlur.hack(true);

  setTimeout(function () {
    if( !errorLoading ) {
      _.addClass(document.body, 'aplazame-blur');
    }
  }, 0);

  tmpOverlay.innerHTML = '

' +
  require('./loading-svg') + '

Cargando pasarela de pago...

';

  document.body.appendChild(tmpOverlay);

  var loadingText = tmpOverlay.querySelector('.aplazame-overlay-loading-text');

  setTimeout(function () {
    if( !errorLoading ) {
      tmpOverlay.querySelector('.logo-aplazame').className += ' animate';
    }
  }, 200);

  return http( iframeSrc ).then(function (response) {
      var iframe = _.getIFrame({
            top: 0,
            left: 0,
            width: '100%',
            height: '0',
            background: 'transparent'
          }),
          httpCheckout = function () {
            var started = _.now();
            return http.apply(this, arguments).then(function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-success',
                started: started,
                elapsed: _.now() - started,
                response: http.plainResponse(response)
              }, '*');
              return response;
            }, function (response) {
              iframe.contentWindow.postMessage({
                aplazame: 'checkout',
                event: 'http-error',
                started: started,
                elapsed: _.now() - started,
                response: http.plainResponse(response)
              }, '*');
              throw response;
            });
          };

      iframe.id = 'aplazame-checkout-iframe';
      iframe.className = 'aplazame-modal';

      document.body.appendChild(iframe);
      iframe.src = iframeSrc;

      if (errorMessage) {
        throw new Error(errorMessage);
      }

      var onMessage = function (e, message) {

        switch( message.event ) {
          case 'merchant':
            iframe.style.display = _.remove_style;
            e.source.postMessage({
              checkout: options
            }, '*');
            break;
          case 'show-iframe':
            _.removeClass(iframe, 'hide');
            cssModal.hack(true);
            cssOverlay.hack(false);
            document.body.removeChild(tmpOverlay);
            break;
          case 'loading-text':
            loadingText.textContent = message.text;
            break;
          case 'open-link':
            if( isApp )
              navigator.app.loadUrl(message.href, { openExternal: true });
            else
              window.open(message.href, '_system');
            break;
          case 'drop-blur':
            _.removeClass(document.body, 'aplazame-blur');
            _.addClass(document.body, 'aplazame-unblur');
            setTimeout(function () {
              cssBlur.hack(false);
              _.removeClass(document.body, 'aplazame-blur');
              _.removeClass(document.body, 'aplazame-unblur');
            }, 600);
            break;
          case 'confirm':
          case 'success':
            _.log('aplazame.checkout:confirm', message);

            httpCheckout( options.merchant.confirmation_url, {
              method: 'post',
              contentType: 'application/json',
              data: message.data,
              params: _.extend(message.params || {}, {
                order_id: message.data.checkout_token,
                checkout_token: message.data.checkout_token
              })
            }).then(function (response) {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'success',
                response: http.plainResponse(response)
              }, '*');
            }, function () {
              e.source.postMessage({
                aplazame: 'checkout',
                event: 'confirmation',
                result: 'error',
                response: http.plainResponse(response)
              }, '*');
            });
            // confirmation_url
            break;
          case 'close':
            if( iframe ) {
              document.body.removeChild(iframe);
              cssModal.hack(false);
              iframe = null;
              document.head.removeChild(viewPortHack);

              _.onMessage.off('checkout', onMessage);

              if( on[message.result] ) on[message.result]();
            }
            break;
        }
      };

      _.onMessage('checkout', onMessage);

    }).catch(function (reason) {
      // throw new Error('can not connect to ' + baseCheckout);
      errorLoading = true;

      log('Aplazame ' + reason);

      _.removeClass(tmpOverlay.querySelector('.logo-aplazame'), 'animate');
      loadingText.innerHTML = '
Error cargando pasarela de pago

soporte@aplazame.com
';
      loadingText.style.lineHeight = '1.5';

      onError(reason);
    });

}

module.exports = checkout;
<|endoftext|>


<commit_before>/*
 * Rapid Interface Builder (RIB) - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011-2012, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

// Palette view widget

(function($, undefined) {

    $.widget('rib.paletteView', {

        options: {
            model: null,
        },

        _create: function() {
            var o = this.options,
                e = this.element;

            this.refresh(null, this);

            return this;
        },

        _setOption: function(key, value) {
            switch (key) {
                case 'model':
                    this.options.model = value;
                    this.refresh(null, this);
                    break;
                default:
                    break;
            }
        },

        destroy: function() {
            // TODO: unbind any ADM event handlers
            $(this.element).find('.'+this.widgetName).remove();
            this.options.primaryTools.remove();
            this.options.secondaryTools.remove();
        },

        refresh: function(event, widget) {
            var listWidgets, columns, generateWidget;

            widget = widget || this;

            generateWidget = function (container, name) {
                var reg = new RegExp("src:\\s*url\\s*\\('../../"),
                    li = $('')
                        .appendTo(container);
                $.get("src/css/images/widgets/" +
                        BWidget.getPaletteImageName(name), function (data) {
                    li.attr('src','data:image/svg+xml;utf8,'
                        + new XMLSerializer().serializeToString(data)
                            .replace(reg, "src: url('" + location.protocol
                                + "//" + location.host + "/" + location.pathname
                                + "/src/css/")
                    );
                });
                $(li).disableSelection()
                    .addClass('nrc-palette-widget')
                    .data("adm-node", {type: name});
            };
            listWidgets = function (container, group) {
                $.each(group, function (i, value) {
                    if (value && typeof value === "string") {
                        if (BWidget.isPaletteWidget(value)) {
                            generateWidget(container, value);
                        }
                    }
                    else if (value)
                        listWidgets(container, value);
                });
            };

            if (widget.options && widget.options.model) {
                this.element.empty();
                this.element.append('
');
                listWidgets((this.element.find('.columns')), this.options.model);
                var w = this.element.find('.nrc-palette-widget');

                w.draggable({
                    scroll: false,
                    revert: false,
                    appendTo: 'body',
                    iframeFix: true,
                    containment: false,
                    connectToSortable: $(':rib-layoutView')
                                       .layoutView('option', 'contentDocument')
                                       .find('.ui-page-active'),
                    helper: 'clone',
                    refreshPositions: true,
                    stack: '.layoutView iframe',
                    revertDuration: 0,
                    filter: function() { return $.rib.dndfilter($(this)); },
                    start: function(event,ui){
                        var d = $(this).draggable('option','connectToSortable'),
                            f = $(':rib-layoutView')
                                    .layoutView('option','contentDocument'),
                            s = [], id;

                        if (ui.helper) {
                            if (ui.helper[0].id == "") {
                                ui.helper[0].id = this.id+'-helper';
                            }
                        }

                        // Must have an active page in order to filter
                        if (!ADM.getActivePage()) {
                            console.warning('Filter failure: No active page.');
                            return s;
                        } else {
                            id = ADM.getActivePage().getProperty('id');
                        }

                        // Find all adm-nodes (and page) on the active page
                        f = f.find('#'+id);
                        s = f.find('.adm-node').andSelf();

                        // First mark all nodes as blocked
                        s && s.addClass('ui-masked');

                        // Then unmark all valid targets
                        d && d.removeClass('ui-masked')
                              .addClass('ui-unmasked');

                        // Also unmark adm-node descendants of valid targets
                        // that are not also children of a masked container
                        // - Solves styling issues with nested containers
                        $('.ui-unmasked',f).each(function() {
                            var that = this, nodes;
                            $('.adm-node',this)
                                .not('.nrc-sortable-container')
                                .each(function() {
                                    var rents = $(this).parentsUntil(that,
                                          '.nrc-sortable-container.ui-masked');
                                    if (!rents.length) {
                                        $(this).removeClass('ui-masked')
                                               .addClass('ui-unmasked');
                                    }
                                });
                        });
                    },
                    stop: function(event,ui){
                        var f = $(':rib-layoutView')
                                    .layoutView('option','contentDocument');
                        f = f.find('#'+ADM.getActivePage().getProperty('id'));

                        // Reset masked states on all nodes on the active page
                        f.find('.ui-masked, .ui-unmasked')
                            .andSelf()
                            .removeClass('ui-masked ui-unmasked');

                        // Reset active state on all nodes on the active page
                        // - Fixes a glitch where ui-state-active sometimes
                        //   remains after dragging has completed...
                        f.find('.ui-state-active')
                            .removeClass('ui-state-active');
                    },
                })
                .disableSelection();
            }
        },
        resize: function(event, widget) {
            var headerHeight = 30, resizeBarHeight = 20, used, e;
            e = this.element;

            // allocate 70% of the remaining space for the palette
            used = 2 * headerHeight + resizeBarHeight;
            e.height(Math.round((e.parent().height() - used) * 0.7));
        },

    });
})(jQuery);
<commit_msg>[Palette View] Performance improvements to SVG loading<commit_after>/*
 * Rapid Interface Builder (RIB) - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011-2012, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

// Palette view widget

(function($, undefined) {

    $.widget('rib.paletteView', {

        options: {
            model: null,
        },

        _create: function() {
            var o = this.options,
                e = this.element;

            this.refresh(null, this);

            return this;
        },

        _setOption: function(key, value) {
            switch (key) {
                case 'model':
                    this.options.model = value;
                    this.refresh(null, this);
                    break;
                default:
                    break;
            }
        },

        destroy: function() {
            // TODO: unbind any ADM event handlers
            $(this.element).find('.'+this.widgetName).remove();
            this.options.primaryTools.remove();
            this.options.secondaryTools.remove();
        },

        fontRegExp: new RegExp("src:\\s*url\\s*\\('../../"),

        refresh: function(event, widget) {
            var listWidgets, columns, generateWidget;

            widget = widget || this;

            generateWidget = function (container, name) {
                var href = location.href.replace(location.search, ''),
                    li = $('')
                        .appendTo(container);
                name = BWidget.getPaletteImageName(name);
                $.get("src/css/images/widgets/" + name,
                    function (data, stat, resp) {
                        li.attr('src', 'data:image/svg+xml;utf8,' +
                            resp.responseText.replace(widget.fontRegExp,
                                "src: url('" + href + "src/css/"));
                    });
                $(li).disableSelection()
                    .addClass('nrc-palette-widget')
                    .data("adm-node", {type: name});
            };
            listWidgets = function (container, group) {
                $.each(group, function (i, value) {
                    if (value && typeof value === "string") {
                        if (BWidget.isPaletteWidget(value)) {
                            generateWidget(container, value);
                        }
                    }
                    else if (value)
                        listWidgets(container, value);
                });
            };

            if (widget.options && widget.options.model) {
                this.element.empty();
                this.element.append('
');
                listWidgets((this.element.find('.columns')), this.options.model);
                var w = this.element.find('.nrc-palette-widget');

                w.draggable({
                    scroll: false,
                    revert: false,
                    appendTo: 'body',
                    iframeFix: true,
                    containment: false,
                    connectToSortable: $(':rib-layoutView')
                                       .layoutView('option', 'contentDocument')
                                       .find('.ui-page-active'),
                    helper: 'clone',
                    refreshPositions: true,
                    stack: '.layoutView iframe',
                    revertDuration: 0,
                    filter: function() { return $.rib.dndfilter($(this)); },
                    start: function(event,ui){
                        var d = $(this).draggable('option','connectToSortable'),
                            f = $(':rib-layoutView')
                                    .layoutView('option','contentDocument'),
                            s = [], id;

                        if (ui.helper) {
                            if (ui.helper[0].id == "") {
                                ui.helper[0].id = this.id+'-helper';
                            }
                        }

                        // Must have an active page in order to filter
                        if (!ADM.getActivePage()) {
                            console.warning('Filter failure: No active page.');
                            return s;
                        } else {
                            id = ADM.getActivePage().getProperty('id');
                        }

                        // Find all adm-nodes (and page) on the active page
                        f = f.find('#'+id);
                        s = f.find('.adm-node').andSelf();

                        // First mark all nodes as blocked
                        s && s.addClass('ui-masked');

                        // Then unmark all valid targets
                        d && d.removeClass('ui-masked')
                              .addClass('ui-unmasked');

                        // Also unmark adm-node descendants of valid targets
                        // that are not also children of a masked container
                        // - Solves styling issues with nested containers
                        $('.ui-unmasked',f).each(function() {
                            var that = this, nodes;
                            $('.adm-node',this)
                                .not('.nrc-sortable-container')
                                .each(function() {
                                    var rents = $(this).parentsUntil(that,
                                          '.nrc-sortable-container.ui-masked');
                                    if (!rents.length) {
                                        $(this).removeClass('ui-masked')
                                               .addClass('ui-unmasked');
                                    }
                                });
                        });
                    },
                    stop: function(event,ui){
                        var f = $(':rib-layoutView')
                                    .layoutView('option','contentDocument');
                        f = f.find('#'+ADM.getActivePage().getProperty('id'));

                        // Reset masked states on all nodes on the active page
                        f.find('.ui-masked, .ui-unmasked')
                            .andSelf()
                            .removeClass('ui-masked ui-unmasked');

                        // Reset active state on all nodes on the active page
                        // - Fixes a glitch where ui-state-active sometimes
                        //   remains after dragging has completed...
                        f.find('.ui-state-active')
                            .removeClass('ui-state-active');
                    },
                })
                .disableSelection();
            }
        },
        resize: function(event, widget) {
            var headerHeight = 30, resizeBarHeight = 20, used, e;
            e = this.element;

            // allocate 70% of the remaining space for the palette
            used = 2 * headerHeight + resizeBarHeight;
            e.height(Math.round((e.parent().height() - used) * 0.7));
        },

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