<commit_before>'use strict';

const Axios = require('axios');
const https = require('https');
const config = require('config/config');
const accounts = require('freedom-accounts-util');

const { rejectUnauthorized } = config.CUDL;
const {
    base_url,
    client_id,
    user_agent,
    endpoints,
    client_secret
} = config.FREEDOM;

const DASHBOARD_SCOPES = config.ACCOUNTS_API.scopes.DASHBOARD;

module.exports = {
    get_user_information,
    get_oauth_access_token
};

function get_oauth_access_token(params) {
    params.client_id = client_id;
    params.client_secret = client_secret;

    return accounts.generate_token(DASHBOARD_SCOPES.USER_READONLY)
        .then(({access_token}) => {
            const url = `${base_url}${endpoints.OAUTH_ACCESS_TOKEN}`;
            const options = {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `bearer ${access_token}`,
                    'User-Agent': user_agent
                },
                httpsAgent: new https.Agent({
                    rejectUnauthorized: rejectUnauthorized
                })
            };

            return Axios.post(
                url,
                params,
                options
            );
        });
}

function get_user_information({ user_id, access_token }) {
    let url = `${base_url}${endpoints.USER_INFORMATION}${(user_id ? `/${user_id}` : '')}`;
    const options = {
        headers: {
            'User-Agent': user_agent
        },
        httpsAgent: new https.Agent({
            rejectUnauthorized: rejectUnauthorized
        })
    };

    return Axios.get(
        `${url}?access_token=${access_token}`,
        options
    );
}
<commit_msg>refactor: Changed the code to async/await<commit_after>'use strict';

const Axios = require('axios');
const https = require('https');
const config = require('config/config');
const accounts = require('freedom-accounts-util');

const { rejectUnauthorized } = config.CUDL;
const {
    base_url,
    client_id,
    user_agent,
    endpoints,
    client_secret
} = config.FREEDOM;

const DASHBOARD_SCOPES = config.ACCOUNTS_API.scopes.DASHBOARD;

module.exports = {
    get_user_information,
    get_oauth_access_token
};

async function get_oauth_access_token(params) {
    params.client_id = client_id;
    params.client_secret = client_secret;

    return await accounts.generate_token(DASHBOARD_SCOPES.USER_READONLY)
        .then(async ({access_token}) => {
            const url = `${base_url}${endpoints.OAUTH_ACCESS_TOKEN}`;
            const options = {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `bearer ${access_token}`,
                    'User-Agent': user_agent
                },
                httpsAgent: new https.Agent({
                    rejectUnauthorized: rejectUnauthorized
                })
            };

            return await Axios.post(
                url,
                params,
                options
            );
        });
}

async function get_user_information({ user_id, access_token }) {
    let url = `${base_url}${endpoints.USER_INFORMATION}${(user_id ? `/${user_id}` : '')}`;
    const options = {
        headers: {
            'User-Agent': user_agent
        },
        httpsAgent: new https.Agent({
            rejectUnauthorized: rejectUnauthorized
        })
    };

    return await Axios.get(
        `${url}?access_token=${access_token}`,
        options
    );
}
<|endoftext|>


<commit_before>module.exports = function karmaConfig(config) {
    config.set({

    browsers: [ 'Chrome' ],

    singleRun: true,

    frameworks: [ 'mocha' ],

    files: [
      'tests.webpack.js'
    ],

    preprocessors: {
      'tests.webpack.js': [ 'webpack', 'sourcemap' ]
    },

    reporters: [ 'dots', 'coverage', 'coveralls' ],

    junitReporter: {
      outputDir: './web/target/karma-tests-results',
      suite: ''
    },

    coverageReporter: {
      dir: './coverage/',
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'cobertura', subdir: '.', file: 'cobertura.txt' },
        { type: 'lcovonly', subdir: '.' }
      ]
  },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          { test: /\.jsx$/, loader: 'babel-loader' }
        ],
        postLoaders: [{
            test: /\.jsx$/,
            exclude: /(__tests__|node_modules|legacy)\//,
            loader: 'istanbul-instrumenter'
        }]
      },
      resolve: {
          extensions: ['', '.js', '.json', '.jsx']
      }
    },

    webpackServer: {
      noInfo: true
    }

  });
};
<commit_msg>fixed code compression when debugging. close #42<commit_after>module.exports = function karmaConfig(config) {
    var postLoaders = [];
    // postloader compiles the jsx
    // so is needed only for coverage test, not in continuostest
    // assume singleRun = false means you are debugging
    if (config.singleRun) {
        postLoaders.push({
            test: /\.jsx$/,
            exclude: /(__tests__|node_modules|legacy)\//,
            loader: 'istanbul-instrumenter'
        });
    }
    config.set({

    browsers: [ 'Chrome' ],

    singleRun: true,

    frameworks: [ 'mocha' ],

    files: [
      'tests.webpack.js'
    ],

    preprocessors: {
      'tests.webpack.js': [ 'webpack', 'sourcemap' ]
    },

    reporters: [ 'dots', 'coverage', 'coveralls' ],

    junitReporter: {
      outputDir: './web/target/karma-tests-results',
      suite: ''
    },

    coverageReporter: {
      dir: './coverage/',
      reporters: [
        { type: 'html', subdir: 'report-html' },
        { type: 'cobertura', subdir: '.', file: 'cobertura.txt' },
        { type: 'lcovonly', subdir: '.' }
      ]
  },

    webpack: {
      devtool: 'inline-source-map',
      module: {
        loaders: [
          { test: /\.jsx$/, loader: 'babel-loader' }
        ],
        postLoaders: postLoaders
      },
      resolve: {
          extensions: ['', '.js', '.json', '.jsx']
      }
    },

    webpackServer: {
      noInfo: true
    }

  });
};
<|endoftext|>


<commit_before>var document = require('global/document');
var value = require('observ');
var struct = require('observ-struct');
var Delegator = require('dom-delegator');
var mainLoop = require('main-loop');
var h = require('virtual-dom/virtual-hyperscript');
var sendChange = require('value-event/change');
var find = require('lodash.find');
var diff = require('virtual-dom/vtree/diff');
var patch = require('virtual-dom/vdom/patch');
var create = require('virtual-dom/vdom/create-element');
var extend = require('xtend');
var sortBy = require('lodash.sortby');

var courses = require('./catalog');

function channels(funcs, context) {
  return Object.keys(funcs).reduce(createHandle, {});

  function createHandle(acc, name) {
    var handle = Delegator.allocateHandle(funcs[name].bind(null, context));
    acc[name] = handle;
    return acc;
  }
}

function mercury(obj) {
  var copy = extend(obj);
  var copyChannels = copy.channels;
  var copyHandles = copy.handles;

  if (copyChannels) {
    copy.channels = value(null);
  }
  else if (copyHandles) {
    copy.handles = value(null);
  }

  var observ = struct(copy);

  if (copyChannels) {
    observ.channels.set(channels(copyChannels, observ));
  }
  else if (copyHandles) {
    observ.handles.set(channels(copyHandles, observ));
  }

  return observ;
}

function change(state, data) {
  console.log('change');
  state.query.set(data.query);
}

var state = mercury({
  query: value(''),
  channels: {
    change: change
  }
});

Delegator();

var loop = mainLoop(state(), render, {
  diff: diff,
  create: create,
  patch: patch
});

document.body.appendChild(loop.target);
state(loop.update);

function prerequisites(course) {
  var preqs = course.prerequisites;
  if (preqs) {
    var r = preqs.match(/[A-Z]{3}[0-9]{4}C*/g);
    console.log(r);
    if (r) {
      var c = find(courses, {'code': r[0]});
      console.log(c);
      if (c) {
        return h('li', [
          'Prerequisites: ' +
          preqs.substring(0, preqs.indexOf(r)),
          h('abbr', {
            title: c.name
          }, r),
          preqs.substring(preqs.indexOf(r[0]) + r[0].length + 1)
        ]);
      }
    }
    return h('li', 'Prerequisites: ' + course.prerequisites);
  }
  return null;
}

function render(state) {

  // Filter out courses which do not contain the search query
  //
  // Instead of filtering out courses that do not contain the search query
  // verbatim, it is more appropriate to split the query into keywords, and
  // proceed to remove courses that do not contain every keyword.
  var results = courses.filter(function(course) {
    var valid = true;
    state.query.toLowerCase().split(' ').forEach(function(keyword) {
      if (valid) {
        valid = course.name.toLowerCase().indexOf(keyword) >= 0
                || course.code.toLowerCase().indexOf(keyword) >= 0
                || course.description.toLowerCase().indexOf(keyword) >= 0;
      }
    });
    return valid;
  });

  results = sortBy(results, 'code');

  var ret = [];

  var inputField = h('input', {
    type: 'search',
    name: 'query',
    value: String(state.query),
    'ev-event': sendChange(state.channels.change),
    autofocus: true
  });

  results.forEach(function(course) {
    ret.push(h('li', [
      h('h3', [
        h('span.code', course.code),
        h('span', ' ' + course.name)
      ]),
      h('ul.props', [
        h('li', 'Credits: ' + course.credits),
        prerequisites(course)
      ]),
      h('p', course.description)
    ]));
  });

  return h('div', [
    inputField,
    h('ul.results', ret)
  ]);
}
<commit_msg>Remove padding<commit_after>var document = require('global/document');
var value = require('observ');
var struct = require('observ-struct');
var Delegator = require('dom-delegator');
var mainLoop = require('main-loop');
var h = require('virtual-dom/virtual-hyperscript');
var sendChange = require('value-event/change');
var find = require('lodash.find');
var diff = require('virtual-dom/vtree/diff');
var patch = require('virtual-dom/vdom/patch');
var create = require('virtual-dom/vdom/create-element');
var extend = require('xtend');
var sortBy = require('lodash.sortby');

