<commit_before>// movies.js
var Movies = require('../models/movies');
var sw = require("swagger-node-express");
var param = sw.params;
var url = require("url");
var swe = sw.errors;
var _ = require('underscore');

/*
 *  Util Functions
 */

function writeResponse (res, response, start) {
  sw.setHeaders(res);
  res.header('Duration-ms', new Date() - start);
  if (response.neo4j) {
    res.header('Neo4j', JSON.stringify(response.neo4j));
  }
  res.send(JSON.stringify(response.results));
}

function parseUrl(req, key) {
  return url.parse(req.url,true).query[key];
}

function parseBool (req, key) {
  return 'true' == url.parse(req.url,true).query[key];
}

/*
 * API Specs and Functions
 */

exports.list = {
  'spec': {
    "description" : "List all movies",
    "path" : "/movies",
    "notes" : "DOES THIS WORK Returns all movies",
    "summary" : "Find all movies",
    "method": "GET",
    "params" : [],
    "responseClass" : "List[Movie]",
    "errorResponses" : [swe.notFound('movies')],
    "nickname" : "getMovies"
  },
  'action': function (req, res) {
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();
    Movies.getAll(null, options, function (err, response) {
      if (err || !response.results) throw swe.notFound('movies');
      writeResponse(res, response, start);
    });
  }
};

exports.movieCount = {
  'spec': {
    "description" : "Movie count",
    "path" : "/movies/count",
    "notes" : "Movie count",
    "summary" : "Movie count",
    "method": "GET",
    "params" : [],
    "responseClass" : "Count",
    "errorResponses" : [swe.notFound('movies')],
    "nickname" : "movieCount"
  },
  'action': function (req, res) {
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();
    Movies.getAllCount(null, options, function (err, response) {
      // if (err || !response.results) throw swe.notFound('movies');
      writeResponse(res, response, start);
    });
  }
};

exports.findById = {
  'spec': {
    "description" : "find a movie",
    "path" : "/movies/{id}",
    "notes" : "Returns a movie based on ID",
    "summary" : "Find movie by ID",
    "method": "GET",
    "params" : [
      param.path("id", "ID of movie that needs to be fetched", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMovieById"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, start);
    };

    Movies.getById(params, options, callback);

  }
};

exports.findByTitle = {
  'spec': {
    "description" : "Find a movie",
    "path" : "/movies/title/{title}",
    "notes" : "Returns a movie based on title",
    "summary" : "Find movie by title",
    "method": "GET",
    "params" : [
      param.path("title", "Title of movie that needs to be fetched", "string")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('title'), swe.notFound('movie')],
    "nickname" : "getMovieByTitle"
  },
  'action': function (req,res) {
    var title = req.params.title;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!title) throw swe.invalid('title');

    var params = {
      title: title
    };

    Movies.getByTitle(params, options, function (err, response) {
        if (err) throw swe.notFound('movies');
        writeResponse(res, response, start);
      });

  }
};

exports.findByGenre = {
  'spec': {
    "description" : "Find a movie",
    "path" : "/movies/genre/{id}",
    "notes" : "Returns movies based on genre id",
    "summary" : "Find movie by genre id",
    "method": "GET",
    "params" : [
      param.path("id", "The id of the genre", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movies')],
    "nickname" : "getMoviesByGenre"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, start);
    };

    Movies.getByGenre(params, options, callback);
  }
};