var courses = require('./catalog');

function channels(funcs, context) {
  return Object.keys(funcs).reduce(createHandle, {});

  function createHandle(acc, name) {
    var handle = Delegator.allocateHandle(funcs[name].bind(null, context));
    acc[name] = handle;
    return acc;
  }
}

function mercury(obj) {
  var copy = extend(obj);
  var copyChannels = copy.channels;
  var copyHandles = copy.handles;

  if (copyChannels) {
    copy.channels = value(null);
  }
  else if (copyHandles) {
    copy.handles = value(null);
  }

  var observ = struct(copy);

  if (copyChannels) {
    observ.channels.set(channels(copyChannels, observ));
  }
  else if (copyHandles) {
    observ.handles.set(channels(copyHandles, observ));
  }

  return observ;
}

function change(state, data) {
  console.log('change');
  state.query.set(data.query);
}

var state = mercury({
  query: value(''),
  channels: {
    change: change
  }
});

Delegator();

var loop = mainLoop(state(), render, {
  diff: diff,
  create: create,
  patch: patch
});

document.body.appendChild(loop.target);
state(loop.update);

function prerequisites(course) {
  var preqs = course.prerequisites;
  if (preqs) {
    var r = preqs.match(/[A-Z]{3}[0-9]{4}C*/g);
    console.log(r);
    if (r) {
      var c = find(courses, {'code': r[0]});
      console.log(c);
      if (c) {
        return h('li', [
          'Prerequisites: ' +
          preqs.substring(0, preqs.indexOf(r)),
          h('abbr', {
            title: c.name
          }, r),
          preqs.substring(preqs.indexOf(r[0]) + r[0].length + 1)
        ]);
      }
    }
    return h('li', 'Prerequisites: ' + course.prerequisites);
  }
  return null;
}

function render(state) {
  // Filter out courses which do not contain the search query
  //
  // Instead of filtering out courses that do not contain the search query
  // verbatim, it is more appropriate to split the query into keywords, and
  // proceed to remove courses that do not contain every keyword.
  var results = courses.filter(function(course) {
    var valid = true;
    state.query.toLowerCase().split(' ').forEach(function(keyword) {
      if (valid) {
        valid = course.name.toLowerCase().indexOf(keyword) >= 0
                || course.code.toLowerCase().indexOf(keyword) >= 0
                || course.description.toLowerCase().indexOf(keyword) >= 0;
      }
    });
    return valid;
  });

  results = sortBy(results, 'code');

  var ret = [];

  var inputField = h('input', {
    type: 'search',
    name: 'query',
    value: String(state.query),
    'ev-event': sendChange(state.channels.change),
    autofocus: true
  });

  results.forEach(function(course) {
    ret.push(h('li', [
      h('h3', [
        h('span.code', course.code),
        h('span', ' ' + course.name)
      ]),
      h('ul.props', [
        h('li', 'Credits: ' + course.credits),
        prerequisites(course)
      ]),
      h('p', course.description)
    ]));
  });

  return h('div', [
    inputField,
    h('ul.results', ret)
  ]);
}
<|endoftext|>


<commit_before>'use strict';

const _       = require('lodash');
const Context = require('./Context');
const sprintf = require('sprintf-js').sprintf;

class Action {

    /**
     * Perform the action
     * @param {Context} context
     * @param {Object} [options = {}]
     */
    run(context, options = {}) {
        throw new Error(sprintf('Run method not implemented for %s', this.getName()));
    }

    /**
     * Invoked before "run"
     * @param context
     * @param options
     */
    beforeRun(context, options) {
        return null;
    }

    /**
     * Invoked after "run"
     * @param context
     * @param options
     */
    afterRun(context, options) {
        return null;
    }

    /**
     * Get the action description
     * @returns {String}
     */
    getDescription() {
        return this.constructor.description ? this.constructor.description : '';
    }

    /**
     * By default, deduce the name of the action from the class name
     * @returns {String|null}
     */
    getName() {
        const matches = /(\w+)(?:Action)?/.exec(this.constructor.name);
        return matches ? _.kebabCase(matches[1]) : null;
    }

    /**
     * Make a Context instance based on the given arguments
     * @param {Object} args
     * @param {Boolean} [cli = false]
     * @returns {Context}
     */
    makeContext(args, cli) {
        return new (this.constructor.Context)(_.extend({}, this.parseContextArgs(args), {cli: !!cli}));
    }

    /**
     * Invoked when the action has completed successfully
     * @param {Context} context
     */
    onSuccess(context) {
        context.reporter.onSuccess(this, context.getUptime());
    }

    /**
     * Invoked when an error is thrown during the execution of the action
     * @param {Context} context
     * @param {Error} error
     */
    onError(context, error) {
        context.reporter.onError(this, error, context.getUptime());
    }

    /**
     * Get the available options for this action
     * @returns {Option[]}
     */
    getAvailableOptions() {
        return [
            require('./options/verbose')
        ];
    }

    /**
     * Get default options for Context
     * @returns {Object}
     */
    getContextDefaults() {
        return {};
    }

    /**
     * Return a function that will run the action
     * @param {Context} context
     * @param {Object} args
     * @return {Function}
     */
    prepare(context, args) {
        const options = this.parseArgs(args);
        return () => Promise.resolve(this.beforeRun(context, options))
            .then(() => this.run(context, options))
            .then(() => this.afterRun(context, options));
    }

    /**
     * Run the action from the CLI
     * @param {Object} args
     */
    executeCli(args) {
        const context = this.makeContext(args, true);
        let exec      = this.prepare(context, args);
        return exec().then(() => this.onSuccess(context), e => this.onError(context, e));
    }

    /**
     * Run the action via the API
     * @param {Object} args
     * @returns {Promise}
     */
    executeApi(args) {
        return this.prepare(this.makeContext(args), args)();
    }

    /**
     * Turn the args object into an options object
     * @param args
     * @returns {Object}
     */
    parseArgs(args) {
        return {};
    }

    /**
     * Get options for Context based on the given arguments
     * @param {Object} args
     * @returns {Object}
     */
    parseContextArgs(args) {
        let options = this.getContextDefaults();
        _.forEach(this.getAvailableOptions(), option => option.transformContextOptions(options, args));
        return options;
    }

    /**
     * Provision the yargs instance with this action's options
     * @param yargs
     */
    describeAction(yargs) {
        _.forEach(this.getAvailableOptions(), option => option.transformYargs(yargs));
        return yargs;
    }

    /**
     * Register the action into the yargs configuration
     * @param yargs
     */
    register(yargs) {
        return yargs.command(
            this.getName(),
            this.getDescription(),
            yargs => this.describeAction(yargs),
            args => this.executeCli(args)
        );
    }
}
Action.Context = Context;

module.exports = Action;<commit_msg>Call “done” at the end of the execution queue to ensure errors will be displayed<commit_after>'use strict';

const _       = require('lodash');
const Context = require('./Context');
const Promise = require('bluebird');
const sprintf = require('sprintf-js').sprintf;

class Action {

    /**
     * Perform the action
     * @param {Context} context
     * @param {Object} [options = {}]
     */
    run(context, options = {}) {
        throw new Error(sprintf('Run method not implemented for %s', this.getName()));
    }

    /**
     * Invoked before "run"
     * @param context
     * @param options
     */
    beforeRun(context, options) {
        return null;
    }

    /**
     * Invoked after "run"
     * @param context
     * @param options
     */
    afterRun(context, options) {
        return null;
    }

    /**
     * Get the action description
     * @returns {String}
     */
    getDescription() {
        return this.constructor.description ? this.constructor.description : '';
    }

    /**
     * By default, deduce the name of the action from the class name
     * @returns {String|null}
     */
    getName() {
        const matches = /(\w+)(?:Action)?/.exec(this.constructor.name);
        return matches ? _.kebabCase(matches[1]) : null;
    }

    /**
     * Make a Context instance based on the given arguments
     * @param {Object} args
     * @param {Boolean} [cli = false]
     * @returns {Context}
     */
    makeContext(args, cli) {
        return new (this.constructor.Context)(_.extend({}, this.parseContextArgs(args), {cli: !!cli}));
    }

    /**
     * Invoked when the action has completed successfully
     * @param {Context} context
     */
    onSuccess(context) {
        context.reporter.onSuccess(this, context.getUptime());
    }

    /**
     * Invoked when an error is thrown during the execution of the action
     * @param {Context} context
     * @param {Error} error
     */
    onError(context, error) {
        context.reporter.onError(this, error, context.getUptime());
    }

    /**
     * Get the available options for this action
     * @returns {Option[]}
     */
    getAvailableOptions() {
        return [
            require('./options/verbose')
        ];
    }

    /**
     * Get default options for Context
     * @returns {Object}
     */
    getContextDefaults() {
        return {};
    }

    /**
     * Return a function that will run the action
     * @param {Context} context
     * @param {Object} args
     * @return {Function}
     */
    prepare(context, args) {
        const options = this.parseArgs(args);
        return () => Promise.resolve(this.beforeRun(context, options))
            .then(() => this.run(context, options))
            .then(() => this.afterRun(context, options));
    }

    /**
     * Run the action from the CLI
     * @param {Object} args
     */
    executeCli(args) {
        const context = this.makeContext(args, true);
        let exec      = this.prepare(context, args);
        return exec().then(() => this.onSuccess(context), e => this.onError(context, e));
    }

    /**
     * Run the action via the API
     * @param {Object} args
     * @returns {Promise}
     */
    executeApi(args) {
        return this.prepare(this.makeContext(args), args)();
    }

    /**
     * Turn the args object into an options object
     * @param args
     * @returns {Object}
     */
    parseArgs(args) {
        return {};
    }

    /**
     * Get options for Context based on the given arguments
     * @param {Object} args
     * @returns {Object}
     */
    parseContextArgs(args) {
        let options = this.getContextDefaults();
        _.forEach(this.getAvailableOptions(), option => option.transformContextOptions(options, args));
        return options;
    }

    /**
     * Provision the yargs instance with this action's options
     * @param yargs
     */
    describeAction(yargs) {
        _.forEach(this.getAvailableOptions(), option => option.transformYargs(yargs));
        return yargs;
    }

    /**
     * Register the action into the yargs configuration
     * @param yargs
     */
    register(yargs) {
        return yargs.command(
            this.getName(),
            this.getDescription(),
            yargs => this.describeAction(yargs),
            args => Promise.resolve(this.executeCli(args)).done()
        );
    }
}
Action.Context = Context;

module.exports = Action;<|endoftext|>


<commit_before>var prototype
	, util = require('util')
	, path = require('path')
	, fs = require('fs')
	, step = require('stepup')
	, trycatch = require('trycatch')
	, _ = require('./_')
	, HermesClient = require('./hermesClient').HermesClient
	, cache = require('./connectionCache')
	, ZipRequestStream = require('../phonegap/ZipRequestStream')

function HermesFiles(inConfig) {
	arguments.callee.super_.call(this, inConfig)

	if (this.cache) {
		this.cache = cache
	}
}

util.inherits(HermesFiles, HermesClient)
prototype = Object.getPrototypeOf(HermesFiles.prototype)
HermesFiles.prototype.verbs = Object.create(prototype.verbs || {})

_.extend(true, HermesFiles.prototype, {
	name: "Hermes Files Service"
, execute: function(inVerb, req, res, next) {
		var self

		self = this

		console.log('HermesFiles, execute: ', inVerb)
		step(function(err) {
				next(err)
			}
		, function() {
				var connection

				if (req.params.config) {
					if (self.cache) {
						// locate a cached connection, if any
						// connection = self.cache.extract(key)
					}

					if (connection) {
						this(null, connection)
					} else if (self.connect) {
						self.connect(req.params.config, this)
					} else {
						this()
					}
				}
			}
		, function(connection) {
				req.connection = connection
				self.verbs[inVerb].call(self, req, res, this)
			}
		, function(data) {
				next(null, data)

				if (self.cache) {
					// cache this ftp instance for temporary reuse
					// self.cache.set(key, ftp)
				}
			}
		)
	}
, routes: {
		'/:verb/*': function(route, req, res) {
			console.log('HermesFiles, route: ', route)
			// strip leading slash from path
			req.params.path = _.ltrim(req.params[0], '/')

			prototype.routes[route].apply(this, arguments)
		}
	}
, verbs: {
		getFolder: function(req, res, next) {
			var zipRequestStream
				, self = this
				, outPath =  path.join(path.dirname(__filename), 'out' + Date.now() + '.zip')

			console.log('getFolder: ', req.params.fsPath, ', ', req.params.path)

			/*
			if (typeof uri.cookie !== 'string' && !!uri.cookie) {
				uri.cookie = Object.keys(uri.cookie).map(function(v) {
					return v+'="'+encodeURIComponent(JSON.stringify(uri.cookie[v]))+'"'
				}).join(';')
			}
			*/

			zipRequestStream = ZipRequestStream(function get(inPath, next) {
					console.log('HermesFiles, get: ', path.resolve(req.params.root, inPath))
					self._get(path.resolve(req.params.root, inPath), next)
				}
				, function list(inPath, next) {
					console.log('HermesFiles, list: ', path.resolve(req.params.root, inPath))
					self._list(req.params.root, inPath, next)
				})(req.params.fsPath)

			// Since phonegap requires multipart/form-data, which requires Content-length
			// We must pipe to fs first (or memory) and then pipe out
			// Does content-length get set when piping to res?
			zipRequestStream.pipe(fs.createWriteStream(outPath))
			zipRequestStream.on('end', function() {
				fs.stat(outPath, function(err, stat) {
					if (err) return next(err)

					var rs = fs.createReadStream(outPath)
					res.setHeader('Content-length', stat.size)
					rs.pipe(res)
					rs.on('end', fs.unlink.bind(fs, outPath))
				})
			})
			zipRequestStream.on('error', next)
		}
	}
})

module.exports = {
	HermesFiles: HermesFiles
}
<commit_msg>Produce a useful message when connecting to / on a Hermes service from a browser<commit_after>var prototype
	, util = require('util')
	, path = require('path')
	, fs = require('fs')
	, step = require('stepup')
	, trycatch = require('trycatch')
	, _ = require('./_')
	, HermesClient = require('./hermesClient').HermesClient
	, cache = require('./connectionCache')
	, ZipRequestStream = require('../phonegap/ZipRequestStream')

function HermesFiles(inConfig) {
	arguments.callee.super_.call(this, inConfig)

	if (this.cache) {
		this.cache = cache
	}
}

util.inherits(HermesFiles, HermesClient)
prototype = Object.getPrototypeOf(HermesFiles.prototype)
HermesFiles.prototype.verbs = Object.create(prototype.verbs || {})

_.extend(true, HermesFiles.prototype, {
	name: "Hermes Files Service"
, execute: function(inVerb, req, res, next) {
		var self

		self = this

		console.log('HermesFiles, execute: ', inVerb)
		step(function(err) {
				next(err)
			}
		, function() {
				var connection

				if (req.params.config) {
					if (self.cache) {
						// locate a cached connection, if any
						// connection = self.cache.extract(key)
					}

					if (connection) {
						this(null, connection)
					} else if (self.connect) {
						self.connect(req.params.config, this)
					} else {
						this()
					}
				}
			}
		, function(connection) {
				req.connection = connection
				self.verbs[inVerb].call(self, req, res, this)
			}
		, function(data) {
				next(null, data)

				if (self.cache) {
					// cache this ftp instance for temporary reuse
					// self.cache.set(key, ftp)
				}
			}
		)
	}
, routes: {
		'/': function(route, req, res) {
			console.log("Route /");
			res.send("<b>Hermes server running, use Ares to connect.</b>");
		},
		'/:verb/*': function(route, req, res) {
			console.log('HermesFiles, route: ', route)
			// strip leading slash from path
			req.params.path = _.ltrim(req.params[0], '/')

			prototype.routes[route].apply(this, arguments)
		}
	}
, verbs: {
		getFolder: function(req, res, next) {
			var zipRequestStream
				, self = this
				, outPath =  path.join(path.dirname(__filename), 'out' + Date.now() + '.zip')

			console.log('getFolder: ', req.params.fsPath, ', ', req.params.path)

			/*
			if (typeof uri.cookie !== 'string' && !!uri.cookie) {
				uri.cookie = Object.keys(uri.cookie).map(function(v) {
					return v+'="'+encodeURIComponent(JSON.stringify(uri.cookie[v]))+'"'
				}).join(';')
			}
			*/

			zipRequestStream = ZipRequestStream(function get(inPath, next) {
					console.log('HermesFiles, get: ', path.resolve(req.params.root, inPath))
					self._get(path.resolve(req.params.root, inPath), next)
				}
				, function list(inPath, next) {
					console.log('HermesFiles, list: ', path.resolve(req.params.root, inPath))
					self._list(req.params.root, inPath, next)
				})(req.params.fsPath)

			// Since phonegap requires multipart/form-data, which requires Content-length
			// We must pipe to fs first (or memory) and then pipe out
			// Does content-length get set when piping to res?
			zipRequestStream.pipe(fs.createWriteStream(outPath))
			zipRequestStream.on('end', function() {
				fs.stat(outPath, function(err, stat) {
					if (err) return next(err)

					var rs = fs.createReadStream(outPath)
					res.setHeader('Content-length', stat.size)
					rs.pipe(res)
					rs.on('end', fs.unlink.bind(fs, outPath))
				})
			})
			zipRequestStream.on('error', next)
		}
	}
})