exports.findMoviesByDateRange = {
  'spec': {
    "description" : "Find movies",
    "path" : "/movies/daterange/{start}/{end}",
    "notes" : "Returns movies between a year range",
    "summary" : "Find movie by year range",
    "method": "GET",
    "params" : [
      param.path("start", "Year that the movie was released on or after", "integer"),
      param.path("end", "Year that the movie was released before", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('start'), swe.invalid('end'), swe.notFound('movie')],
    "nickname" : "getMoviesByDateRange"
  },
  'action': function (req,res) {
    var start = req.params.start;
    var end = req.params.end;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!start) throw swe.invalid('start');
    if (!end) throw swe.invalid('end');

    var params = {
      start: start,
      end: end
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getByDateRange(params, options, callback);

  }
};

exports.findMoviesbyDirector = {
  'spec': {
    "description" : "Find a director",
    "path" : "/movies/directed_by/{id}",
    "notes" : "Returns movies directed by a person",
    "summary" : "Returns movies directed by a person",
    "method": "GET",
    "params" : [
      param.path("id", "Id of the director person", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('person')],
    "nickname" : "findMoviesbyDirector"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('person');
      writeResponse(res, response, start);
    };

    Movies.getMoviesbyDirector(params, options, callback);
  }
};

exports.findMoviesByActor = {
  'spec': {
    "description" : "Find movies acted in by some actor person",
    "path" : "/movies/acted_in_by/{id}",
    "notes" : "Returns movies that a person acted in",
    "summary" : "Find movies by actor",
    "method": "GET",
    "params" : [
      param.path("id", "id of the actor who acted in the movies movies", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMoviesByActor"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getByActor(params, options, callback);

  }
};

exports.findMoviesByWriter = {
  'spec': {
    "description" : "Find movies written by some person",
    "path" : "/movies/written_by/{id}",
    "notes" : "Returns movies that a person wrote in",
    "summary" : "Find movies by writer",
    "method": "GET",
    "params" : [
      param.path("id", "id of the writer who wrote the movies", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMoviesByWriter"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getMoviesByWriter(params, options, callback);

  }
};

<commit_msg>remove some extra text in docs<commit_after>// movies.js
var Movies = require('../models/movies');
var sw = require("swagger-node-express");
var param = sw.params;
var url = require("url");
var swe = sw.errors;
var _ = require('underscore');

/*
 *  Util Functions
 */

function writeResponse (res, response, start) {
  sw.setHeaders(res);
  res.header('Duration-ms', new Date() - start);
  if (response.neo4j) {
    res.header('Neo4j', JSON.stringify(response.neo4j));
  }
  res.send(JSON.stringify(response.results));
}

function parseUrl(req, key) {
  return url.parse(req.url,true).query[key];
}

function parseBool (req, key) {
  return 'true' == url.parse(req.url,true).query[key];
}

/*
 * API Specs and Functions
 */

exports.list = {
  'spec': {
    "description" : "List all movies",
    "path" : "/movies",
    "notes" : "Returns all movies",
    "summary" : "Find all movies",
    "method": "GET",
    "params" : [],
    "responseClass" : "List[Movie]",
    "errorResponses" : [swe.notFound('movies')],
    "nickname" : "getMovies"
  },
  'action': function (req, res) {
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();
    Movies.getAll(null, options, function (err, response) {
      if (err || !response.results) throw swe.notFound('movies');
      writeResponse(res, response, start);
    });
  }
};

exports.movieCount = {
  'spec': {
    "description" : "Movie count",
    "path" : "/movies/count",
    "notes" : "Movie count",
    "summary" : "Movie count",
    "method": "GET",
    "params" : [],
    "responseClass" : "Count",
    "errorResponses" : [swe.notFound('movies')],
    "nickname" : "movieCount"
  },
  'action': function (req, res) {
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();
    Movies.getAllCount(null, options, function (err, response) {
      // if (err || !response.results) throw swe.notFound('movies');
      writeResponse(res, response, start);
    });
  }
};

exports.findById = {
  'spec': {
    "description" : "find a movie",
    "path" : "/movies/{id}",
    "notes" : "Returns a movie based on ID",
    "summary" : "Find movie by ID",
    "method": "GET",
    "params" : [
      param.path("id", "ID of movie that needs to be fetched", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMovieById"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, start);
    };

    Movies.getById(params, options, callback);

  }
};

exports.findByTitle = {
  'spec': {
    "description" : "Find a movie",
    "path" : "/movies/title/{title}",
    "notes" : "Returns a movie based on title",
    "summary" : "Find movie by title",
    "method": "GET",
    "params" : [
      param.path("title", "Title of movie that needs to be fetched", "string")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('title'), swe.notFound('movie')],
    "nickname" : "getMovieByTitle"
  },
  'action': function (req,res) {
    var title = req.params.title;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!title) throw swe.invalid('title');

    var params = {
      title: title
    };

    Movies.getByTitle(params, options, function (err, response) {
        if (err) throw swe.notFound('movies');
        writeResponse(res, response, start);
      });

  }
};

exports.findByGenre = {
  'spec': {
    "description" : "Find a movie",
    "path" : "/movies/genre/{id}",
    "notes" : "Returns movies based on genre id",
    "summary" : "Find movie by genre id",
    "method": "GET",
    "params" : [
      param.path("id", "The id of the genre", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movies')],
    "nickname" : "getMoviesByGenre"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, start);
    };

    Movies.getByGenre(params, options, callback);
  }
};

exports.findMoviesByDateRange = {
  'spec': {
    "description" : "Find movies",
    "path" : "/movies/daterange/{start}/{end}",
    "notes" : "Returns movies between a year range",
    "summary" : "Find movie by year range",
    "method": "GET",
    "params" : [
      param.path("start", "Year that the movie was released on or after", "integer"),
      param.path("end", "Year that the movie was released before", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('start'), swe.invalid('end'), swe.notFound('movie')],
    "nickname" : "getMoviesByDateRange"
  },
  'action': function (req,res) {
    var start = req.params.start;
    var end = req.params.end;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!start) throw swe.invalid('start');
    if (!end) throw swe.invalid('end');

    var params = {
      start: start,
      end: end
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getByDateRange(params, options, callback);

  }
};

exports.findMoviesbyDirector = {
  'spec': {
    "description" : "Find a director",
    "path" : "/movies/directed_by/{id}",
    "notes" : "Returns movies directed by a person",
    "summary" : "Returns movies directed by a person",
    "method": "GET",
    "params" : [
      param.path("id", "Id of the director person", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('person')],
    "nickname" : "findMoviesbyDirector"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };
    var start = new Date();

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('person');
      writeResponse(res, response, start);
    };

    Movies.getMoviesbyDirector(params, options, callback);
  }
};

exports.findMoviesByActor = {
  'spec': {
    "description" : "Find movies acted in by some actor person",
    "path" : "/movies/acted_in_by/{id}",
    "notes" : "Returns movies that a person acted in",
    "summary" : "Find movies by actor",
    "method": "GET",
    "params" : [
      param.path("id", "id of the actor who acted in the movies movies", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMoviesByActor"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getByActor(params, options, callback);

  }
};

exports.findMoviesByWriter = {
  'spec': {
    "description" : "Find movies written by some person",
    "path" : "/movies/written_by/{id}",
    "notes" : "Returns movies that a person wrote in",
    "summary" : "Find movies by writer",
    "method": "GET",
    "params" : [
      param.path("id", "id of the writer who wrote the movies", "integer")
    ],
    "responseClass" : "Movie",
    "errorResponses" : [swe.invalid('id'), swe.notFound('movie')],
    "nickname" : "getMoviesByWriter"
  },
  'action': function (req,res) {
    var id = req.params.id;
    var options = {
      neo4j: parseBool(req, 'neo4j')
    };

    if (!id) throw swe.invalid('id');

    var params = {
      id: id
    };

    var callback = function (err, response) {
      if (err) throw swe.notFound('movie');
      writeResponse(res, response, new Date());
    };

    Movies.getMoviesByWriter(params, options, callback);

  }
};

<|endoftext|>


<commit_before>/*
 * meteor-rssfeed — This package publishes data as rss feeds, it takes params and listens on the url "/rss"
 */

// Polyfill
if(!Array.isArray) {
  Array.isArray = function (vArg) {
    return Object.prototype.toString.call(vArg) === '[object Array]';
  };
}

var url = Npm.require('url');

var feedHandlers = {};

var nameFollowsConventions = function(name) {
  // TODO: Expand check to follow URI name specs or test name to follow
  // Meteor.Collection naming convention
  return name === '' + name;
};

RssFeed = {
  publish: function(name, handlerFunction) {
    if (!nameFollowsConventions(name)) {
      throw new Error('RssFeed publish expects valid name to be of type String');
    }
    // Check if the handlerFunction is actually a function
    if (typeof handlerFunction !== 'function') {
      throw new Error('RssFeed publish expects feed handler as a function');
    }

    // Add the handler function to feedHandlers
    feedHandlers[name] = handlerFunction;
  },
  unpublish: function(name) {
    if (!nameFollowsConventions(name)) {
      throw new Error('RssFeed unpublish expects valid name to be of type String');
    }
    // We could do a check to se if the name is allready found, if not then
    // throw an error, but for now we are silent
    delete feedHandlers[name];
  },
  createTag: function(key, value) {
    if (typeof key === 'undefined') {
      return value;
    }

    return '<' + key + '>' + value + '</' + key + '>';
  },
  cdataValue: function(value) {
    return '<![CDATA[' + value + ']]>';
  },
  objectToXML: function(sourceObject) {
    // The returning string
    var result = '';

    // We do a one level iteration of the object
    for (var key in sourceObject) {
      if (sourceObject.hasOwnProperty(key)) {
        var value = sourceObject[key];
        // We create <key>value</key>
        if (typeof value === 'object') {
          // If date
          if (value instanceof Date) {
            // We extract the date into correct format
            // If Date we produce the formatted date Mon, 06 Sep 2009 16:20:00 +0000
            result += this.createTag(key, value.toUTCString());
          } else {
            if (Array.isArray(value)) {
              // If array we repeat the tag n times with values?
              for (var i = 0; i < value.length; i++) {
                result += this.createTag(key, this.objectToXML(value[i]));
              }
            } else {
              // If objects we do nothing - one could create nested xml?
              result += this.createTag(key, this.objectToXML(value));
            }
          }

        } else {
          if (typeof value === 'function') {
            // Should we execute the function and return the value into tag?
            value = value();
          }
          // But if text then incapsulate in <![CDATA[ ]]>
          result += this.createTag(key, value);
        }
      }
    }

    return result;
  }
};

// Handle the actual connection
WebApp.connectHandlers.use(function(req, res, next) {
  rssurl = /^\/rss/gi;

  if (!rssurl.test(req.url)) {
    return next();
  }

  var parsed = url.parse(req.url, true);
  var folders = parsed.pathname.split('/');

  feedName = folders[2];

  // If feedHandler not found or somehow the feedhandler is not a function then
  // return a 404
  if (!feedHandlers[feedName] || typeof feedHandlers[feedName] !== 'function') {
    res.writeHead(404);
    res.end();
    return;
  }

  var self = {
    query: parsed.query,
    res: res
  };

  // Helper functions this scope
  Fiber = Npm.require('fibers');
  fileHandler = Fiber(function(self) {
    // We fetch feed data from feedHandler, the handler uses the this.addItem()
    // function to populate the feed, this way we have better check control and
    // better error handling + messages

    var feedObject = {
      channel: {
        title:'',
        description:'',
        link: '',
        lastBuildDate: '',
        pubDate: '',
        ttl: '',
        generator: 'Meteor RSS Feed',
        item: [] // title, description, link, guid, pubDate
      }
    };

    var feedScope = {
      cdata: RssFeed.cdataValue,
      setValue: function(key, value) {
        feedObject.channel[key] = value;
      },
      addItem: function(itemObject) {
        feedObject.channel.item.push(itemObject);
      }
    };

    feedHandlers[feedName].apply(feedScope, [self.query]);

    var feed = '<?xml version="1.0" encoding="UTF-8" ?>\n';
    feed += '<rss version="2.0">';
    feed += RssFeed.objectToXML(feedObject);
    feed += '</rss>';

    var feedBuffer = new Buffer(feed);

    self.res.setHeader('Content-Type', 'application/rss+xml; charset=utf-8');
    self.res.setHeader('Content-Length', feedBuffer.length);
    self.res.end(feedBuffer);

  });
  // Run feed handler
  try {
    fileHandler.run(self);
  } catch(err) {
    res.writeHead(404);
    res.end();
    throw new Error('Error in feed handler function, name ' + feedName + ' Error: ' + err.message);
  }

  return;
});
<commit_msg>Added trailing slash to the rssurl variable.<commit_after>/*
 * meteor-rssfeed — This package publishes data as rss feeds, it takes params and listens on the url "/rss"
 */

// Polyfill
if(!Array.isArray) {
  Array.isArray = function (vArg) {
    return Object.prototype.toString.call(vArg) === '[object Array]';
  };
}

var url = Npm.require('url');

var feedHandlers = {};

var nameFollowsConventions = function(name) {
  // TODO: Expand check to follow URI name specs or test name to follow
  // Meteor.Collection naming convention
  return name === '' + name;
};

RssFeed = {
  publish: function(name, handlerFunction) {
    if (!nameFollowsConventions(name)) {
      throw new Error('RssFeed publish expects valid name to be of type String');
    }
    // Check if the handlerFunction is actually a function
    if (typeof handlerFunction !== 'function') {
      throw new Error('RssFeed publish expects feed handler as a function');
    }

    // Add the handler function to feedHandlers
    feedHandlers[name] = handlerFunction;
  },
  unpublish: function(name) {
    if (!nameFollowsConventions(name)) {
      throw new Error('RssFeed unpublish expects valid name to be of type String');
    }
    // We could do a check to se if the name is allready found, if not then
    // throw an error, but for now we are silent
    delete feedHandlers[name];
  },
  createTag: function(key, value) {
    if (typeof key === 'undefined') {
      return value;
    }

    return '<' + key + '>' + value + '</' + key + '>';
  },
  cdataValue: function(value) {
    return '<![CDATA[' + value + ']]>';
  },
  objectToXML: function(sourceObject) {
    // The returning string
    var result = '';

    // We do a one level iteration of the object
    for (var key in sourceObject) {
      if (sourceObject.hasOwnProperty(key)) {
        var value = sourceObject[key];
        // We create <key>value</key>
        if (typeof value === 'object') {
          // If date
          if (value instanceof Date) {
            // We extract the date into correct format
            // If Date we produce the formatted date Mon, 06 Sep 2009 16:20:00 +0000
            result += this.createTag(key, value.toUTCString());
          } else {
            if (Array.isArray(value)) {
              // If array we repeat the tag n times with values?
              for (var i = 0; i < value.length; i++) {
                result += this.createTag(key, this.objectToXML(value[i]));
              }
            } else {
              // If objects we do nothing - one could create nested xml?
              result += this.createTag(key, this.objectToXML(value));
            }
          }

        } else {
          if (typeof value === 'function') {
            // Should we execute the function and return the value into tag?
            value = value();
          }
          // But if text then incapsulate in <![CDATA[ ]]>
          result += this.createTag(key, value);
        }
      }
    }

    return result;
  }
};

// Handle the actual connection
WebApp.connectHandlers.use(function(req, res, next) {
  rssurl = /^\/rss\//gi;

  if (!rssurl.test(req.url)) {
    return next();
  }

  var parsed = url.parse(req.url, true);
  var folders = parsed.pathname.split('/');

  feedName = folders[2];

  // If feedHandler not found or somehow the feedhandler is not a function then
  // return a 404
  if (!feedHandlers[feedName] || typeof feedHandlers[feedName] !== 'function') {
    res.writeHead(404);
    res.end();
    return;
  }

  var self = {
    query: parsed.query,
    res: res
  };

  // Helper functions this scope
  Fiber = Npm.require('fibers');
  fileHandler = Fiber(function(self) {
    // We fetch feed data from feedHandler, the handler uses the this.addItem()
    // function to populate the feed, this way we have better check control and
    // better error handling + messages

    var feedObject = {
      channel: {
        title:'',
        description:'',
        link: '',
        lastBuildDate: '',
        pubDate: '',
        ttl: '',
        generator: 'Meteor RSS Feed',
        item: [] // title, description, link, guid, pubDate
      }
    };

    var feedScope = {
      cdata: RssFeed.cdataValue,
      setValue: function(key, value) {
        feedObject.channel[key] = value;
      },
      addItem: function(itemObject) {
        feedObject.channel.item.push(itemObject);
      }
    };

    feedHandlers[feedName].apply(feedScope, [self.query]);

    var feed = '<?xml version="1.0" encoding="UTF-8" ?>\n';
    feed += '<rss version="2.0">';
    feed += RssFeed.objectToXML(feedObject);
    feed += '</rss>';

    var feedBuffer = new Buffer(feed);

    self.res.setHeader('Content-Type', 'application/rss+xml; charset=utf-8');
    self.res.setHeader('Content-Length', feedBuffer.length);
    self.res.end(feedBuffer);

  });
  // Run feed handler
  try {
    fileHandler.run(self);
  } catch(err) {
    res.writeHead(404);
    res.end();
    throw new Error('Error in feed handler function, name ' + feedName + ' Error: ' + err.message);
  }

  return;
});
<|endoftext|>


<commit_before>if (simpleStorage.get('token')) {
  $('#account-btn').show();
} else {
  $('#load-login-btn').show();
}

function showLoginForm() {
  $('#register-box').fadeOut('fast',function() {
      $('#login-box').fadeIn('fast');
      $('#modal-register-footer').fadeOut('fast',function() {
        $('#model-label-header').text('Login');
        $('#modal-login-footer').fadeIn('fast');
      });
  });
};

function showRegisterForm() {
  $('#login-box').fadeOut('fast',function() {
      $('#register-box').fadeIn('fast');
      $('#modal-login-footer').fadeOut('fast',function() {
        $('#model-label-header').text('Register');
        $('#modal-register-footer').fadeIn('fast');
      });
  });
};

var renderIndexPage = function() {
  var templatingFunction = Handlebars.compile($('#index-page-template').html());
  $.ajax({
    url: "http://localhost:3000/books",
    method: 'GET'
  }).done(function(books, textStatus, jqxhr){
    console.log(books);
    var html = templatingFunction(books);
    $("#page").html(html);
  }).fail(function(jqxhr, textStatus, errorThrown){
    console.log(books);
    console.log(textStatus);
    console.log(jqxhr.responseText);
  });
};

// ---------------------- Books --------------------------
var setCreateResultMessage = function(success) {
  if (success) {
    $('#create-book-result-message').addClass('bg-success message');
    $('#create-book-result-message').text('Your book was created successfully!');
    $("#create-book-result-message").css();
  } else {
    $("#create-book-result-message").addClass('bg-danger message');
    $("#create-book-result-message").text('Something went wrong!');
  }
}

var booksPageTemplate = Handlebars.compile($("#books-page-template").html());

var renderCreateBookPage = function(book) {
  var templatingFunction = Handlebars.compile($('#create-book-template').html());
  var html = templatingFunction(book);
  $("#page").html(html);
};

var renderDisplayBookPage = function(book) {
  var templatingFunction = Handlebars.compile($('#display-book-template').html());
  var html = templatingFunction(book);
  $("#page").html(html);
};

// ---------------------- Loans --------------------------

var renderCreateLoanPage = function(users, books) {
  var templatingFunction = Handlebars.compile($('#create-loan-template').html());
  var html = templatingFunction(users, books);
  $("#page").html(html);
};

$(document).ready(function() {
  Authenticator.init();

  renderIndexPage("Books List");

  $("#page").on("click", "#thumbnail-preview-btn", function() {
    var clicked_id = $(this).data('id');
    console.log("Clicked button number " + clicked_id);
    $.ajax({
      url: "http://localhost:3000/books/" + clicked_id,
      method: 'GET'
    }).done(function(book, textStatus, jqxhr){
      console.log(book);
      $("#page").html(renderDisplayBookPage(book));

    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(jqxhr.responseText);
    });
  });

  $("#create-a-book-dd-btn").on("click", function(){
    console.log("#create-a-book-dd-btn clicked");
    renderCreateBookPage();
  });

  //create book with Ajax
  $("#page").on("click", "#book-create", function() {
    var reader = new FileReader();

    reader.onload = function(event){
      $.ajax({
        url: 'http://localhost:3000/books',
        method: 'POST',
        headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
        data: {
          book: {
            title: $("#book-title").val(),
            author: $("#book-author").val(),
            year: $("#book-year").val(),
            price: $("#book-price").val(),
            image: event.target.result,
            url: $("#book-url").val()
          }
        }
      }).done(function(book, textStatus, jqxhr){
        console.log("Book created successfully");
        $("#book-title").text(book.title);
        $("#book-title").attr('readonly', 'readonly');
        $("#book-author").text(book.author);
        $("#book-author").attr('readonly', 'readonly');
        $("#book-year").text(book.year);
        $("#book-year").attr('readonly', 'readonly');
        $("#book-price").text(book.price);
        $("#book-price").attr('readonly', 'readonly');
        $("#book-url").text(book.url);
        $("#book-url").attr('readonly', 'readonly');
        setCreateResultMessage(true);
      }).fail(function(jqxhr, textStatus, errorThrown){
        console.log(textStatus);
        console.log(jqxhr.responseText);
        setCreateResultMessage(false);
      });
    };

    reader.readAsDataURL($('#book-image-upload')[0].files[0]);

  });

  //show user books
  $("#my-books").on("click", function() {
    console.log("my books clicked");

    $.ajax({
      url: "http://localhost:3000/books?limit=me",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      $("#page").html(booksPageTemplate({heading: "My Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING CURRENT USER'S books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show my loaned books
  $("#my-loaned-books").on("click", function() {
    console.log("my loaned books clicked");

    $.ajax({
      url: "http://localhost:3000/books/loaned",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      console.log(data);
      $("#page").html(booksPageTemplate({heading: "My Loaned Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING CURRENT USER'S books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show my borrowed books
  $("#my-borrowed-books").on("click", function() {
    console.log("my borrowed books clicked");

    $.ajax({
      url: "http://localhost:3000/books/borrowed",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      console.log(data);
      $("#page").html(booksPageTemplate({heading: "My Borrowed Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show all boks
  $("#books-show").on("click", function() {
    $("#book-label").html();

    $.ajax({
      url: "http://localhost:3000/books",
      method: 'GET' //,
      // headers: { Authorization: 'Token token=' + $('#token').val()}
    }).done(function(data, textStatus, jqxhr){
      $("#page").html(booksPageTemplate({heading: "All Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING ALL the books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // update Book with Ajax
  $("#book-update").on("click", function() {
    $.ajax({
      url: 'http://localhost:3000/books/' + $("#book-id").val(),
      method: 'PATCH',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
      data: {
        book: {
          title: $("#book-title").val(),
          author: $("#book-author").val(),
          year: $("#book-year").val(),
          price: $("#book-price").val(),
          url: $("#book-url").val(),
          status: $("#book-status").val()
        }
      }
    }).done(function(book, textStatus, jqxhr) {
      $("#book-label").html(bookTemplate(book));
    }).fail(function(jqxhr, textStatus, errorThrown) {
      console.log("textStatus: " + textStatus);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  //destroy Book with Ajax
  $("#book-destroy").on('click', function() {
   $.ajax({
     url: 'http://localhost:3000/books/' + $("#book-id").val(),
     method: 'DELETE'
   }).done(function(book, textStatus, jqxhr){
     console.log("Your book has been deleted, here is some data about it: " + data);
   }).fail(function(jqxhr, textStatus, errorThrown) {
    $("#book-label").html(jqxhr.responseText);
   });
  });

  // ------------------ Loan ---------------

  // show create loan page
  $("#create-a-loan-dd-btn").on("click", function() {
    console.log("#create-a-loan-dd-btn clicked");

    var users = {};
    var books = {};
    $('#page').load('partials/create-loan-form.html');
    $.ajax({
      url: "http://localhost:3000/users",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      var templatingFunction = Handlebars.compile($('#create-user-select-template').html());
      var html = templatingFunction({users: data.users});
      $('#loan-borrower-combo').html(html);
      users = data;
      console.log(users);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("Error in getting users");
      console.log(jqxhr.responseText);
    });

    $.ajax({
      url: "http://localhost:3000/books?limit=me",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      var templatingFunction = Handlebars.compile($('#create-book-select-template').html());
      var html = templatingFunction({books: data.books});
      $('#loan-book-combo').html(html);
      books = data;
      console.log(books);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("Error in getting books");
      console.log(jqxhr.responseText);
    });
    $("#loan-date").datepicker({format: 'YYYY-MM-DD'});

  });

  //create Loan with Ajax
  $("#page").on('click', "#loan-create", function() {
    console.log("Loan create clicked");
    var borrowe_id = $('loan-borrower-combo').selected_value;
    var book_id =
    $.ajax({
      url: 'http://localhost:3000/loans',
      method: 'POST',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
      data: {
        loan: {
          borrower_id: $("#loan-borrower-combo").val(),
          book_id: $("#loan-book-combo").val(),
          date_loaned: $("#loan-date").val(),
          loan_duration: $("#loan_duration").val()
        }
      }
    }).done(function(book, textStatus, jqxhr){
      console.log("Book created successfully");
      $("#book-title").text(book.title);
      $("#book-title").attr('readonly', 'readonly');
      $("#book-author").text(book.author);
      $("#book-author").attr('readonly', 'readonly');
      $("#book-year").text(book.year);
      $("#book-year").attr('readonly', 'readonly');
      $("#book-price").text(book.price);
      $("#book-price").attr('readonly', 'readonly');
      $("#book-url").text(book.url);
      $("#book-url").attr('readonly', 'readonly');
      setCreateResultMessage(true);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(textStatus);
      console.log(jqxhr.responseText);
      setCreateResultMessage(false);
    });
  });

  //update Loan with Ajax
  $("#loan-update").on('click', function(){
    $.ajax({
      url: 'http://localhost:3000/loans/' + $("#user-id").val(),
      method: 'PATCH',
      data: {
        loan: {
          name: $("#name").val(),
          born: $("#born").val(),
          died: $("#died").val()
        }
      }
    }).done(function(book, textStatus, jqxhr){
      console.log("I'm a robot that UPDATED a person.");
    }).fail(function(jqxhr, textStatus, errorThrown) {
      $("#loan-label").html(jqxhr.responseText);
    });
  });

  //destroy Loan with Ajax
  $("#loan-destroy").on('click', function(){
    $.ajax({
      url: 'http://localhost:3000/loans/' + $("#user-id").val(),
      method: 'DELETE'
    }).done(function(book, textStatus, jqxhr){
      console.log("This loan has been added to your list of deleted loans.");
    }).fail(function(jqxhr, textStatus, errorThrown) {
      $("#loan-label").html(jqxhr.responseText);
    });
  });
});
<commit_msg>Add event handler for update button<commit_after>if (simpleStorage.get('token')) {
  $('#account-btn').show();
} else {
  $('#load-login-btn').show();
}

function showLoginForm() {
  $('#register-box').fadeOut('fast',function() {
      $('#login-box').fadeIn('fast');
      $('#modal-register-footer').fadeOut('fast',function() {
        $('#model-label-header').text('Login');
        $('#modal-login-footer').fadeIn('fast');
      });
  });
};

function showRegisterForm() {
  $('#login-box').fadeOut('fast',function() {
      $('#register-box').fadeIn('fast');
      $('#modal-login-footer').fadeOut('fast',function() {
        $('#model-label-header').text('Register');
        $('#modal-register-footer').fadeIn('fast');
      });
  });
};

var renderIndexPage = function() {
  var templatingFunction = Handlebars.compile($('#index-page-template').html());
  $.ajax({
    url: "http://localhost:3000/books",
    method: 'GET'
  }).done(function(books, textStatus, jqxhr){
    console.log(books);
    var html = templatingFunction(books);
    $("#page").html(html);
  }).fail(function(jqxhr, textStatus, errorThrown){
    console.log(books);
    console.log(textStatus);
    console.log(jqxhr.responseText);
  });
};

// ---------------------- Books --------------------------
var setCreateResultMessage = function(success) {
  if (success) {
    $('#create-book-result-message').addClass('bg-success message');
    $('#create-book-result-message').text('Your book was created successfully!');
    $("#create-book-result-message").css();
  } else {
    $("#create-book-result-message").addClass('bg-danger message');
    $("#create-book-result-message").text('Something went wrong!');
  }
}

var booksPageTemplate = Handlebars.compile($("#books-page-template").html());

var renderCreateBookPage = function(book) {
  var templatingFunction = Handlebars.compile($('#create-book-template').html());
  var html = templatingFunction(book);
  $("#page").html(html);
};

var renderDisplayBookPage = function(book) {
  var templatingFunction = Handlebars.compile($('#display-book-template').html());
  var html = templatingFunction(book);
  $("#page").html(html);
};

// ---------------------- Loans --------------------------

var renderCreateLoanPage = function(users, books) {
  var templatingFunction = Handlebars.compile($('#create-loan-template').html());
  var html = templatingFunction(users, books);
  $("#page").html(html);
};

$(document).ready(function() {
  Authenticator.init();

  renderIndexPage("Books List");

  $("#page").on("click", "#thumbnail-preview-btn", function() {
    var clicked_id = $(this).data('id');
    console.log("Clicked button number " + clicked_id);
    $.ajax({
      url: "http://localhost:3000/books/" + clicked_id,
      method: 'GET'
    }).done(function(book, textStatus, jqxhr){
      console.log(book);
      $("#page").html(renderDisplayBookPage(book));

    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(jqxhr.responseText);
    });
  });

  $("#page").on("click", "#thumbnail-update-btn", function() {
    var clicked_id = $(this).data('id');
    console.log("Clicked button number " + clicked_id);
    $.ajax({
      url: "http://localhost:3000/books/" + clicked_id,
      method: 'GET'
    }).done(function(book, textStatus, jqxhr){
      console.log(book);
      $("#page").html(renderDisplayBookPage(book));

    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(jqxhr.responseText);
    });
  });

  $("#create-a-book-dd-btn").on("click", function(){
    console.log("#create-a-book-dd-btn clicked");
    renderCreateBookPage();
  });

  //create book with Ajax
  $("#page").on("click", "#book-create", function() {
    var reader = new FileReader();

    reader.onload = function(event){
      $.ajax({
        url: 'http://localhost:3000/books',
        method: 'POST',
        headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
        data: {
          book: {
            title: $("#book-title").val(),
            author: $("#book-author").val(),
            year: $("#book-year").val(),
            price: $("#book-price").val(),
            image: event.target.result,
            url: $("#book-url").val()
          }
        }
      }).done(function(book, textStatus, jqxhr){
        console.log("Book created successfully");
        $("#book-title").text(book.title);
        $("#book-title").attr('readonly', 'readonly');
        $("#book-author").text(book.author);
        $("#book-author").attr('readonly', 'readonly');
        $("#book-year").text(book.year);
        $("#book-year").attr('readonly', 'readonly');
        $("#book-price").text(book.price);
        $("#book-price").attr('readonly', 'readonly');
        $("#book-url").text(book.url);
        $("#book-url").attr('readonly', 'readonly');
        setCreateResultMessage(true);
      }).fail(function(jqxhr, textStatus, errorThrown){
        console.log(textStatus);
        console.log(jqxhr.responseText);
        setCreateResultMessage(false);
      });
    };

    reader.readAsDataURL($('#book-image-upload')[0].files[0]);

  });

  //show user books
  $("#my-books").on("click", function() {
    console.log("my books clicked");

    $.ajax({
      url: "http://localhost:3000/books?limit=me",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      $("#page").html(booksPageTemplate({heading: "My Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING CURRENT USER'S books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show my loaned books
  $("#my-loaned-books").on("click", function() {
    console.log("my loaned books clicked");

    $.ajax({
      url: "http://localhost:3000/books/loaned",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      console.log(data);
      $("#page").html(booksPageTemplate({heading: "My Loaned Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING CURRENT USER'S books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show my borrowed books
  $("#my-borrowed-books").on("click", function() {
    console.log("my borrowed books clicked");

    $.ajax({
      url: "http://localhost:3000/books/borrowed",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      console.log(data);
      $("#page").html(booksPageTemplate({heading: "My Borrowed Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // show all boks
  $("#books-show").on("click", function() {
    $("#book-label").html();

    $.ajax({
      url: "http://localhost:3000/books",
      method: 'GET' //,
      // headers: { Authorization: 'Token token=' + $('#token').val()}
    }).done(function(data, textStatus, jqxhr){
      $("#page").html(booksPageTemplate({heading: "All Books", books: data.books}));
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("There was an error while LISTING ALL the books, error: " + jqxhr);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  // update Book with Ajax
  $("#book-update").on("click", function() {
    $.ajax({
      url: 'http://localhost:3000/books/' + $("#book-id").val(),
      method: 'PATCH',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
      data: {
        book: {
          title: $("#book-title").val(),
          author: $("#book-author").val(),
          year: $("#book-year").val(),
          price: $("#book-price").val(),
          url: $("#book-url").val(),
          status: $("#book-status").val()
        }
      }
    }).done(function(book, textStatus, jqxhr) {
      $("#book-label").html(bookTemplate(book));
    }).fail(function(jqxhr, textStatus, errorThrown) {
      console.log("textStatus: " + textStatus);
      $("#book-label").html(jqxhr.responseText);
    });
  });

  //destroy Book with Ajax
  $("#book-destroy").on('click', function() {
   $.ajax({
     url: 'http://localhost:3000/books/' + $("#book-id").val(),
     method: 'DELETE'
   }).done(function(book, textStatus, jqxhr){
     console.log("Your book has been deleted, here is some data about it: " + data);
   }).fail(function(jqxhr, textStatus, errorThrown) {
    $("#book-label").html(jqxhr.responseText);
   });
  });

  // ------------------ Loan ---------------

  // show create loan page
  $("#create-a-loan-dd-btn").on("click", function() {
    console.log("#create-a-loan-dd-btn clicked");

    var users = {};
    var books = {};
    $('#page').load('partials/create-loan-form.html');
    $.ajax({
      url: "http://localhost:3000/users",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      var templatingFunction = Handlebars.compile($('#create-user-select-template').html());
      var html = templatingFunction({users: data.users});
      $('#loan-borrower-combo').html(html);
      users = data;
      console.log(users);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("Error in getting users");
      console.log(jqxhr.responseText);
    });

    $.ajax({
      url: "http://localhost:3000/books?limit=me",
      method: 'GET',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') }
    }).done(function(data, textStatus, jqxhr){
      var templatingFunction = Handlebars.compile($('#create-book-select-template').html());
      var html = templatingFunction({books: data.books});
      $('#loan-book-combo').html(html);
      books = data;
      console.log(books);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log("Error in getting books");
      console.log(jqxhr.responseText);
    });
    $("#loan-date").datepicker({format: 'YYYY-MM-DD'});

  });

  //create Loan with Ajax
  $("#page").on('click', "#loan-create", function() {
    console.log("Loan create clicked");
    var borrowe_id = $('loan-borrower-combo').selected_value;
    var book_id =
    $.ajax({
      url: 'http://localhost:3000/loans',
      method: 'POST',
      headers: { Authorization: 'Token token=' + simpleStorage.get('token') },
      data: {
        loan: {
          borrower_id: $("#loan-borrower-combo").val(),
          book_id: $("#loan-book-combo").val(),
          date_loaned: $("#loan-date").val(),
          loan_duration: $("#loan_duration").val()
        }
      }
    }).done(function(book, textStatus, jqxhr){
      console.log("Book created successfully");
      $("#book-title").text(book.title);
      $("#book-title").attr('readonly', 'readonly');
      $("#book-author").text(book.author);
      $("#book-author").attr('readonly', 'readonly');
      $("#book-year").text(book.year);
      $("#book-year").attr('readonly', 'readonly');
      $("#book-price").text(book.price);
      $("#book-price").attr('readonly', 'readonly');
      $("#book-url").text(book.url);
      $("#book-url").attr('readonly', 'readonly');
      setCreateResultMessage(true);
    }).fail(function(jqxhr, textStatus, errorThrown){
      console.log(textStatus);
      console.log(jqxhr.responseText);
      setCreateResultMessage(false);
    });
  });

  //update Loan with Ajax
  $("#loan-update").on('click', function(){
    $.ajax({
      url: 'http://localhost:3000/loans/' + $("#user-id").val(),
      method: 'PATCH',
      data: {
        loan: {
          name: $("#name").val(),
          born: $("#born").val(),
          died: $("#died").val()
        }
      }
    }).done(function(book, textStatus, jqxhr){
      console.log("I'm a robot that UPDATED a person.");
    }).fail(function(jqxhr, textStatus, errorThrown) {
      $("#loan-label").html(jqxhr.responseText);
    });
  });

  //destroy Loan with Ajax
  $("#loan-destroy").on('click', function(){
    $.ajax({
      url: 'http://localhost:3000/loans/' + $("#user-id").val(),
      method: 'DELETE'
    }).done(function(book, textStatus, jqxhr){
      console.log("This loan has been added to your list of deleted loans.");
    }).fail(function(jqxhr, textStatus, errorThrown) {
      $("#loan-label").html(jqxhr.responseText);
    });
  });
});
<|endoftext|>


<commit_before>var Controller = require("../controllers/controller.js");
var Login = require("../controllers/login");
var Profile = require("../controllers/profile");
var Chat = require("../controllers/chat");
var Upload = require("../controllers/upload");
var Job = require("../controllers/job");

module.exports = [

	{ path: "/public/{file*}",	method: "GET",				config: Controller.serveFile },
	{ path: "/",				method: "GET",				config: Controller.home },
	{ path: "/dashboard", 		method: "GET", 				config: Controller.dashboard },
	{ path: "/users", 			method: "GET", 				config: Controller.users },
	{ path: "/help", 			method: "GET", 				config: Controller.help },
	{ path: "/logout", 			method: "GET", 				config: Controller.logout },

	{ path: "/signup/social", 	method: "GET", 				config: Login.social },
	{ path: "/facebook",		method: ["GET", "POST"],	config: Login.facebook },
	{ path: "/google",			method: ["GET", "POST"],	config: Login.google },
	{ path: "/signup/iam", 		method: "GET", 				config: Login.iam },
	{ path: "/client", 			method: "POST", 			config: Login.client },
	{ path: "/photographer", 	method: "POST", 			config: Login.photographer },

	{ path: "/profile", 		method: "GET", 				config: Profile.view },
	{ path: "/profile/edit", 	method: "GET", 				config: Profile.edit },
	{ path: "/profile/edit", 	method: "POST", 			config: Profile.post },
	{ path: "/photo/delete", 	method: "POST", 			config: Profile.deletePhoto },

	{ path: "/upload", 			method: "GET", 				config: Upload.view },
	{ path: "/sign_s3", 		method: "GET", 				config: Upload.signS3 },
	{ path: "/submit_form", 	method: "POST", 			config: Upload.submit },

	{ path: "/chat2/{user*}", 	method: "POST", 			config: Chat.recipient },
	{ path: "/chat/{id*}", 		method: "GET", 				config: Chat.view},
	{ path: "/chat/{id*}", 		method: "POST", 			config: Chat.submit },

	{ path: "/newjob", 			method: "GET", 				config: Job.view },
	{ path: "/newjob", 			method: "POST", 			config: Job.post }

	] ;<commit_msg>routes for public<commit_after>var Controller = require("../controllers/controller.js");
var Profile = require("../controllers/profile");
var Upload = require("../controllers/upload");
var Login = require("../controllers/login");
var Chat = require("../controllers/chat");
var Job = require("../controllers/job");

module.exports = [

	{ path: "/public/{file*}",	method: "GET",				config: Controller.serveFile },
	{ path: "/",				method: "GET",				config: Controller.home },
	{ path: "/dashboard", 		method: "GET", 				config: Controller.dashboard },
	{ path: "/users", 			method: "GET", 				config: Controller.users },
	{ path: "/help", 			method: "GET", 				config: Controller.help },
	{ path: "/logout", 			method: "GET", 				config: Controller.logout },

	{ path: "/signup/social", 	method: "GET", 				config: Login.social },
	{ path: "/facebook",		method: ["GET", "POST"],	config: Login.facebook },
	{ path: "/google",			method: ["GET", "POST"],	config: Login.google },
	{ path: "/signup/iam", 		method: "GET", 				config: Login.iam },
	{ path: "/client", 			method: "POST", 			config: Login.client },
	{ path: "/photographer", 	method: "POST", 			config: Login.photographer },

	{ path: "/profile", 		method: "GET", 				config: Profile.view },
	{ path: "/profile/{id*}", 	method: "GET", 				config: Profile.publicView },
	{ path: "/profile/{id*}", 	method: "POST", 			config: Profile.publicPost },
	{ path: "/profile/edit", 	method: "GET", 				config: Profile.edit },
	{ path: "/profile/edit", 	method: "POST", 			config: Profile.post },
	{ path: "/photo/delete", 	method: "POST", 			config: Profile.deletePhoto },

	{ path: "/upload", 			method: "GET", 				config: Upload.view },
	{ path: "/sign_s3", 		method: "GET", 				config: Upload.signS3 },
	{ path: "/watermark", 		method: "GET", 				config: Upload.watermark },
	{ path: "/submit_form", 	method: "POST", 			config: Upload.submit },

	{ path: "/chat2/{id*}", 	method: "POST", 			config: Chat.recipient },
	{ path: "/chat/{id*}", 		method: "GET", 				config: Chat.view},
	{ path: "/chat/{id*}", 		method: "POST", 			config: Chat.submit },

	{ path: "/newjob", 			method: "GET", 				config: Job.view },
	{ path: "/newjob", 			method: "POST", 			config: Job.post }

	] ;<|endoftext|>


<commit_before>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 *
 * Google CDN, Latest jQuery
 * To use the default WordPress version of jQuery, go to lib/config.php and
 * remove or comment out: add_theme_support('jquery-cdn');
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {

      },
      finalize: function() {
          $("#promotions-crousel").owlCarousel({
              items : 3,
              itemsDesktop : [1199,3],
              itemsDesktopSmall : [979,3]
          });
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {

      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<commit_msg>Smooth scroll for anchors<commit_after>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 *
 * Google CDN, Latest jQuery
 * To use the default WordPress version of jQuery, go to lib/config.php and
 * remove or comment out: add_theme_support('jquery-cdn');
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
          $("#promotions-crousel").owlCarousel({
              items : 3,
              itemsDesktop : [1199,3],
              itemsDesktopSmall : [979,3]
          });

          $('a[href*=#]:not([href=#])').click(function() {
              if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
                  var target = $(this.hash);
                  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
                  if (target.length) {
                      $('html,body').animate({
                          scrollTop: target.offset().top
                      }, 1000);
                      return false;
                  }
              }
          });

      },
      finalize: function() {

        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {

      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    }
  };

  // The routing fires all common scripts, followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('Here\'s wechat api.');
});

module.exports = router;
<commit_msg>Remove another cm account.<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.send('Here\'s wechat api.');
});

router.get('/access', function(req, res, next) {
  res.send('无 Fuck 说.');
});

module.exports = router;
<|endoftext|>


<commit_before>/*! imageCover | fullScreen | typeScale | middlize | resImg | colymn | Paul Browne | GNU License | 2015 */
!function(){function a(a,b){var c=[window.innerWidth];return window.addEventListener("resize",function(){var d=window.innerWidth,e=c.length;c.push(d),c[e]!==c[e-1]&&(clearTimeout(b),b=setTimeout(a,200))}),a}helperize=function(){var a=window.innerWidth,b=document.getElementsByTagName("body")[0].style,c=document.querySelectorAll(".fullscreen,.fullheight"),d=document.querySelectorAll(".middlize,.vmid"),e=document.querySelectorAll(".icovr");b.fontSize=a/600+15+"px",b.lineHeight=a/8e3+1.4;for(var f=0;f<c.length;f++)c[f].style.minHeight=window.innerHeight+"px";for(var g=0;g<d.length;g++)d[g].style.top=(d[g].parentNode.offsetHeight-d[g].offsetHeight)/2+"px",d[g].parentNode.style.position="relative";for(var h=0;h<e.length;h++){if(!document.querySelectorAll(".icovr-cont").length){var i=document.createElement("div");i.className="icovr-cont",e[h].parentNode.insertBefore(i,e[h]).appendChild(e[h])}var j=e[h].parentNode.offsetWidth,k=e[h].parentNode.offsetHeight,l=j/k,m=e[h].naturalWidth,n=e[h].naturalHeight,o=m/n,p=e[h].style;l>=o&&(p.width="100%",p.height="auto",p.top=(k-n/(m/j))/2+"px",p.left=0),o>l&&(p.width="auto",p.height="100%",p.top=0,p.left=(j-m/(n/k))/2+"px")}},resImg=function(){var a=document.getElementsByTagName("img");if(0!==a.length)for(var b=function(a,b){return a.hasAttribute(b)},c=window.devicePixelRatio?window.devicePixelRatio:1,d=0;d<a.length;d++){var e=a[d],f=c*e.parentNode.offsetWidth,g="data-src",h=c&&b(e,"data-src-base2x")?"data-src-base2x":"data-src-base";if(b(e,g)){for(var i=b(e,h)?e.getAttribute(h):"",j=e.getAttribute(g),k=j.split(","),l=0;l<k.length;l++){var p,q,m=k[l].replace(":","||").split("||"),n=m[0],o=m[1];if(-1!==n.indexOf("<"))if(p=n.split("<"),k[l-1]){var r=k[l-1].split(/:(.+)/),s=r[0].split("<");q=f<=p[1]&&f>s[1]}else q=f<=p[1];else if(p=n.split(">"),k[l+1]){var t=k[l+1].split(/:(.+)/),u=t[0].split(">");q=f>=p[1]&&f<u[1]}else q=f>=p[1];if(q){var w,v=-1!==o.indexOf("//")?1:0;w=1===v?o:i+o,e.src!==w&&e.setAttribute("src",w);break}}e.addEventListener("load",helperize)}}},colymn=function(){function m(a){return RegExp(a+"-(col|center)-","g")}function n(a){return RegExp(a+"-center-\\d+(px|em)","g")}function o(a,b){return RegExp(a+"-"+b+"-\\d+-\\d+","g")}function p(a){return a.test(w[x].className)}function q(a){return w[x].className.match(a).toString().match(/(\d+|px|em)/g)}function r(a){var b=q(a),c=b[0]/b[1]*(100+e-e*b[1])+e*b[0]-e,d=parseFloat(w[x].parentNode.style.width),f=100/d*-(c+e)+"%";return f}function s(a){var b=q(a),c=100*b[0]/b[1]-(b[1]-b[0])*e/b[1]+"%";return c}function t(a){for(;"svg"!==a.nodeName&&(a=a.parentNode)&&"svg"!==a.nodeName;);return!!a}for(var a=window.innerWidth,b=window.innerHeight,c=document.querySelectorAll("*"),d=document.querySelectorAll(".colymn-clearfix"),e=4,f=300,g=300,h=440,i=640,j=1024,k=1440,l=0;l<d.length;l++)d[l].parentNode.removeChild(d[l]);for(var u=0,v=0;v<c.length;v++)if(!t(c[v]))for(var w=c[v].children,x=0;x<w.length;++x){var y=w[x].style,z="xx";a>f&&b>a&&p(m("pp"))&&(z="pp"),a>g&&a>b&&p(m("pl"))&&(z="pl"),a>h&&b>a&&p(m("tp"))&&(z="tp"),a>i&&a>b&&p(m("tl"))&&(z="tl"),a>j&&p(m("dt"))&&(z="dt"),a>=k&&p(m("hd"))&&(z="hd");var A=o(z,"left"),B=o(z,"right"),C=o(z,"(col|offset)"),D=o(z,"(left|right)"),E=o(z,"center"),F=o(z,"col"),G=m("\\w+"),H=n(z);if(p(G)&&(y.position="relative",y.display="block",y.marginRight=0,y.marginLeft=0,y["float"]="none",y.width="100%"),p(H)){var I=q(H);y.display="block",y.marginRight="auto",y.marginLeft="auto",y["float"]="none",y.width=I[0]+I[1]}if(p(E)&&(y.width=s(E),y["float"]="none",y.marginRight="auto",y.marginLeft="auto"),p(F)){if(y.width=s(F),y["float"]="left",y.marginLeft=e+"%","0"===q(F)[0]&&(y.display="none"),!p(D)){var J=q(C);if(J[2]||(J[2]=0,J[3]=1),.01>=u&&(y.marginLeft=0),J[2]){var K=J[2]/J[3]*(100+e-e*J[3])+e*J[2];y.marginLeft=K+e+"%",.01>=u&&(y.marginLeft=K+"%")}if(u+=J[0]/J[1]+J[2]/J[3],u>=.99){u-=1;var L=document.createElement("div");L.style.clear="both",L.className="colymn-clearfix",w[x].parentNode.insertBefore(L,w[x].nextSibling)}}p(A)&&(y.marginRight=e+"%",y.marginLeft=r(A)),p(B)&&(y["float"]="right",y.marginLeft=e+"%",y.marginRight=r(B))}}helperize(),resImg()},a(function(){colymn()})}();
<commit_msg>updated colymn with options<commit_after>/*! imageCover | fullScreen | typeScale | middlize | resImg | colymn | Paul Browne | GNU License | 2015 */
!function(){function a(a,b){var c=[window.innerWidth];return window.addEventListener("resize",function(){var d=window.innerWidth,e=c.length;c.push(d),c[e]!==c[e-1]&&(clearTimeout(b),b=setTimeout(a,200))}),a}helperize=function(){var a=window.innerWidth,b=document.getElementsByTagName("body")[0].style,c=document.querySelectorAll(".fullscreen,.fullheight"),d=document.querySelectorAll(".middlize,.vmid"),e=document.querySelectorAll(".icovr");b.fontSize=a/600+15+"px",b.lineHeight=a/8e3+1.4;for(var f=0;f<c.length;f++)c[f].style.minHeight=window.innerHeight+"px";for(var g=0;g<d.length;g++)d[g].style.top=(d[g].parentNode.offsetHeight-d[g].offsetHeight)/2+"px",d[g].parentNode.style.position="relative";for(var h=0;h<e.length;h++){if(!document.querySelectorAll(".icovr-cont").length){var i=document.createElement("div");i.className="icovr-cont",e[h].parentNode.insertBefore(i,e[h]).appendChild(e[h])}var j=e[h].parentNode.offsetWidth,k=e[h].parentNode.offsetHeight,l=j/k,m=e[h].naturalWidth,n=e[h].naturalHeight,o=m/n,p=e[h].style;l>=o&&(p.width="100%",p.height="auto",p.top=(k-n/(m/j))/2+"px",p.left=0),o>l&&(p.width="auto",p.height="100%",p.top=0,p.left=(j-m/(n/k))/2+"px")}},resImg=function(){var a=document.getElementsByTagName("img");if(0!==a.length)for(var b=function(a,b){return a.hasAttribute(b)},c=window.devicePixelRatio?window.devicePixelRatio:1,d=0;d<a.length;d++){var e=a[d],f=c*e.parentNode.offsetWidth,g="data-src",h=c&&b(e,"data-src-base2x")?"data-src-base2x":"data-src-base";if(b(e,g)){for(var i=b(e,h)?e.getAttribute(h):"",j=e.getAttribute(g),k=j.split(","),l=0;l<k.length;l++){var p,q,m=k[l].replace(":","||").split("||"),n=m[0],o=m[1];if(-1!==n.indexOf("<"))if(p=n.split("<"),k[l-1]){var r=k[l-1].split(/:(.+)/),s=r[0].split("<");q=f<=p[1]&&f>s[1]}else q=f<=p[1];else if(p=n.split(">"),k[l+1]){var t=k[l+1].split(/:(.+)/),u=t[0].split(">");q=f>=p[1]&&f<u[1]}else q=f>=p[1];if(q){var w,v=-1!==o.indexOf("//")?1:0;w=1===v?o:i+o,e.src!==w&&e.setAttribute("src",w);break}}e.addEventListener("load",helperize)}}};var c,b={margin:4,phonePortrait:300,phoneLandscape:300,tabletPortrait:440,tabletLandscape:640,desktop:1024,fullHD:1440};colymn=function(a){function p(a){return RegExp(a+"-(col|center)-","g")}function q(a){return RegExp(a+"-center-\\d+(px|em)","g")}function r(a,b){return RegExp(a+"-"+b+"-\\d+-\\d+","g")}function s(a){return a.test(z[A].className)}function t(a){return z[A].className.match(a).toString().match(/(\d+|px|em)/g)}function u(a){var b=t(a),c=b[0]/b[1]*(100+h-h*b[1])+h*b[0]-h,d=parseFloat(z[A].parentNode.style.width),e=100/d*-(c+h)+"%";return e}function v(a){var b=t(a),c=100*b[0]/b[1]-(b[1]-b[0])*h/b[1]+"%";return c}function w(a){for(;"svg"!==a.nodeName&&(a=a.parentNode)&&"svg"!==a.nodeName;);return!!a}c=arguments[0];for(var d=window.innerWidth,e=window.innerHeight,f=document.querySelectorAll("*"),g=document.querySelectorAll(".colymn-clearfix"),h=a&&a.margin?a.margin:b.margin,i=a&&a.phonePortrait?a.phonePortrait:b.phonePortrait,j=a&&a.phoneLandscape?a.phoneLandscape:b.phoneLandscape,k=a&&a.tabletPortrait?a.tabletPortrait:b.tabletPortrait,l=a&&a.tabletLandscape?a.tabletLandscape:b.tabletLandscape,m=a&&a.desktop?a.desktop:b.desktop,n=a&&a.fullHD?a.fullHD:b.fullHD,o=0;o<g.length;o++)g[o].parentNode.removeChild(g[o]);for(var x=0,y=0;y<f.length;y++)if(!w(f[y]))for(var z=f[y].children,A=0;A<z.length;++A){var B=z[A].style,C="xx";d>i&&e>d&&s(p("pp"))&&(C="pp"),d>j&&d>e&&s(p("pl"))&&(C="pl"),d>k&&e>d&&s(p("tp"))&&(C="tp"),d>l&&d>e&&s(p("tl"))&&(C="tl"),d>m&&s(p("dt"))&&(C="dt"),d>=n&&s(p("hd"))&&(C="hd");var D=r(C,"left"),E=r(C,"right"),F=r(C,"(col|offset)"),G=r(C,"(left|right)"),H=r(C,"center"),I=r(C,"col"),J=p("\\w+"),K=q(C);if(s(J)&&(B.position="relative",B.display="block",B.marginRight=0,B.marginLeft=0,B["float"]="none",B.width="100%"),s(K)){var L=t(K);B.display="block",B.marginRight="auto",B.marginLeft="auto",B["float"]="none",B.width=L[0]+L[1]}if(s(H)&&(B.width=v(H),B["float"]="none",B.marginRight="auto",B.marginLeft="auto"),s(I)){if(B.width=v(I),B["float"]="left",B.marginLeft=h+"%","0"===t(I)[0]&&(B.display="none"),!s(G)){var M=t(F);if(M[2]||(M[2]=0,M[3]=1),.01>=x&&(B.marginLeft=0),M[2]){var N=M[2]/M[3]*(100+h-h*M[3])+h*M[2];B.marginLeft=N+h+"%",.01>=x&&(B.marginLeft=N+"%")}if(x+=M[0]/M[1]+M[2]/M[3],x>=.99){x-=1;var O=document.createElement("div");O.style.clear="both",O.className="colymn-clearfix",z[A].parentNode.insertBefore(O,z[A].nextSibling)}}s(D)&&(B.marginRight=h+"%",B.marginLeft=u(D)),s(E)&&(B["float"]="right",B.marginLeft=h+"%",B.marginRight=u(E))}}helperize(),resImg()},a(function(){colymn(c)})}();
<|endoftext|>