module.exports = {
	HermesFiles: HermesFiles
}
<|endoftext|>


<commit_before>/* ==========================================================================
   Settings for webpack JavaScript bundling system.
   ========================================================================== */

const BROWSER_LIST = require( './browser-list-config' );
const webpack = require( 'webpack' );
const UglifyWebpackPlugin = require( 'uglifyjs-webpack-plugin' );

// Constants
const COMMON_BUNDLE_NAME = 'common.js';

/* Commmon webpack 'module' option used in each configuration.
   Runs code through Babel and uses global supported browser list. */
const COMMON_MODULE_CONFIG = {
  rules: [ {
    use: {
      loader: 'babel-loader?cacheDirectory=true',
      options: {
        presets: [ [ 'env', {
          targets: {
            browsers: BROWSER_LIST.LAST_2_PLUS_IE_9_AND_UP
          },
          debug: false
        } ] ]
      }
    }
  } ]
};

/* Set warnings to true to show linter-style warnings.
   Set mangle to false and beautify to true to debug the output code. */
const COMMON_UGLIFY_CONFIG = new UglifyWebpackPlugin( {
  parallel: true,
  uglifyOptions: {
    ie8: false,
    ecma: 5,
    warnings: false,
    mangle: true,
    output: {
      comments: false,
      beautify: false
    }
  }
} );

const COMMON_CHUNK_CONFIG = new webpack.optimize.SplitChunksPlugin( {
  name: COMMON_BUNDLE_NAME
} );

const STATS_CONFIG = {
  stats: {
    entrypoints: false
  }
};

const commonConf = {
  cache: true,
  module: COMMON_MODULE_CONFIG,
  mode: 'production',
  output: {
    filename: '[name]'
  },
  plugins: [
    COMMON_UGLIFY_CONFIG
  ],
  stats: STATS_CONFIG.stats
};

module.exports = commonConf;
<commit_msg>Remove COMMON_CHUNK_CONFIG<commit_after>/* ==========================================================================
   Settings for webpack JavaScript bundling system.
   ========================================================================== */

const BROWSER_LIST = require( './browser-list-config' );
const webpack = require( 'webpack' );
const UglifyWebpackPlugin = require( 'uglifyjs-webpack-plugin' );

// Constants
const COMMON_BUNDLE_NAME = 'common.js';

/* Commmon webpack 'module' option used in each configuration.
   Runs code through Babel and uses global supported browser list. */
const COMMON_MODULE_CONFIG = {
  rules: [ {
    use: {
      loader: 'babel-loader?cacheDirectory=true',
      options: {
        presets: [ [ 'env', {
          targets: {
            browsers: BROWSER_LIST.LAST_2_PLUS_IE_9_AND_UP
          },
          debug: false
        } ] ]
      }
    }
  } ]
};

/* Set warnings to true to show linter-style warnings.
   Set mangle to false and beautify to true to debug the output code. */
const COMMON_UGLIFY_CONFIG = new UglifyWebpackPlugin( {
  parallel: true,
  uglifyOptions: {
    ie8: false,
    ecma: 5,
    warnings: false,
    mangle: true,
    output: {
      comments: false,
      beautify: false
    }
  }
} );

const STATS_CONFIG = {
  stats: {
    entrypoints: false
  }
};

const commonConf = {
  cache: true,
  module: COMMON_MODULE_CONFIG,
  mode: 'production',
  output: {
    filename: '[name]'
  },
  plugins: [
    COMMON_UGLIFY_CONFIG
  ],
  stats: STATS_CONFIG.stats
};

module.exports = commonConf;
<|endoftext|>


<commit_before>/**
  Copyright 2010-2011 Mateusz Paprocki <mattpap@gmail.com>
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

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

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

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

py_builtins.hasattr = function(obj, name) {
    name = js(name);
    return obj["PY$" + name] === undefined ? False : True;
};

py_builtins.getattr = function(obj, name, value) {
    name = js(name);
    var val = obj["PY$" + name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
        }
    }
};

py_builtins.setattr = function(obj, name, value) {
    name = js(name);
    obj["PY$" + name] = value;
};

py_builtins.js_getattr = function(obj, name, value) {
    var val = obj[name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
        }
    }
};

py_builtins.js_setattr = function(obj, name, value) {
    obj[name] = value;
};

py_builtins.delattr = function(obj, name) {
    name = js(name);
    if (obj["PY$" + name] !== undefined) {
        delete obj["PY$" + name];
    } else {
        throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
    }
};

py_builtins.hash = function(obj) {
    if (obj.PY$__hash__ !== undefined) {
        return obj.PY$__hash__();
    } else if (typeof(obj) === 'number') {
        return obj === -1 ? -2 : obj;
    } else {
        throw py_builtins.AttributeError('__hash__');
    }
};

py_builtins.len = function(obj) {
    if (obj.PY$__len__ !== undefined) {
        return obj.PY$__len__();
    } else {
        throw py_builtins.AttributeError('__len__');
    }
};

py_builtins.dir = function(obj) {
    var res = list();
    for (var i in obj) {
        if (i.indexOf('PY$') !== -1) {
            res.PY$append($PY.str(i.substr(3)));
        }
    }
    res.PY$sort();
    return res;
};

py_builtins.cmp = function(x, y) {
  return x.PY$__cmp__(y);
};

py_builtins.repr = function(obj) {
    if (obj == undefined) {
        return "None";
    } else if (obj.PY$__repr__ !== undefined) {
        return obj.PY$__repr__(obj);
    } else if (obj.PY$__str__ !== undefined) {
        return obj.PY$__str__(obj);
    } else if (obj.toString !== undefined) {
        return str(obj.toString());
    } else {
        throw py_builtins.AttributeError('__repr__, __str__ or toString not found on ' + typeof(obj));
    }
};

py_builtins.range = function(start, end, step) {
    start = js(start);

    if (end === undefined) {
        end = start;
        start = 0;
    } else {
        end = js(end);
    }

    if (step === undefined) {
        step = 1;
    } else {
        step = js(step);
    }

    var seq = [];

    for (var i = start; i < end; i += step) {
        seq.push(i);
    }

    if (py_builtins.PY$__python3__)
        return iter(seq);
    else
        return list(seq);
};

py_builtins.xrange = function(start, end, step) {
    return iter(py_builtins.range(start, end, step));
};

py_builtins.map = function() {
    if (arguments.length < 2) {
        throw py_builtins.TypeError("py_builtins.map() requires at least two args");
    }

    if (arguments.length > 2) {
        throw py_builtins.NotImplementedError("only one sequence allowed in py_builtins.map()");
    }

    var func = arguments[0];
    var items = list();

    iterate(arguments[1], function(item) {
        items.PY$append(func(item));
    });

    if (py_builtins.PY$__python3__)
        return iter(items);
    else
        return items;
};

py_builtins.enumerate = function(obj) {
    if (arguments.length != 1) {
        throw py_builtins.NotImplementedError("enumerate() only supports 1 argument");
    }
    var items = list();
    var count = 0;
    iterate(obj, function(elm) {
                items.PY$append(tuple([count++, elm]));
            });
    return items;
};

py_builtins.zip = function() {
    if (!arguments.length) {
        return list();
    }

    var iters = list();
    var i;

    for (i = 0; i < arguments.length; i++) {
        iters.PY$append(iter(arguments[i]));
    }

    var items = list();

    while (true) {
        var item = list();

        for (i = 0; i < arguments.length; i++) {
            try {
                var value = iters.PY$__getitem__(i).PY$next();
            } catch (exc) {
                if (exc === $PY.StopIter || $PY.isinstance(exc, py_builtins.StopIteration)) {
                    return items;
                } else {
                    throw exc;
                }
            }

            item.PY$append(value);
        }

        items.PY$append(tuple(item));
    }
    return None;
};

py_builtins.isinstance = function(obj, cls) {
    if (cls.PY$__class__ === tuple) {
        var length = cls.PY$__len__();

        if (length.PY$__eq__($c0) == True) {
            return False;
        }

        for (var i = 0; i < length; i++) {
            var _cls = cls.PY$__getitem__(i);

            if ($PY.isinstance(obj, _cls)) {
                return True;
            }
        }

        return False;
    } else {
        var c = obj.PY$__class__;
        while (c) {
            if (c === cls)
                return True;
            c = c.PY$__super__;
        }
        return False;
    }
};

py_builtins.__not__ = function(obj) {
   if (obj.PY$__nonzero__ !== undefined) {
       return js(obj.PY$__nonzero__()) ? False : True;
   } else if (obj.PY$__len__ !== undefined) {
       return js(obj.PY$__len__()) === 0 ? True : False;
   } else {
       return js(obj) ? False : True;
   }
};

py_builtins.__is__ = function(a, b) {
    return a === b ? True : False;
};

py_builtins.max = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == True)
        throw py_builtins.ValueError("max() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__gt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.min = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == True)
        throw py_builtins.ValueError("min() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__lt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.sum = function(list) {
    var result = 0;

    iterate(list, function(item) {
        result += js(item);
    });

    return result;
};

py_builtins.filter = function(f, l) {
   var res = list();
   iterate(l, function(item) {
     if (f(item) == True) {
       res.PY$append(item);
     }
   });
   return res;
};

py_builtins.reduce = function(func, seq) {
    var initial;
    if (arguments.length == 3) {
        initial = arguments[2];
    } else {
        initial = null;
    }
    if (py_builtins.len(seq) < 2) {
        return initial;
    }
    var accum, start;
    if (arguments.length == 3) {
        accum = initial;
        start = 0;
    } else {
        accum = func(seq.PY$__getitem__(0), seq.PY$__getitem__(1));
        start = 2;
    }
    for (var i = start; i < py_builtins.len(seq)._js_(); i++) {
        accum = func(accum, seq.PY$__getitem__(i));
    }
    return accum;
};

py_builtins.sorted = function(iterable) {
    var l = list(iterable);
    l.PY$sort();
    return l;
};

if (typeof console !== 'undefined' && console.log !== undefined) {
    if (console.log.apply !== undefined) {
        py_builtins.print = function()  {
            console.log.apply(console, arguments);
        };
    } else {
        py_builtins.print = function()  {
            var args = js(str(" ").PY$join(tuple(Array.prototype.slice.call(arguments))));
            console.log(args);
        };
    }
} else if (typeof WScript !== 'undefined') {
    py_builtins.print = function() {
        var args = js(str(" ").PY$join(tuple(Array.prototype.slice.call(arguments))));
        WScript.Echo(args);
    };
} else if (typeof window === 'undefined' || window.print !== print) {
    py_builtins.print = function() {
        if (arguments.length <= 1) {
            if (arguments[0] !== undefined) {
                print($PY.str(arguments[0]));
            } else {
                print("");
            }
        } else {
            print.apply(null, arguments);
        }
    };
} else {
    py_builtins.print = function() {
        var args = tuple(Array.prototype.slice.call(arguments));
        alert(js($PY.str(" ").PY$join(py_builtins.map(py_builtins.repr, args))));
    };
}
<commit_msg> * Use _js_() in py_builtins.reduce with 2nd arg<commit_after>/**
  Copyright 2010-2011 Mateusz Paprocki <mattpap@gmail.com>
  Copyright 2011 Christian Iversen <ci@sikkerhed.org>

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

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

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

py_builtins.hasattr = function(obj, name) {
    name = js(name);
    return obj["PY$" + name] === undefined ? False : True;
};

py_builtins.getattr = function(obj, name, value) {
    name = js(name);
    var val = obj["PY$" + name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
        }
    }
};

py_builtins.setattr = function(obj, name, value) {
    name = js(name);
    obj["PY$" + name] = value;
};

py_builtins.js_getattr = function(obj, name, value) {
    var val = obj[name];

    if (val !== undefined) {
        return val;
    } else {
        if (value !== undefined) {
            return value;
        } else {
            throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
        }
    }
};

py_builtins.js_setattr = function(obj, name, value) {
    obj[name] = value;
};

py_builtins.delattr = function(obj, name) {
    name = js(name);
    if (obj["PY$" + name] !== undefined) {
        delete obj["PY$" + name];
    } else {
        throw py_builtins.AttributeError("Object " + js(str(obj)) + " does not have attribute " + name);
    }
};

py_builtins.hash = function(obj) {
    if (obj.PY$__hash__ !== undefined) {
        return obj.PY$__hash__();
    } else if (typeof(obj) === 'number') {
        return obj === -1 ? -2 : obj;
    } else {
        throw py_builtins.AttributeError('__hash__');
    }
};

py_builtins.len = function(obj) {
    if (obj.PY$__len__ !== undefined) {
        return obj.PY$__len__();
    } else {
        throw py_builtins.AttributeError('__len__');
    }
};

py_builtins.dir = function(obj) {
    var res = list();
    for (var i in obj) {
        if (i.indexOf('PY$') !== -1) {
            res.PY$append($PY.str(i.substr(3)));
        }
    }
    res.PY$sort();
    return res;
};

py_builtins.cmp = function(x, y) {
  return x.PY$__cmp__(y);
};

py_builtins.repr = function(obj) {
    if (obj == undefined) {
        return "None";
    } else if (obj.PY$__repr__ !== undefined) {
        return obj.PY$__repr__(obj);
    } else if (obj.PY$__str__ !== undefined) {
        return obj.PY$__str__(obj);
    } else if (obj.toString !== undefined) {
        return str(obj.toString());
    } else {
        throw py_builtins.AttributeError('__repr__, __str__ or toString not found on ' + typeof(obj));
    }
};

py_builtins.range = function(start, end, step) {
    start = js(start);

    if (end === undefined) {
        end = start;
        start = 0;
    } else {
        end = js(end);
    }

    if (step === undefined) {
        step = 1;
    } else {
        step = js(step);
    }

    var seq = [];

    for (var i = start; i < end; i += step) {
        seq.push(i);
    }

    if (py_builtins.PY$__python3__)
        return iter(seq);
    else
        return list(seq);
};

py_builtins.xrange = function(start, end, step) {
    return iter(py_builtins.range(start, end, step));
};

py_builtins.map = function() {
    if (arguments.length < 2) {
        throw py_builtins.TypeError("py_builtins.map() requires at least two args");
    }

    if (arguments.length > 2) {
        throw py_builtins.NotImplementedError("only one sequence allowed in py_builtins.map()");
    }

    var func = arguments[0];
    var items = list();

    iterate(arguments[1], function(item) {
        items.PY$append(func(item));
    });

    if (py_builtins.PY$__python3__)
        return iter(items);
    else
        return items;
};

py_builtins.enumerate = function(obj) {
    if (arguments.length != 1) {
        throw py_builtins.NotImplementedError("enumerate() only supports 1 argument");
    }
    var items = list();
    var count = 0;
    iterate(obj, function(elm) {
                items.PY$append(tuple([count++, elm]));
            });
    return items;
};

py_builtins.zip = function() {
    if (!arguments.length) {
        return list();
    }

    var iters = list();
    var i;

    for (i = 0; i < arguments.length; i++) {
        iters.PY$append(iter(arguments[i]));
    }

    var items = list();

    while (true) {
        var item = list();

        for (i = 0; i < arguments.length; i++) {
            try {
                var value = iters.PY$__getitem__(i).PY$next();
            } catch (exc) {
                if (exc === $PY.StopIter || $PY.isinstance(exc, py_builtins.StopIteration)) {
                    return items;
                } else {
                    throw exc;
                }
            }

            item.PY$append(value);
        }

        items.PY$append(tuple(item));
    }
    return None;
};

py_builtins.isinstance = function(obj, cls) {
    if (cls.PY$__class__ === tuple) {
        var length = cls.PY$__len__();

        if (length.PY$__eq__($c0) == True) {
            return False;
        }

        for (var i = 0; i < length; i++) {
            var _cls = cls.PY$__getitem__(i);

            if ($PY.isinstance(obj, _cls)) {
                return True;
            }
        }

        return False;
    } else {
        var c = obj.PY$__class__;
        while (c) {
            if (c === cls)
                return True;
            c = c.PY$__super__;
        }
        return False;
    }
};

py_builtins.__not__ = function(obj) {
   if (obj.PY$__nonzero__ !== undefined) {
       return js(obj.PY$__nonzero__()) ? False : True;
   } else if (obj.PY$__len__ !== undefined) {
       return js(obj.PY$__len__()) === 0 ? True : False;
   } else {
       return js(obj) ? False : True;
   }
};

py_builtins.__is__ = function(a, b) {
    return a === b ? True : False;
};

py_builtins.max = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == True)
        throw py_builtins.ValueError("max() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__gt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.min = function(list) {
    if (py_builtins.len(list).PY$__eq__($c0) == True)
        throw py_builtins.ValueError("min() arg is an empty sequence");
    else {
        var result = null;

        iterate(list, function(item) {
                if ((result === null) || js(item.PY$__lt__(result)))
                    result = item;
        });

        return result;
    }
};

py_builtins.sum = function(list) {
    var result = 0;

    iterate(list, function(item) {
        result += js(item);
    });

    return result;
};

py_builtins.filter = function(f, l) {
   var res = list();
   iterate(l, function(item) {
     if (f(item) == True) {
       res.PY$append(item);
     }
   });
   return res;
};

py_builtins.reduce = function(func, seq) {
    var initial;
    if (arguments.length == 3) {
        initial = arguments[2];
    } else {
        initial = null;
    }
    if (py_builtins.len(seq)._js_() < 2) {
        return initial;
    }
    var accum, start;
    if (arguments.length == 3) {
        accum = initial;
        start = 0;
    } else {
        accum = func(seq.PY$__getitem__(0), seq.PY$__getitem__(1));
        start = 2;
    }
    for (var i = start; i < py_builtins.len(seq)._js_(); i++) {
        accum = func(accum, seq.PY$__getitem__(i));
    }
    return accum;
};

py_builtins.sorted = function(iterable) {
    var l = list(iterable);
    l.PY$sort();
    return l;
};

if (typeof console !== 'undefined' && console.log !== undefined) {
    if (console.log.apply !== undefined) {
        py_builtins.print = function()  {
            console.log.apply(console, arguments);
        };
    } else {
        py_builtins.print = function()  {
            var args = js(str(" ").PY$join(tuple(Array.prototype.slice.call(arguments))));
            console.log(args);
        };
    }
} else if (typeof WScript !== 'undefined') {
    py_builtins.print = function() {
        var args = js(str(" ").PY$join(tuple(Array.prototype.slice.call(arguments))));
        WScript.Echo(args);
    };
} else if (typeof window === 'undefined' || window.print !== print) {
    py_builtins.print = function() {
        if (arguments.length <= 1) {
            if (arguments[0] !== undefined) {
                print($PY.str(arguments[0]));
            } else {
                print("");
            }
        } else {
            print.apply(null, arguments);
        }
    };
} else {
    py_builtins.print = function() {
        var args = tuple(Array.prototype.slice.call(arguments));
        alert(js($PY.str(" ").PY$join(py_builtins.map(py_builtins.repr, args))));
    };
}
<|endoftext|>


<commit_before>!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.apiOperations=e():t.apiOperations=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.oe=function(t){throw t},e.p="",e(e.s=2)}([function(t,e,n){"use strict";function r(t,e,n){return fetch(t,e).then(function(t){return(0,v.checkStatus)(t,n)})}function o(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=arguments[2];return r(t,e,n).then(v.parseResponse)}function u(t,e,n,r){var u={headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)};return o(t,y(u,n),r)}function i(t,e,n){return o(t,y({method:"get"},e),n)}function s(t,e,n,r){var o=function(t){return/\?/.test(t)};return i(""+t+(o(t)?"&":"?")+(0,h.stringify)(e),n,r)}function c(t,e,n,r){return u(t,e,y({method:"post"},n),r)}function a(t,e,n,r){return u(t,e,y({method:"put"},n),r)}function p(t,e,n,r){return u(t,e,y({method:"patch"},n),r)}function f(t,e,n){return o(t,y({method:"delete"},e),n)}function d(t,e){if(/^https?:\/\//.test(e))throw new Error('Endpoint seems invalid: "'+e+'"');return t.replace(/(\/$)/,"")+"/"+e.toString().replace(/(^\/)/,"")}function l(t,e,n){return{get:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2];return i(d(t,r),y(e,o),y(n,u))},getQuery:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],i=arguments[3];return s(d(t,r),o,y(e,u),y(n,i))},postJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],i=arguments[3];return c(d(t,r),o,y(e,u),y(n,i))},putJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],i=arguments[3];return a(d(t,r),o,y(e,u),y(n,i))},patchJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],i=arguments[3];return p(d(t,r),o,y(e,u),y(n,i))},"delete":function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2];return f(d(t,r),y(e,o),y(n,u))}}}Object.defineProperty(e,"__esModule",{value:!0}),e.patchJson=e.putJson=e.postJson=e.getQuery=e.get=void 0,e.delete_=f,e.createApiSource=l;var v=n(1),h=n(5),y=function(t,e){return Object.assign({},t,e)};e.get=i,e.getQuery=s,e.postJson=c,e.putJson=a,e.patchJson=p},function(t,e){"use strict";function n(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=u(e.statusValidator),i=u(e.errorParser),s=n?n(t.status):t.status>=200&&t.status<300;return s?t:r(t).then(function(e){throw o(e,t,i)})}function r(t){return"application/json"===t.headers.get("Content-Type")?t.json():t.text()}function o(t,e,n){var r=new Error(t.message||e.statusText);return r.name=t.error||e.status,r.response=e,r.body=t,n?n(t,e):r}function u(t){var e=function(t){return"[object Function]"==={}.toString.call(t)};return void 0===t&&null===t||!e(t)?!1:t}Object.defineProperty(e,"__esModule",{value:!0}),e.checkStatus=n,e.parseResponse=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createApiSource=e.delete_=e.patchJson=e.putJson=e.postJson=e.getQuery=e.get=void 0;var r=n(0);e.get=r.get,e.getQuery=r.getQuery,e.postJson=r.postJson,e.putJson=r.putJson,e.patchJson=r.patchJson,e.delete_=r.delete_,e.createApiSource=r.createApiSource},function(t,e){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}t.exports=function(t,e,o,u){e=e||"&",o=o||"=";var i={};if("string"!=typeof t||0===t.length)return i;var s=/\+/g;t=t.split(e);var c=1e3;u&&"number"==typeof u.maxKeys&&(c=u.maxKeys);var a=t.length;c>0&&a>c&&(a=c);for(var p=0;a>p;++p){var f,d,l,v,h=t[p].replace(s,"%20"),y=h.indexOf(o);y>=0?(f=h.substr(0,y),d=h.substr(y+1)):(f=h,d=""),l=decodeURIComponent(f),v=decodeURIComponent(d),n(i,l)?r(i[l])?i[l].push(v):i[l]=[i[l],v]:i[l]=v}return i};var r=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},function(t,e){"use strict";function n(t,e){if(t.map)return t.map(e);for(var n=[],r=0;r<t.length;r++)n.push(e(t[r],r));return n}var r=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};t.exports=function(t,e,i,s){return e=e||"&",i=i||"=",null===t&&(t=void 0),"object"==typeof t?n(u(t),function(u){var s=encodeURIComponent(r(u))+i;return o(t[u])?n(t[u],function(t){return s+encodeURIComponent(r(t))}).join(e):s+encodeURIComponent(r(t[u]))}).join(e):s?encodeURIComponent(r(s))+i+encodeURIComponent(r(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},u=Object.keys||function(t){var e=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.push(n);return e}},function(t,e,n){"use strict";e.decode=e.parse=n(3),e.encode=e.stringify=n(4)}])});<commit_msg>1.1.1<commit_after>!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.apiOperations=e():t.apiOperations=e()}(this,function(){return function(t){function e(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return t[r].call(o.exports,o,o.exports,e),o.loaded=!0,o.exports}var n={};return e.m=t,e.c=n,e.oe=function(t){throw t},e.p="",e(e.s=2)}([function(t,e,n){"use strict";function r(t,e,n){return fetch(t,e).then(function(t){return(0,d.checkStatus)(t,n)})}function o(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=arguments[2];return r(t,e,n).then(d.parseResponse)}function u(t,e,n,r){var u={headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify(e)};return o(t,v(u,n),r)}function s(t,e,n){return o(t,v({method:"get"},e),n)}function a(t,e,n,r){var o=function(t){return/\?/.test(t)};return s(""+t+(o(t)?"&":"?")+(0,l.stringify)(e),n,r)}function i(t,e,n,r){return u(t,e,v({method:"post"},n),r)}function c(t,e,n,r){return u(t,e,v({method:"put"},n),r)}function p(t,e,n,r){return u(t,e,v({method:"patch"},n),r)}function g(t,e,n){return o(t,v({method:"delete"},e),n)}function f(t,e){if(/^https?:\/\//.test(e))throw new Error('Endpoint seems invalid: "'+e+'"');return t.replace(/(\/$)/,"")+"/"+e.toString().replace(/(^\/)/,"")}function m(t,e,n){return{get:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2];return s(f(t,r),v(e,o),v(n,u))},getQuery:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],s=arguments[3];return a(f(t,r),o,v(e,u),v(n,s))},postJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],s=arguments[3];return i(f(t,r),o,v(e,u),v(n,s))},putJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],s=arguments[3];return c(f(t,r),o,v(e,u),v(n,s))},patchJson:function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2],s=arguments[3];return p(f(t,r),o,v(e,u),v(n,s))},"delete":function(){var r=arguments.length<=0||void 0===arguments[0]?"":arguments[0],o=arguments[1],u=arguments[2];return g(f(t,r),v(e,o),v(n,u))}}}Object.defineProperty(e,"__esModule",{value:!0}),e.patchJson=e.putJson=e.postJson=e.getQuery=e.get=void 0,e.delete_=g,e.createApiSource=m;var d=n(1),l=n(5),v=function(t,e){return Object.assign({},t,e)};e.get=s,e.getQuery=a,e.postJson=i,e.putJson=c,e.patchJson=p},function(t,e){"use strict";function n(t){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],n=u(e.statusValidator),s=u(e.errorParser),a=n?n(t.status):t.status>=200&&t.status<300;return a?t:r(t).then(function(e){throw o(e,t,s)})}function r(t){return"application/json"===t.headers.get("Content-Type")?t.json():t.text()}function o(t,e,n){var r=new Error(t.message||e.statusText);return r.name=t.error||e.status,r.response=e,r.body=t,n?n(t,e):r}function u(t){var e=function(t){return"[object Function]"==={}.toString.call(t)};return void 0===t&&null===t||!e(t)?!1:t}Object.defineProperty(e,"__esModule",{value:!0}),e.checkStatus=n,e.parseResponse=r},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.createApiSource=e.delete_=e.patchJson=e.putJson=e.postJson=e.getQuery=e.get=void 0;var r=n(0);e.get=r.get,e.getQuery=r.getQuery,e.postJson=r.postJson,e.putJson=r.putJson,e.patchJson=r.patchJson,e.delete_=r.delete_,e.createApiSource=r.createApiSource},function(t,e){"use strict";function n(t,e){return Object.prototype.hasOwnProperty.call(t,e)}t.exports=function(t,e,o,u){e=e||"&",o=o||"=";var s={};if("string"!=typeof t||0===t.length)return s;var a=/\+/g;t=t.split(e);var i=1e3;u&&"number"==typeof u.maxKeys&&(i=u.maxKeys);var c=t.length;i>0&&c>i&&(c=i);for(var p=0;c>p;++p){var g,f,m,d,l=t[p].replace(a,"%20"),v=l.indexOf(o);v>=0?(g=l.substr(0,v),f=l.substr(v+1)):(g=l,f=""),m=decodeURIComponent(g),d=decodeURIComponent(f),n(s,m)?r(s[m])?s[m].push(d):s[m]=[s[m],d]:s[m]=d}return s};var r=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)}},function(t,e){"use strict";function n(t,e){if(t.map)return t.map(e);for(var n=[],r=0;r<t.length;r++)n.push(e(t[r],r));return n}var r=function(t){switch(typeof t){case"string":return t;case"boolean":return t?"true":"false";case"number":return isFinite(t)?t:"";default:return""}};t.exports=function(t,e,s,a){return e=e||"&",s=s||"=",null===t&&(t=void 0),"object"==typeof t?n(u(t),function(u){var a=encodeURIComponent(r(u))+s;return o(t[u])?n(t[u],function(t){return a+encodeURIComponent(r(t))}).join(e):a+encodeURIComponent(r(t[u]))}).join(e):a?encodeURIComponent(r(a))+s+encodeURIComponent(r(t)):""};var o=Array.isArray||function(t){return"[object Array]"===Object.prototype.toString.call(t)},u=Object.keys||function(t){var e=[];for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&e.push(n);return e}},function(t,e,n){"use strict";e.decode=e.parse=n(3),e.encode=e.stringify=n(4)}])});<|endoftext|>


<commit_before>(function ($) {

    var contentTop = [],
    content = [],
    lastScrollTop = 0,
    scrollDir = '',
    itemClass = '',
    itemHover = '',
    menuSize = null,
    stickyHeight = 0,
    stickyMarginB = 0,
    currentMarginT = 0,
    $element = $(),
    currentMarginT = 0,
    topMargin = 0,
    top,
    vartop = 0,
    varscroll = 0,
    contentView = $(),
    testView = $();

    function getTopMargin(options) {
        if (options.topMargin == 'auto') {
            return parseInt($('.stuckMenu').css('margin-top'));
        } else {
            if (isNaN(options.topMargin) && options.topMargin.search("px") > 0) {
                return parseInt(options.topMargin.replace("px", ""));
            } else if (!isNaN(parseInt(options.topMargin))) {
                return parseInt(options.topMargin);
            } else {
                console.log("incorrect argument, ignored.");
                return 0;
            }
        }
    }

    $.fn.stickUp = function (options) {
        $element = $(this);
        // adding a class to users div
        $element.addClass('stuckMenu');
        //getting options
        var objn = 0;
        if (options != null) {
            var parts = options.parts;
            for (var key in  parts) {
                if (parts.hasOwnProperty(key)) {
                    content[objn] = parts[objn];
                    objn++;
                }
            }

            itemClass = options.itemClass;
            itemHover = options.itemHover;

            topMargin = (options.topMargin != null) ? getTopMargin(options) : 0;

            menuSize = $('.' + itemClass).size();
        }

        stickyHeight = parseInt($element.height());
        stickyMarginB = parseInt($element.css('margin-bottom'));
        currentMarginT = parseInt($element.next().closest('div').css('margin-top'));
        top = parseInt($element.offset().top);
    };

    function baseScrollHandlerFn(event) {
        var st = $(event.target).scrollTop();
        scrollDir = (st > lastScrollTop) ? 'down' : 'up';
        lastScrollTop = st;
    }

    function stickUpScrollHandlerFn() {
        var scroll = parseInt($(document).scrollTop());
        if (menuSize != null && content.length > 0) {
            for (var i = 0; i < menuSize; i++) {
                contentTop[i] = $('#' + content[i] + '').offset().top;
                function bottomView(i) {
                    var contentView = $('#' + content[i] + '').height() * .4;
                    if (scroll > (contentTop[i] - contentView)) {
                        setItemHover(i);
                    } else if (scroll < 50) {
                        setItemHover(0);
                    }
                }

                if (scrollDir == 'down' && scroll > contentTop[i] - 50 && scroll < contentTop[i] + 50) {
                    setItemHover(i);
                }

                if (scrollDir == 'up') {
                    bottomView(i, contentTop[i]);
                }
            }
        }

        if (top < scroll + topMargin && !$element.hasClass('isStuck')) {

            $element
                .addClass('isStuck')
                .next()
                .closest('div')
                .css({
                    'margin-top': stickyHeight + stickyMarginB + currentMarginT + 'px'
                }, 10);

            $element.css("position", "fixed");

            $element.css({
                top: '0px'
            }, 10, function () {

            });
        }

        if (scroll + topMargin < top && $element.hasClass('isStuck')) {

            $element
                .removeClass('isStuck')
                .next()
                .closest('div')
                .css({
                    'margin-top': currentMarginT + 'px'
                }, 10);

            $element.css("position", "relative");
        }
    }

    function setItemHover(position) {
        $('.' + itemClass).removeClass(itemHover);
        $('.' + itemClass + ':eq(' + position + ')').addClass(itemHover);
    }

    $(window).on('scroll', baseScrollHandlerFn);
    $(document).on('scroll', stickUpScrollHandlerFn);

}(jQuery));<commit_msg>reduce layout thrashing<commit_after>(function ($,window,document) {

    var contentTop = [],
    content = [],
    lastScrollTop = 0,
    scrollDir = '',
    itemClass = '',
    itemHover = '',
    menuSize = null,
    active = false,
    stickyHeight = 0,
    currentMarginT = 0,
    $element = $(),
    currentMarginT = 0,
    topMargin = 0,
    top,

    getTopMargin = function(options) {
        if (options.topMargin == 'auto') {
            return parseInt($('.stuckMenu').css('margin-top'));
        } else {
            if (isNaN(options.topMargin) && options.topMargin.search("px") > 0) {
                return parseInt(options.topMargin.replace("px", ""));
            } else if (!isNaN(parseInt(options.topMargin))) {
                return parseInt(options.topMargin);
            } else {
                console.log("incorrect argument, ignored.");
                return 0;
            }
        }
    },

    baseScrollHandlerFn = function(event) {
        var st = $(event.target).scrollTop();
        scrollDir = (st > lastScrollTop) ? 'down' : 'up';
        lastScrollTop = st;
        if(!active){
            stickyHeight = parseInt($element.outerHeight(true));
            top = parseInt($element.offset().top);
            currentMarginT = parseInt($element.next().closest('div').css('margin-top'));
        }
    },

    stickUpScrollHandlerFn = function() {
        var scroll = parseInt($(document).scrollTop());
        if (menuSize != null && content.length > 0) {
            for (var i = 0; i < menuSize; i++) {
                contentTop[i] = $('#' + content[i] + '').offset().top;
                function bottomView(i) {
                    var contentView = $('#' + content[i] + '').height() * .4;
                    if (scroll > (contentTop[i] - contentView)) {
                        setItemHover(i);
                    } else if (scroll < 50) {
                        setItemHover(0);
                    }
                }

                if (scrollDir == 'down' && scroll > contentTop[i] - 50 && scroll < contentTop[i] + 50) {
                    setItemHover(i);
                }

                if (scrollDir == 'up') {
                    bottomView(i, contentTop[i]);
                }
            }
        }

        //STICK IT
        if (top < scroll + topMargin && !$element.hasClass('isStuck')) {
            active = true;
            window.requestAnimationFrame(function() {
                $element
                    .addClass('isStuck')
                    .next()
                    .closest('div')
                    .css({
                        'margin-top': stickyHeight + currentMarginT + 'px'
                    });

                $element.css("position", "fixed");

                $element.css({
                    top: '0px'
                });
            });
        }

        //UNSTICK
        if (scroll + topMargin < top && $element.hasClass('isStuck')) {
            window.requestAnimationFrame(function() {
                $element
                    .removeClass('isStuck')
                    .next()
                    .closest('div')
                    .css({
                        'margin-top': currentMarginT + 'px'
                    });

                $element.css("position", "relative");
            });
            active = false;
        }
    },

    setItemHover = function(position) {
        $('.' + itemClass).removeClass(itemHover);
        $('.' + itemClass + ':eq(' + position + ')').addClass(itemHover);
    };

    $.fn.stickUp = function (options) {
        $element = $(this);
        // adding a class to users div
        $element.addClass('stuckMenu');
        //getting options
        var objn = 0;
        if (options != null) {
            var parts = options.parts;
            for (var key in  parts) {
                if (parts.hasOwnProperty(key)) {
                    content[objn] = parts[objn];
                    objn++;
                }
            }

            itemClass = options.itemClass;
            itemHover = options.itemHover;

            topMargin = (options.topMargin != null) ? getTopMargin(options) : 0;

            menuSize = $('.' + itemClass).size();
        }

        $(window).on('scroll.stickUp', baseScrollHandlerFn);
        $(document).on('scroll.stickUp', stickUpScrollHandlerFn);
    };
}(jQuery,window,document));<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 Christoph Jerolimov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var cons = require('consolidate');
var path = require('path');

var Comprise = function(options) {
	this.defaultEngine = options.engine;
	this.defaultExtension = options.extension || options.engine;
	this.defaultLayout = options.layout;

	this.templateDir = options.templateDir || '';
	this.layoutDir = options.layoutDir || options.templateDir + '/_layout';
	this.partialDir = options.partialDir || options.templateDir + '/_partials';

	this.layouts = [];
	this.partialIndex = 0;
	this.partials = {};
};

Comprise.prototype.engine = function(template) {
	var ext = path.extname(template);
	if (ext.length > 1) {
		return ext.substring(1);
	} else {
		return this.defaultEngine;
	}
};

Comprise.prototype.filename = function(template) {
	var ext = path.extname(template);
	if (ext.length > 1) {
		return this.templateDir + '/' + template;
	} else {
		return this.templateDir + '/' + template + '.' + this.defaultExtension;
	}
};

Comprise.prototype.render = function(template, variables, callback) {
	if (this.defaultLayout) {
		this.layouts.push(this.defaultLayout);
	}

	this.renderImpl(template, variables, function(err, response) {
		if (callback) {
			var _callback = callback;
			callback = null;

			if (err) {
				console.error('err', err);
			}
			try {
				_callback(err, response);
			} catch (e) {
				console.error('Error in callback', e);
			}
		}
	});
};

Comprise.prototype.renderImpl = function(template, variables, callback) {
	var self = this;

	this.finish = function() {
		if (!self.response) {
			return;
		}

//		console.log('Pre replacement: ', self.response);

		for (var partialKey in self.partials) {
			if (self.partials[partialKey]) {
//				console.log('Search and replace partial', partialKey, self.partials[partialKey]);
				self.response = self.response.replace(partialKey, self.partials[partialKey]);
				delete self.partials[partialKey];
			}
		}

		if (!Object.keys(self.partials).length) {
			callback(null, self.response);
		}

//		console.log('Post replacement', self.response);
	};

	variables.layout = function(layout) {
//		console.log('add layout', layout);
		self.layouts.push(layout);
		return ''; // Force no output
	};

	variables.nolayout = function() {
		self.layouts = [];
	};

	variables.content = function() {
		return self.content;
	};

	variables.partial = function(partialTemplate, partialVariables) {
//		console.log('include partial', partialTemplate);

		var partialKey = '## ComprisePartial ' + self.partialIndex++ + ' ##';
		partialVariables = partialVariables || variables;
		self.partials[partialKey] = null;

		cons[self.engine(partialTemplate)](self.filename(partialTemplate), partialVariables, function(err, response) {
//			console.log('partial result for ' + partialKey + ':', err, response);
			if (err) {
				callback(err);
				delete self.partials[partialKey];
			} else {
				self.partials[partialKey] = response;
				self.finish();
			}
		});

		return partialKey;
	};

	// TODO: Could we simplify this?
	if (this.engine(template) == 'handlebars') {
		var helpers = variables.helpers || {};
		helpers.layout = variables.layout;
		helpers.nolayout = variables.nolayout;
		helpers.content = variables.content;
		helpers.partial = variables.partial;
		variables.helpers = helpers;
	}

	cons[this.engine(template)](this.filename(template), variables, function(err, response) {
//		console.log('finish rendering', template, response)
		if (err) {
			callback(err);
		} else if (self.layouts.length) {
			var layout = self.layouts.shift();
//			console.log('run next layout', layout);
			self.content = response;
			self.renderImpl(layout, variables, callback);
		} else {
			self.response = response;
			self.finish();
		}
	});
};

exports.Comprise = Comprise;
<commit_msg>Fix nolayout output: Should be an empty string.<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2013 Christoph Jerolimov
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var cons = require('consolidate');
var path = require('path');

var Comprise = function(options) {
	this.defaultEngine = options.engine;
	this.defaultExtension = options.extension || options.engine;
	this.defaultLayout = options.layout;

	this.templateDir = options.templateDir || '';
	this.layoutDir = options.layoutDir || options.templateDir + '/_layout';
	this.partialDir = options.partialDir || options.templateDir + '/_partials';

	this.layouts = [];
	this.partialIndex = 0;
	this.partials = {};
};

Comprise.prototype.engine = function(template) {
	var ext = path.extname(template);
	if (ext.length > 1) {
		return ext.substring(1);
	} else {
		return this.defaultEngine;
	}
};

Comprise.prototype.filename = function(template) {
	var ext = path.extname(template);
	if (ext.length > 1) {
		return this.templateDir + '/' + template;
	} else {
		return this.templateDir + '/' + template + '.' + this.defaultExtension;
	}
};

Comprise.prototype.render = function(template, variables, callback) {
	if (this.defaultLayout) {
		this.layouts.push(this.defaultLayout);
	}

	this.renderImpl(template, variables, function(err, response) {
		if (callback) {
			var _callback = callback;
			callback = null;

			if (err) {
				console.error('err', err);
			}
			try {
				_callback(err, response);
			} catch (e) {
				console.error('Error in callback', e);
			}
		}
	});
};

Comprise.prototype.renderImpl = function(template, variables, callback) {
	var self = this;

	this.finish = function() {
		if (!self.response) {
			return;
		}

//		console.log('Pre replacement: ', self.response);

		for (var partialKey in self.partials) {
			if (self.partials[partialKey]) {
//				console.log('Search and replace partial', partialKey, self.partials[partialKey]);
				self.response = self.response.replace(partialKey, self.partials[partialKey]);
				delete self.partials[partialKey];
			}
		}

		if (!Object.keys(self.partials).length) {
			callback(null, self.response);
		}

//		console.log('Post replacement', self.response);
	};

	variables.layout = function(layout) {
//		console.log('add layout', layout);
		self.layouts.push(layout);
		return ''; // Force no output
	};

	variables.nolayout = function() {
		self.layouts = [];
		return ''; // Force no output
	};

	variables.content = function() {
		return self.content;
	};

	variables.partial = function(partialTemplate, partialVariables) {
//		console.log('include partial', partialTemplate);

		var partialKey = '## ComprisePartial ' + self.partialIndex++ + ' ##';
		partialVariables = partialVariables || variables;
		self.partials[partialKey] = null;

		cons[self.engine(partialTemplate)](self.filename(partialTemplate), partialVariables, function(err, response) {
//			console.log('partial result for ' + partialKey + ':', err, response);
			if (err) {
				callback(err);
				delete self.partials[partialKey];
			} else {
				self.partials[partialKey] = response;
				self.finish();
			}
		});

		return partialKey;
	};

	// TODO: Could we simplify this?
	if (this.engine(template) == 'handlebars') {
		var helpers = variables.helpers || {};
		helpers.layout = variables.layout;
		helpers.nolayout = variables.nolayout;
		helpers.content = variables.content;
		helpers.partial = variables.partial;
		variables.helpers = helpers;
	}

	cons[this.engine(template)](this.filename(template), variables, function(err, response) {
//		console.log('finish rendering', template, response)
		if (err) {
			callback(err);
		} else if (self.layouts.length) {
			var layout = self.layouts.shift();
//			console.log('run next layout', layout);
			self.content = response;
			self.renderImpl(layout, variables, callback);
		} else {
			self.response = response;
			self.finish();
		}
	});
};

exports.Comprise = Comprise;
<|endoftext|>