<commit_before>
(function() {
    'use strict';

    /**
     * Controller for the imls app home view
     */
    /* ngInject */
    function HomeController($cookies, $log, $q, $scope, $geolocation, $state, Config, Geocoder, Museum) {
        var ctl = this;

        var map = null;
        var searchMarker = null;

        var SEARCH_DIST_METERS = 1609.34;  // 1 mile

        initialize();

        function initialize() {
            ctl.list = [];
            ctl.safeList = [];
            ctl.states = {
                DISCOVER: 0,
                LIST: 1,
                ERROR: -1
            };
            ctl.pageState = ctl.states.DISCOVER;
            ctl.rowsPerPage = 10;

            ctl.onLocationClicked = onLocationClicked;
            ctl.onSearchClicked = onSearchClicked;
            ctl.onTypeaheadSelected = onTypeaheadSelected;
            ctl.search = search;
            $scope.$on('imls:vis:ready', function (e, vis, newMap) {
                map = newMap;

                var lastSearched = $cookies.getObject(Config.cookies.LAST_SEARCHED);
                if (lastSearched) {
                    ctl.pageState = ctl.states.LIST;
                    ctl.searchText = lastSearched.text;
                    requestNearbyMuseums(lastSearched.position);
                }
            });
        }

        function onLocationClicked() {
            $geolocation.getCurrentPosition({
                enableHighAccuracy: true,
                maximumAge: 0
            }).then(function (position) {
                requestNearbyMuseums({
                    x: position.coords.longitude,
                    y: position.coords.latitude
                });
            })
            .catch(function (error) {
                $log.error(error);
                ctl.pageState = ctl.states.ERROR;
            });
        }

        function onSearchClicked() {
            search(ctl.searchText);
        }

        function search(text) {
            return $q.all([Geocoder.search(text), Museum.suggest(text)]).then(function (results) {
                $log.info(results);
                return _.flatten(results);
            }).catch(function (error) {
                ctl.pageState = ctl.states.ERROR;
                $log.error(error);
            });
        }

        function onTypeaheadSelected(item) {
            if (item.ismuseum) {
                requestNearbyMuseums({
                    x: item.longitude,
                    y: item.latitude
                });
            } else if (item.feature) {
                // TODO: Additional handling to pass extent to requestNearbyMuseums?
                requestNearbyMuseums(item.feature.geometry);
            } else {
                $log.error('No valid handlers for typeahead item:', item);
                ctl.pageState = ctl.states.ERROR;
            }
        }

        // position is an object with x and y keys
        function requestNearbyMuseums(position) {
            map.setView([position.y, position.x], Config.detailZoom);
            addSearchLocationMarker(position);

            Museum.list(position, SEARCH_DIST_METERS).then(function (rows) {
                if (rows.length) {
                    ctl.list = rows;
                    ctl.pageState = ctl.states.LIST;
                    setLastPositionCookie(position);
                } else {
                    ctl.pageState = ctl.states.ERROR;
                }
            }).catch(function (error) {
                $log.error(error);
                ctl.pageState = ctl.states.ERROR;
            });
        }

        function setLastPositionCookie(position) {
            $cookies.putObject(Config.cookies.LAST_SEARCHED, {
                text: ctl.searchText || '',
                position: position
            }, {
                expires: new Date(new Date().getTime() + 3600 * 1000)
            });
        }

        function addSearchLocationMarker(position) {
            clearSearchLocationMarker();
            searchMarker = L.marker([position.y, position.x], {
                clickable: false,
                keyboard: false
            });
            searchMarker.addTo(map);
        }

        function clearSearchLocationMarker() {
            if (searchMarker) {
                map.removeLayer(searchMarker);
                searchMarker = null;
            }
        }
    }

    angular.module('imls.views.home')
    .controller('HomeController', HomeController);
})();
<commit_msg>Tweak cookie expiry to 12hrs<commit_after>
(function() {
    'use strict';

    /**
     * Controller for the imls app home view
     */
    /* ngInject */
    function HomeController($cookies, $log, $q, $scope, $geolocation, $state, Config, Geocoder, Museum) {
        var ctl = this;

        var map = null;
        var searchMarker = null;

        var SEARCH_DIST_METERS = 1609.34;  // 1 mile

        initialize();

        function initialize() {
            ctl.list = [];
            ctl.safeList = [];
            ctl.states = {
                DISCOVER: 0,
                LIST: 1,
                ERROR: -1
            };
            ctl.pageState = ctl.states.DISCOVER;
            ctl.rowsPerPage = 10;

            ctl.onLocationClicked = onLocationClicked;
            ctl.onSearchClicked = onSearchClicked;
            ctl.onTypeaheadSelected = onTypeaheadSelected;
            ctl.search = search;
            $scope.$on('imls:vis:ready', function (e, vis, newMap) {
                map = newMap;

                var lastSearched = $cookies.getObject(Config.cookies.LAST_SEARCHED);
                if (lastSearched) {
                    ctl.pageState = ctl.states.LIST;
                    ctl.searchText = lastSearched.text;
                    requestNearbyMuseums(lastSearched.position);
                }
            });
        }

        function onLocationClicked() {
            $geolocation.getCurrentPosition({
                enableHighAccuracy: true,
                maximumAge: 0
            }).then(function (position) {
                requestNearbyMuseums({
                    x: position.coords.longitude,
                    y: position.coords.latitude
                });
            })
            .catch(function (error) {
                $log.error(error);
                ctl.pageState = ctl.states.ERROR;
            });
        }

        function onSearchClicked() {
            search(ctl.searchText);
        }

        function search(text) {
            return $q.all([Geocoder.search(text), Museum.suggest(text)]).then(function (results) {
                $log.info(results);
                return _.flatten(results);
            }).catch(function (error) {
                ctl.pageState = ctl.states.ERROR;
                $log.error(error);
            });
        }

        function onTypeaheadSelected(item) {
            if (item.ismuseum) {
                requestNearbyMuseums({
                    x: item.longitude,
                    y: item.latitude
                });
            } else if (item.feature) {
                // TODO: Additional handling to pass extent to requestNearbyMuseums?
                requestNearbyMuseums(item.feature.geometry);
            } else {
                $log.error('No valid handlers for typeahead item:', item);
                ctl.pageState = ctl.states.ERROR;
            }
        }

        // position is an object with x and y keys
        function requestNearbyMuseums(position) {
            map.setView([position.y, position.x], Config.detailZoom);
            addSearchLocationMarker(position);

            Museum.list(position, SEARCH_DIST_METERS).then(function (rows) {
                if (rows.length) {
                    ctl.list = rows;
                    ctl.pageState = ctl.states.LIST;
                    setLastPositionCookie(position);
                } else {
                    ctl.pageState = ctl.states.ERROR;
                }
            }).catch(function (error) {
                $log.error(error);
                ctl.pageState = ctl.states.ERROR;
            });
        }

        function setLastPositionCookie(position) {
            $cookies.putObject(Config.cookies.LAST_SEARCHED, {
                text: ctl.searchText || '',
                position: position
            }, {
                // Set expiry to 12hrs from set time
                expires: new Date(new Date().getTime() + 12 * 3600 * 1000)
            });
        }

        function addSearchLocationMarker(position) {
            clearSearchLocationMarker();
            searchMarker = L.marker([position.y, position.x], {
                clickable: false,
                keyboard: false
            });
            searchMarker.addTo(map);
        }

        function clearSearchLocationMarker() {
            if (searchMarker) {
                map.removeLayer(searchMarker);
                searchMarker = null;
            }
        }
    }

    angular.module('imls.views.home')
    .controller('HomeController', HomeController);
})();
<|endoftext|>


<commit_before>'use strict';

/**
 * @module core-controllers
 */

/**
 * Provides route actions to deal with errors.
 *
 * @class errorController
 */

var errors = process.require('app/server/httpErrors.js');
var defaultController = process.require('app/server/controllers/defaultController.js');

/**
 * Handles requests which does not correspond to anything.
 *
 * @method notFoundAction
 * @static
 */
module.exports.notFoundAction = function(request, response, next) {
  next(errors.PATH_NOT_FOUND);
};

/**
 * Handles all errors.
 *
 * @example
 *     {
 *       "code" : 1,
 *       "httpCode" : 500,
 *       "module" : "core"
 *     }
 *
 * @method errorAction
 * @static
 * @param {Object} error An error object with error code, HTTP code
 * and the module associated to the error
 */
module.exports.errorAction = function(error, request, response, next) {
  if (!error)
    error = errors.UNKNOWN_ERROR;

  if (!error.module)
    error.module = 'core';

  process.logger.error('Error', {
    code: error.code,
    module: error.module,
    method: request.method,
    path: request.url,
    headers: request.headers
  });

   // Send response with HTML content
  if (request.accepts('html') && (error.httpCode == '401' || error.httpCode == '403')) {
    response.status(error.httpCode);
    defaultController.defaultAction(request, response, next);
    return;
  }

  // Send response with JSON content or HTML but not 401 or 403 errorCode
  response.status(error.httpCode);
  response.send({error: {
    code: error.code,
    module: error.module
  }});
};

/**
 * Handles forgotten requests.
 *
 * Depending on request Accept HTTP header, either an HTML content,
 * a JSON content or a text content will be returned with a 404 code.
 *
 * @method notFoundPageAction
 * @static
 */
module.exports.notFoundPageAction = function(request, response) {
  process.logger.warn('404 Not Found', {
    method: request.method,
    path: request.url,
    headers: request.headers
  });

  response.status(404);

  // HTML content
  if (request.accepts('html')) {
    response.render('404', {
      url: request.url
    });
    return;
  }

  // JSON content
  if (request.accepts('json')) {
    response.send({
      error: 'Not found',
      url: request.url
    });
    return;
  }

  // Text content
  response.type('txt').send(request.url + ' not found');
};
<commit_msg>Correct server error on errorController.errorAction and offer the possibilty to add an error message<commit_after>'use strict';

/**
 * @module core-controllers
 */

/**
 * Provides route actions to deal with errors.
 *
 * @class errorController
 */

var errors = process.require('app/server/httpErrors.js');
var defaultController = process.require('app/server/controllers/defaultController.js');

/**
 * Handles requests which does not correspond to anything.
 *
 * @method notFoundAction
 * @static
 */
module.exports.notFoundAction = function(request, response, next) {
  next(errors.PATH_NOT_FOUND);
};

/**
 * Handles all errors.
 *
 * @example
 *     {
 *       "code" : 1,
 *       "httpCode" : 500,
 *       "module" : "core"
 *     }
 *
 * @method errorAction
 * @static
 * @param {Object} error An error object with error code, HTTP code
 * and the module associated to the error
 */
module.exports.errorAction = function(error, request, response, next) {
  if (!error || !error.code)
    error = errors.UNKNOWN_ERROR;

  if (!error.module)
    error.module = 'core';

  process.logger.error('Error', {
    code: error.code,
    module: error.module,
    method: request.method,
    path: request.url,
    headers: request.headers
  });

   // Send response with HTML content
  if (request.accepts('html') && (error.httpCode == '401' || error.httpCode == '403')) {
    response.status(error.httpCode);
    defaultController.defaultAction(request, response, next);
    return;
  }

  // Send response with JSON content or HTML but not 401 or 403 errorCode
  response.status(error.httpCode);
  response.send({
    error: {
      code: error.code,
      module: error.module,
      message: error.message
    }
  });
};

/**
 * Handles forgotten requests.
 *
 * Depending on request Accept HTTP header, either an HTML content,
 * a JSON content or a text content will be returned with a 404 code.
 *
 * @method notFoundPageAction
 * @static
 */
module.exports.notFoundPageAction = function(request, response) {
  process.logger.warn('404 Not Found', {
    method: request.method,
    path: request.url,
    headers: request.headers
  });

  response.status(404);

  // HTML content
  if (request.accepts('html')) {
    response.render('404', {
      url: request.url
    });
    return;
  }

  // JSON content
  if (request.accepts('json')) {
    response.send({
      error: 'Not found',
      url: request.url
    });
    return;
  }

  // Text content
  response.type('txt').send(request.url + ' not found');
};
<|endoftext|>


<commit_before>"use strict"
const   mongoose = require('mongoose'),
    Concept = require('../../models/Concept');

module.exports = () => {

  let data = {}

  Concept.find()
    .sort('label')
    .select('label _id')
    .exec((err, collection)=>{
       if (err) throw err

        let dupes = {}
        collection.forEach((entry) => {
          if (!dupes[entry.label.replace(/ /g, "")]) {
            dupes[.replace(/ /g, "")] = true
          } else {
            //remove the entry
            Concept.find({_id: entry._id})
            .remove()
          }
        })

    }) // end find
} //end exports<commit_msg>fix syntax error<commit_after>"use strict"
const   mongoose = require('mongoose'),
    Concept = require('../../models/Concept');

module.exports = () => {

  let data = {}

  Concept.find()
    .sort('label')
    .select('label _id')
    .exec((err, collection)=>{
       if (err) throw err

        let dupes = {}
        collection.forEach((entry) => {
          if (!dupes[entry.label.replace(/ /g, "")]) {
            dupes[entry.label.replace(/ /g, "")] = true
          } else {
            //remove the entry
            Concept.find({_id: entry._id})
            .remove()
          }
        })

    }) // end find
} //end exports<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2014 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var paypal = require('paypal-rest-sdk');
var url = require('url');
var config = require('../config');
var vat = require('./vat');

paypal.configure({
	'mode': config.paypal.mode, //sandbox or live
	'client_id': config.paypal.client_id,
	'client_secret': config.paypal.client_secret
});

function getBillingAgreement(billingUser, billingAddress, currency, firstCycleAmount, firstBillingCycle, amount, billingCycle, startDate){
	'use strict';

	console.log('firstCycleAmount', firstCycleAmount);
	console.log('amount', amount);
	console.log('startDate', startDate);

	let apiServerConfig = config.servers.find(server => server.service === 'api');
	let port = '';
	if(config.using_ssl && apiServerConfig.public_port !== 443 || !config.using_ssl && apiServerConfig.public_port !== 80){
		port = ':' + apiServerConfig.public_port;
	}

	let baseUrl = (config.using_ssl ? 'https://' : 'http://') + config.host + port;

	let taxAmount = vat.getByCountryCode(billingAddress.country_code) * amount;
	taxAmount = Math.round(taxAmount * 100) / 100;
	let afterTaxAmount = amount - taxAmount;
	afterTaxAmount = Math.round(afterTaxAmount * 100) / 100;

	let paymentDefs = [];
	paymentDefs.push({
		"amount": {
			"currency": currency,
			"value": afterTaxAmount
		},
		"cycles": "0",
		"frequency": "MONTH",
		"frequency_interval": billingCycle,
		"name": "Regular monthly price",
		"type": "REGULAR",
		"charge_models":[{
			"type": "TAX",
			"amount": {
				"value": taxAmount,
				"currency": currency
			}
		}]
	});

	if(firstCycleAmount){

;
		let taxFirstCycleAmount = vat.getByCountryCode(billingAddress.country_code) * firstCycleAmount;
		taxFirstCycleAmount = Math.round(taxFirstCycleAmount * 100) / 100;
		let afterTaxFirstCycleAmount = firstCycleAmount - taxFirstCycleAmount;
		afterTaxFirstCycleAmount = Math.round(afterTaxFirstCycleAmount * 100) / 100;

		paymentDefs.push({
			"amount": {
				"currency": currency,
				"value": afterTaxFirstCycleAmount
			},
			"cycles": "1",
			"frequency": "DAY",
			"frequency_interval": firstBillingCycle,
			"name": "First month pro-rata price",
			"type": "TRIAL",
			"charge_models":[{
				"type": "TAX",
				"amount": {
					"value": taxFirstCycleAmount,
					"currency": currency
				}
			}]
		});
	}

	let billingPlanAttributes = {
		"description": "3D Repo Licence",
		"merchant_preferences": {
			"auto_bill_amount": "yes",
			"cancel_url": `${baseUrl}/${billingUser}?page=billing`,
			"initial_fail_amount_action": "continue",
			"max_fail_attempts": "0",
			"return_url": `${baseUrl}/${billingUser}?page=billing&cancel=1`
		},
		"name": "3D Repo Licences",
		"payment_definitions": paymentDefs,
	    "type": "INFINITE"
	};

	console.log(JSON.stringify(billingPlanAttributes, null ,2));

	return new Promise((resolve, reject) => {

		// create plan
		paypal.billingPlan.create(billingPlanAttributes, function (err, billingPlan) {

			if(err){
				reject(err);
			} else {
				resolve(billingPlan);
			}
		});

	}).then(billingPlan => {

		//activate plan
		return new Promise((resolve, reject) => {
			var billingPlanUpdateAttributes = [
				{
					"op": "replace",
					"path": "/",
					"value": {
						"state": "ACTIVE"
					}
				}
			];

			paypal.billingPlan.update(billingPlan.id, billingPlanUpdateAttributes, function (err) {
				if (err) {
					reject(err);
				} else {
					resolve(billingPlan);
				}
			});

		});
	}).then(billingPlan => {

		//create agreement
		return new Promise((resolve, reject) => {

			let desc = `3D Repo Licence subscription.`;
			desc += `This month's pro-rata price: £${firstCycleAmount}, then `;
			desc += `each month: £${amount}`;

			console.log('desc len', desc.length);

			let billingAgreementAttributes = {
				"name": "3D Repo Licenses",
				"description": desc,
				"start_date": startDate.toISOString(),
				"plan": {
					"id": billingPlan.id
				},
				"payer": {
					"payment_method": "paypal"
				},
				"shipping_address": billingAddress
			};

			console.log('creating agreement...');
			paypal.billingAgreement.create(billingAgreementAttributes, function (err, billingAgreement) {
				if (err) {
					reject(err);
				} else {

					console.log(JSON.stringify(billingAgreement, null ,2));
					let link = billingAgreement.links.find(link => link.rel === 'approval_url');
					let token = url.parse(link.href, true).query.token;

					resolve({
						url: link.href,
						paypalPaymentToken: token
					});
				}
			});

		});

	});

}

function updateBillingAddress(billingAgreementId, billingAddress){
	'use strict';

	let updateOps = [
		{
			"op": "replace",
			"path": "/",
			"value": {
				"shipping_address": billingAddress
			}
		}
	];

	return new Promise((resolve, reject) => {
		paypal.billingAgreement.update(billingAgreementId, updateOps, function (err, billingAgreement) {
			if (err) {
				reject(err);
			} else {
				console.log(JSON.stringify(billingAgreement));
				resolve(billingAgreement);
			}
		});
	});

}

module.exports = {
	getBillingAgreement,
	updateBillingAddress,
	paypal
};
<commit_msg>ISSUE #227 - Fix cancel=1 return from PayPal cancel<commit_after>/**
 *  Copyright (C) 2014 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

var paypal = require('paypal-rest-sdk');
var url = require('url');
var config = require('../config');
var vat = require('./vat');

paypal.configure({
	'mode': config.paypal.mode, //sandbox or live
	'client_id': config.paypal.client_id,
	'client_secret': config.paypal.client_secret
});

function getBillingAgreement(billingUser, billingAddress, currency, firstCycleAmount, firstBillingCycle, amount, billingCycle, startDate){
	'use strict';

	console.log('firstCycleAmount', firstCycleAmount);
	console.log('amount', amount);
	console.log('startDate', startDate);

	let apiServerConfig = config.servers.find(server => server.service === 'api');
	let port = '';
	if(config.using_ssl && apiServerConfig.public_port !== 443 || !config.using_ssl && apiServerConfig.public_port !== 80){
		port = ':' + apiServerConfig.public_port;
	}

	let baseUrl = (config.using_ssl ? 'https://' : 'http://') + config.host + port;

	let taxAmount = vat.getByCountryCode(billingAddress.country_code) * amount;
	taxAmount = Math.round(taxAmount * 100) / 100;
	let afterTaxAmount = amount - taxAmount;
	afterTaxAmount = Math.round(afterTaxAmount * 100) / 100;

	let paymentDefs = [];
	paymentDefs.push({
		"amount": {
			"currency": currency,
			"value": afterTaxAmount
		},
		"cycles": "0",
		"frequency": "MONTH",
		"frequency_interval": billingCycle,
		"name": "Regular monthly price",
		"type": "REGULAR",
		"charge_models":[{
			"type": "TAX",
			"amount": {
				"value": taxAmount,
				"currency": currency
			}
		}]
	});

	if(firstCycleAmount){

;
		let taxFirstCycleAmount = vat.getByCountryCode(billingAddress.country_code) * firstCycleAmount;
		taxFirstCycleAmount = Math.round(taxFirstCycleAmount * 100) / 100;
		let afterTaxFirstCycleAmount = firstCycleAmount - taxFirstCycleAmount;
		afterTaxFirstCycleAmount = Math.round(afterTaxFirstCycleAmount * 100) / 100;

		paymentDefs.push({
			"amount": {
				"currency": currency,
				"value": afterTaxFirstCycleAmount
			},
			"cycles": "1",
			"frequency": "DAY",
			"frequency_interval": firstBillingCycle,
			"name": "First month pro-rata price",
			"type": "TRIAL",
			"charge_models":[{
				"type": "TAX",
				"amount": {
					"value": taxFirstCycleAmount,
					"currency": currency
				}
			}]
		});
	}

	let billingPlanAttributes = {
		"description": "3D Repo Licence",
		"merchant_preferences": {
			"auto_bill_amount": "yes",
			"cancel_url": `${baseUrl}/${billingUser}?page=billing&cancel=1`,
			"initial_fail_amount_action": "continue",
			"max_fail_attempts": "0",
			"return_url": `${baseUrl}/${billingUser}?page=billing`
		},
		"name": "3D Repo Licences",
		"payment_definitions": paymentDefs,
	    "type": "INFINITE"
	};

	console.log(JSON.stringify(billingPlanAttributes, null ,2));

	return new Promise((resolve, reject) => {

		// create plan
		paypal.billingPlan.create(billingPlanAttributes, function (err, billingPlan) {

			if(err){
				reject(err);
			} else {
				resolve(billingPlan);
			}
		});

	}).then(billingPlan => {

		//activate plan
		return new Promise((resolve, reject) => {
			var billingPlanUpdateAttributes = [
				{
					"op": "replace",
					"path": "/",
					"value": {
						"state": "ACTIVE"
					}
				}
			];

			paypal.billingPlan.update(billingPlan.id, billingPlanUpdateAttributes, function (err) {
				if (err) {
					reject(err);
				} else {
					resolve(billingPlan);
				}
			});

		});
	}).then(billingPlan => {

		//create agreement
		return new Promise((resolve, reject) => {

			let desc = `3D Repo Licence subscription.`;
			desc += `This month's pro-rata price: £${firstCycleAmount}, then `;
			desc += `each month: £${amount}`;

			console.log('desc len', desc.length);

			let billingAgreementAttributes = {
				"name": "3D Repo Licenses",
				"description": desc,
				"start_date": startDate.toISOString(),
				"plan": {
					"id": billingPlan.id
				},
				"payer": {
					"payment_method": "paypal"
				},
				"shipping_address": billingAddress
			};

			console.log('creating agreement...');
			paypal.billingAgreement.create(billingAgreementAttributes, function (err, billingAgreement) {
				if (err) {
					reject(err);
				} else {

					console.log(JSON.stringify(billingAgreement, null ,2));
					let link = billingAgreement.links.find(link => link.rel === 'approval_url');
					let token = url.parse(link.href, true).query.token;

					resolve({
						url: link.href,
						paypalPaymentToken: token
					});
				}
			});

		});

	});

}

function updateBillingAddress(billingAgreementId, billingAddress){
	'use strict';

	let updateOps = [
		{
			"op": "replace",
			"path": "/",
			"value": {
				"shipping_address": billingAddress
			}
		}
	];

	return new Promise((resolve, reject) => {
		paypal.billingAgreement.update(billingAgreementId, updateOps, function (err, billingAgreement) {
			if (err) {
				reject(err);
			} else {
				console.log(JSON.stringify(billingAgreement));
				resolve(billingAgreement);
			}
		});
	});

}

module.exports = {
	getBillingAgreement,
	updateBillingAddress,
	paypal
};
<|endoftext|>


<commit_before>var mongoose = require('mongoose');
var schema = mongoose.Schema;

var toneDataSchema = new schema({
    category_id: String,
    category_name: String,
    tones: [
        {
            tone_id: String,
            tone_name: String,
            score: Number
        }
    ]
});

module.exports = mongoose.model('ToneData', toneDataSchema);<commit_msg>Missing strict mode<commit_after>'use strict';

var mongoose = require('mongoose');
var schema = mongoose.Schema;

var toneDataSchema = new schema({
    category_id: String,
    category_name: String,
    tones: [
        {
            tone_id: String,
            tone_name: String,
            score: Number
        }
    ]
});

module.exports = mongoose.model('ToneData', toneDataSchema);<|endoftext|>


<commit_before>angular.module('os.biospecimen.models.specimen', ['os.common.models', 'os.biospecimen.models.form'])
  .factory('Specimen', function(osModel, $http, $parse, SpecimenRequirement, Form, Util, User) {

    function matches(name, regex) {
      return name && name.match(regex) != null;
    }

    function isSpecimenCentric(specimen) {
      return matches(specimen.ppid, /^(\$\$cp_reg_\d+\$\$)$/g) ||
               matches(specimen.visitName, /^(\$\$cp_visit_\d+\$\$)$/g);
    }

    var Specimen = osModel(
      'specimens',
      function(specimen) {
        specimen.externalIds = specimen.externalIds || [];

        if (specimen.specimensPool) {
          specimen.specimensPool = specimen.specimensPool.map(
            function(poolSpmn) {
              return new Specimen(poolSpmn);
            }
          );
        }

        if (specimen.children) {
          specimen.children = specimen.children.map(
            function(child) {
              return new Specimen(child);
            }
          );
        }

        if (specimen.storageLocation) {
          specimen.storageLocation = angular.extend({}, specimen.storageLocation);
        }
        specimen.$$specimenCentricCp = isSpecimenCentric(specimen);
      }
    );

    Specimen.listFor = function(cprId, visitDetail) {
      return Specimen.query(angular.extend({cprId: cprId}, visitDetail || {}));
    };

    Specimen.listByLabels = function(labels) {
      return Specimen.query({label: labels});
    };

    Specimen.flatten = function(specimens, parent, depth, pooledSpecimen, opts) {
      var result = [];
      if (!specimens) {
        return result;
      }

      depth = depth || 0;
      angular.forEach(specimens, function(specimen) {
        var depthIncrStep = 1;
        var hasChildren = (!!specimen.children && specimen.children.length > 0);
        if (opts && opts.hideDerivatives && !specimen.reqId && specimen.lineage == 'Derived' && hasChildren &&
          specimen.children.every(function(a) { return a.lineage == 'Aliquot'; })) {
          depthIncrStep = 0;
          specimen.$$invisibleN = true;
        } else {
          result.push(specimen);
        }

        specimen.depth = depth || 0;
        specimen.parent = specimen.parent || parent;
        specimen.pooledSpecimen = specimen.pooledSpecimen || pooledSpecimen;

        var hasSpecimensPool = false;
        if (depth == 0) {
          hasSpecimensPool = !!specimen.specimensPool && specimen.specimensPool.length > 0;
          if (hasSpecimensPool) {
            result = result.concat(Specimen.flatten(specimen.specimensPool, specimen, depth + 1, specimen, opts));
          }
        }

        specimen.hasChildren = hasSpecimensPool || hasChildren;
        if (hasChildren) {
          result = result.concat(Specimen.flatten(specimen.children, specimen, depth + depthIncrStep, undefined, opts));
        }

        if (specimen instanceof SpecimenRequirement) {
          return;
        }

        specimen.hasOnlyPendingChildren = hasOnlyPendingChildren(specimen.children);
        if (specimen.hasOnlyPendingChildren) {
          specimen.hasOnlyPendingChildren = hasOnlyPendingChildren(specimen.specimensPool);
        }

        if (hasSpecimensPool) {
          specimen.$$childrenHaveImg = hasImage(specimen.specimensPool);
        }

        if (!specimen.$$childrenHaveImg && hasChildren) {
          specimen.$$childrenHaveImg = hasImage(specimen.children);
        }
      });

      return result;
    };

    Specimen.save = function(specimens) {
      return $http.post(Specimen.url() + 'collect', specimens).then(Specimen.modelArrayRespTransform);
    };

    //Update specimens in bulk with same detail
    Specimen.bulkEdit = function(detail) {
      return $http.put(Specimen.url() + "bulk-update", detail).then(Specimen.modelArrayRespTransform);
    }

    //Update specimens in bulk by providing detail for each
    Specimen.bulkUpdate = function(specimens) {
      return $http.put(Specimen.url(), specimens).then(Specimen.modelArrayRespTransform);
    };

    Specimen.isUniqueLabel = function(cpShortTitle, label) {
      return $http.head(Specimen.url(), {params: {cpShortTitle: cpShortTitle, label: label}}).then(
        function(result) {
          return false;
        },

        function(result) {
          return true;
        }
      );
    };

    Specimen.getAnticipatedSpecimen = function(srId) {
      return SpecimenRequirement.getById(srId).then(
        function(sr) {
          return new Specimen(toSpecimenAttrs(sr));
        }
      );
    };

    Specimen.getRouteIds = function(specimenId) {
      return $http.get(Specimen.url() + specimenId + '/cpr-visit-ids').then(
        function(resp) {
          return resp.data;
        }
      );
    }

    Specimen.bulkDelete = function(specimenIds, reason) {
      return $http.delete(Specimen.url(), {params: {id: specimenIds, reason: reason}}).then(
        function(result) {
          return result.data;
        }
      );
    }

    Specimen.bulkStatusUpdate = function(statusSpecs) {
      return $http.put(Specimen.url() + '/status', statusSpecs).then(
        function(result) {
          return result.data;
        }
      );
    }

    Specimen.getByIds = function(ids, includeExtensions) {
      return Specimen.query({id: ids, includeExtensions: includeExtensions});
    }

    Specimen.prototype.getType = function() {
      return 'specimen';
    }

    Specimen.prototype.getDisplayName = function() {
      return this.label;
    };

    Specimen.prototype.hasSufficientQty = function() {
      var qty = this.initialQty;
      angular.forEach(this.children, function(child) {
        if (child.lineage == 'Aliquot') {
          qty -= child.initialQty;
        }
      });

      return qty >= 0;
    }

    Specimen.prototype.rootSpecimen = function() {
      var curr = this;
      while (curr.parent) {
        curr = curr.parent;
      }

      return curr;
    };

    Specimen.prototype.getPrimarySpecimenId = function() {
      return $http.get(Specimen.url() + this.$id() + '/primary-specimen-id').then(
        function(resp) {
          return resp.data.id;
        }
      );
    }

    Specimen.prototype.getExtensionCtxt = function(params) {
      return Specimen.getExtensionCtxt(params);
    }

    Specimen.prototype.getForms = function(params) {
      return Form.listFor(Specimen.url(), this.$id(), params);
    };

    Specimen.prototype.getRecords = function() {
      var url = Specimen.url() + this.$id() + '/extension-records';
      return Form.listRecords(url);
    };

    Specimen.prototype.getEvents = function(callback) {
      var events = [];

      if (!!this.$id()) {
        $http.get(Specimen.url() + '/' + this.$id() + '/events').then(
          function(result) {
            Util.unshiftAll(events, getEventsList(result.data));
            if (typeof callback == 'function') {
              callback(events);
            }
          }
        );
      }

      return events;
    };

    Specimen.prototype.$saveProps = function() {
      var props = ['children', 'depth', 'hasChildren', 'isOpened', 'specimensPool'];
      var that = this;
      props.forEach(function(prop) { delete that[prop]; });
      return this;
    };

    Specimen.prototype.close = function(reason) {
      var statusSpec = {status: 'Closed', reason: reason};
      return updateSpecimenStatus(this, statusSpec);
    }

    Specimen.prototype.reopen = function() {
      var statusSpec = {status: 'Active'};
      return updateSpecimenStatus(this, statusSpec);
    };

    Specimen.prototype.showVirtual = function() {
      return this.storageType == 'Virtual' && (!this.status || this.status == 'Pending');
    }

    Specimen.prototype.getMatchingRule = function(allocRules) {
      var result = -1;
      for (var i = 0; i < allocRules.length; ++i) {
        if ($parse(allocRules[i].criteria)({specimen: this})) {
          result = i;
          break;
        }
      }

      return {index: result, rule: result != -1 ? allocRules[result] : undefined};
    }

    Specimen.prototype.setCollectionEvent = function(formData) {
      if (this.lineage != 'New') {
        return;
      }

      var eventData = {
        id: formData.id,
        user: {id: formData.user},
        time: formData.time,
        comments: formData.comments,
        procedure: formData.procedure,
        container: formData.container
      }

      if (!this.collectionEvent) {
        this.collectionEvent = {};
      }

      if (this.collectionEvent.user && this.collectionEvent.user.id == eventData.user.id) {
        eventData.user = this.collectionEvent.user;
      } else {
        var that = this;
        User.getById(eventData.user.id).then(
          function(user) {
            that.collectionEvent.user = user;
          }
        )
      }

      angular.extend(this.collectionEvent, eventData);
    }

    Specimen.prototype.setReceivedEvent = function(formData) {
      if (this.lineage != 'New') {
        return;
      }

      var eventData = {
        id: formData.id,
        user: {id: formData.user},
        time: formData.time,
        comments: formData.comments,
        receivedQuality: formData.quality
      }

      if (!this.receivedEvent) {
        this.receivedEvent = {};
      }

      if (this.receivedEvent.user && this.receivedEvent.user.id == eventData.user.id) {
        eventData.user = this.receivedEvent.user;
      } else {
        var that = this;
        User.getById(eventData.user.id).then(
          function(user) {
            that.receivedEvent.user = user;
          }
        )
      }

      angular.extend(this.receivedEvent, eventData);
    }

    function toSpecimenAttrs(sr) {
      sr.reqId = sr.id;
      sr.reqLabel = sr.name;
      sr.poolSpecimen = !!sr.pooledSpecimenReqId;

      if (sr.lineage == 'New' && !sr.poolSpecimen) {
        sr.collectionEvent = {user: sr.collector, procedure: sr.collectionProcedure, container: sr.collectionContainer};
        sr.receivedEvent   = {user: sr.receiver, receivedQuality: 'Acceptable'};
      }

      var attrs = [
        'id', 'name', 'pooledSpecimenReqId',
        'collector', 'collectionProcedure', 'collectionContainer',
        'receiver', 'labelPrintCopies'
      ];

      attrs.forEach(function(attr) {
        delete sr[attr];
      });

      if (sr.children) {
        sr.children = sr.children.map(toSpecimenAttrs);
      }

      if (sr.specimensPool) {
        sr.specimensPool = sr.specimensPool.map(toSpecimenAttrs);
      }

      return sr;
    };

    function getEventsList(eventsRecs) { /* eventsRecs: [{event info, records: [event records]}] */
      var eventsList = [];
      angular.forEach(eventsRecs, function(eventRecs) {
        angular.forEach(eventRecs.records, function(record) {
          var user = null, time = null;
          for (var i = 0; i < record.fieldValues.length; ++i) {
            if (record.fieldValues[i].name == 'user') {
              user = record.fieldValues[i].value;
            } else if (record.fieldValues[i].name == 'time') {
              time = record.fieldValues[i].value;
            }
          }

          var formName = eventRecs.name;
          eventsList.push({
            id: record.recordId,
            formId: eventRecs.id,
            formCtxtId: record.fcId,
            sysForm: record.sysForm,
            name: eventRecs.caption,
            updatedBy: record.user,
            updateTime: record.updateTime,
            user: user,
            time: time,
            isEditable: !record.sysForm || formName == 'SpecimenCollectionEvent' || formName == 'SpecimenReceivedEvent'
          });
        });
      });

      eventsList.sort(
        function(e1, e2) {
          var t1 = e1.time || 0;
          var t2 = e2.time || 0;
          return t2 - t1;
        }
      );
      return eventsList;
    }

    function updateSpecimenStatus(specimen, statusSpec) {
      return $http.put(Specimen.url() + '/' + specimen.$id() + '/status', statusSpec).then(
        function(result) {
          angular.extend(specimen, result.data);
          return new Specimen(result);
        }
      );
    }

    function hasOnlyPendingChildren(specimens) {
      if (!specimens || specimens.length == 0) {
        return true;
      }

      return specimens.every(
        function(spmn) {
          return !spmn.status || spmn.status == 'Pending';
        }
      );
    }

    function hasImage(specimens) {
      return (specimens || []).some(
        function(spmn) {
          return !!spmn.imageId || !!spmn.$$childrenHaveImg;
        }
      );
    }

    return Specimen;
  });
<commit_msg>OPSMN-4859: The specimen external IDs in UI was initialised to an empty list. This was erasing the external IDs when the specimen was patch updated.<commit_after>angular.module('os.biospecimen.models.specimen', ['os.common.models', 'os.biospecimen.models.form'])
  .factory('Specimen', function(osModel, $http, $parse, SpecimenRequirement, Form, Util, User) {

    function matches(name, regex) {
      return name && name.match(regex) != null;
    }

    function isSpecimenCentric(specimen) {
      return matches(specimen.ppid, /^(\$\$cp_reg_\d+\$\$)$/g) ||
               matches(specimen.visitName, /^(\$\$cp_visit_\d+\$\$)$/g);
    }

    var Specimen = osModel(
      'specimens',
      function(specimen) {
        if (specimen.specimensPool) {
          specimen.specimensPool = specimen.specimensPool.map(
            function(poolSpmn) {
              return new Specimen(poolSpmn);
            }
          );
        }

        if (specimen.children) {
          specimen.children = specimen.children.map(
            function(child) {
              return new Specimen(child);
            }
          );
        }

        if (specimen.storageLocation) {
          specimen.storageLocation = angular.extend({}, specimen.storageLocation);
        }
        specimen.$$specimenCentricCp = isSpecimenCentric(specimen);
      }
    );

    Specimen.listFor = function(cprId, visitDetail) {
      return Specimen.query(angular.extend({cprId: cprId}, visitDetail || {}));
    };

    Specimen.listByLabels = function(labels) {
      return Specimen.query({label: labels});
    };

    Specimen.flatten = function(specimens, parent, depth, pooledSpecimen, opts) {
      var result = [];
      if (!specimens) {
        return result;
      }

      depth = depth || 0;
      angular.forEach(specimens, function(specimen) {
        var depthIncrStep = 1;
        var hasChildren = (!!specimen.children && specimen.children.length > 0);
        if (opts && opts.hideDerivatives && !specimen.reqId && specimen.lineage == 'Derived' && hasChildren &&
          specimen.children.every(function(a) { return a.lineage == 'Aliquot'; })) {
          depthIncrStep = 0;
          specimen.$$invisibleN = true;
        } else {
          result.push(specimen);
        }

        specimen.depth = depth || 0;
        specimen.parent = specimen.parent || parent;
        specimen.pooledSpecimen = specimen.pooledSpecimen || pooledSpecimen;

        var hasSpecimensPool = false;
        if (depth == 0) {
          hasSpecimensPool = !!specimen.specimensPool && specimen.specimensPool.length > 0;
          if (hasSpecimensPool) {
            result = result.concat(Specimen.flatten(specimen.specimensPool, specimen, depth + 1, specimen, opts));
          }
        }

        specimen.hasChildren = hasSpecimensPool || hasChildren;
        if (hasChildren) {
          result = result.concat(Specimen.flatten(specimen.children, specimen, depth + depthIncrStep, undefined, opts));
        }

        if (specimen instanceof SpecimenRequirement) {
          return;
        }

        specimen.hasOnlyPendingChildren = hasOnlyPendingChildren(specimen.children);
        if (specimen.hasOnlyPendingChildren) {
          specimen.hasOnlyPendingChildren = hasOnlyPendingChildren(specimen.specimensPool);
        }

        if (hasSpecimensPool) {
          specimen.$$childrenHaveImg = hasImage(specimen.specimensPool);
        }

        if (!specimen.$$childrenHaveImg && hasChildren) {
          specimen.$$childrenHaveImg = hasImage(specimen.children);
        }
      });

      return result;
    };

    Specimen.save = function(specimens) {
      return $http.post(Specimen.url() + 'collect', specimens).then(Specimen.modelArrayRespTransform);
    };

    //Update specimens in bulk with same detail
    Specimen.bulkEdit = function(detail) {
      return $http.put(Specimen.url() + "bulk-update", detail).then(Specimen.modelArrayRespTransform);
    }

    //Update specimens in bulk by providing detail for each
    Specimen.bulkUpdate = function(specimens) {
      return $http.put(Specimen.url(), specimens).then(Specimen.modelArrayRespTransform);
    };

    Specimen.isUniqueLabel = function(cpShortTitle, label) {
      return $http.head(Specimen.url(), {params: {cpShortTitle: cpShortTitle, label: label}}).then(
        function(result) {
          return false;
        },

        function(result) {
          return true;
        }
      );
    };

    Specimen.getAnticipatedSpecimen = function(srId) {
      return SpecimenRequirement.getById(srId).then(
        function(sr) {
          return new Specimen(toSpecimenAttrs(sr));
        }
      );
    };

    Specimen.getRouteIds = function(specimenId) {
      return $http.get(Specimen.url() + specimenId + '/cpr-visit-ids').then(
        function(resp) {
          return resp.data;
        }
      );
    }

    Specimen.bulkDelete = function(specimenIds, reason) {
      return $http.delete(Specimen.url(), {params: {id: specimenIds, reason: reason}}).then(
        function(result) {
          return result.data;
        }
      );
    }

    Specimen.bulkStatusUpdate = function(statusSpecs) {
      return $http.put(Specimen.url() + '/status', statusSpecs).then(
        function(result) {
          return result.data;
        }
      );
    }

    Specimen.getByIds = function(ids, includeExtensions) {
      return Specimen.query({id: ids, includeExtensions: includeExtensions});
    }

    Specimen.prototype.getType = function() {
      return 'specimen';
    }

    Specimen.prototype.getDisplayName = function() {
      return this.label;
    };

    Specimen.prototype.hasSufficientQty = function() {
      var qty = this.initialQty;
      angular.forEach(this.children, function(child) {
        if (child.lineage == 'Aliquot') {
          qty -= child.initialQty;
        }
      });

      return qty >= 0;
    }

    Specimen.prototype.rootSpecimen = function() {
      var curr = this;
      while (curr.parent) {
        curr = curr.parent;
      }

      return curr;
    };

    Specimen.prototype.getPrimarySpecimenId = function() {
      return $http.get(Specimen.url() + this.$id() + '/primary-specimen-id').then(
        function(resp) {
          return resp.data.id;
        }
      );
    }

    Specimen.prototype.getExtensionCtxt = function(params) {
      return Specimen.getExtensionCtxt(params);
    }

    Specimen.prototype.getForms = function(params) {
      return Form.listFor(Specimen.url(), this.$id(), params);
    };

    Specimen.prototype.getRecords = function() {
      var url = Specimen.url() + this.$id() + '/extension-records';
      return Form.listRecords(url);
    };

    Specimen.prototype.getEvents = function(callback) {
      var events = [];

      if (!!this.$id()) {
        $http.get(Specimen.url() + '/' + this.$id() + '/events').then(
          function(result) {
            Util.unshiftAll(events, getEventsList(result.data));
            if (typeof callback == 'function') {
              callback(events);
            }
          }
        );
      }

      return events;
    };

    Specimen.prototype.$saveProps = function() {
      var props = ['children', 'depth', 'hasChildren', 'isOpened', 'specimensPool'];
      var that = this;
      props.forEach(function(prop) { delete that[prop]; });
      return this;
    };

    Specimen.prototype.close = function(reason) {
      var statusSpec = {status: 'Closed', reason: reason};
      return updateSpecimenStatus(this, statusSpec);
    }

    Specimen.prototype.reopen = function() {
      var statusSpec = {status: 'Active'};
      return updateSpecimenStatus(this, statusSpec);
    };

    Specimen.prototype.showVirtual = function() {
      return this.storageType == 'Virtual' && (!this.status || this.status == 'Pending');
    }

    Specimen.prototype.getMatchingRule = function(allocRules) {
      var result = -1;
      for (var i = 0; i < allocRules.length; ++i) {
        if ($parse(allocRules[i].criteria)({specimen: this})) {
          result = i;
          break;
        }
      }

      return {index: result, rule: result != -1 ? allocRules[result] : undefined};
    }

    Specimen.prototype.setCollectionEvent = function(formData) {
      if (this.lineage != 'New') {
        return;
      }

      var eventData = {
        id: formData.id,
        user: {id: formData.user},
        time: formData.time,
        comments: formData.comments,
        procedure: formData.procedure,
        container: formData.container
      }

      if (!this.collectionEvent) {
        this.collectionEvent = {};
      }

      if (this.collectionEvent.user && this.collectionEvent.user.id == eventData.user.id) {
        eventData.user = this.collectionEvent.user;
      } else {
        var that = this;
        User.getById(eventData.user.id).then(
          function(user) {
            that.collectionEvent.user = user;
          }
        )
      }

      angular.extend(this.collectionEvent, eventData);
    }

    Specimen.prototype.setReceivedEvent = function(formData) {
      if (this.lineage != 'New') {
        return;
      }

      var eventData = {
        id: formData.id,
        user: {id: formData.user},
        time: formData.time,
        comments: formData.comments,
        receivedQuality: formData.quality
      }

      if (!this.receivedEvent) {
        this.receivedEvent = {};
      }

      if (this.receivedEvent.user && this.receivedEvent.user.id == eventData.user.id) {
        eventData.user = this.receivedEvent.user;
      } else {
        var that = this;
        User.getById(eventData.user.id).then(
          function(user) {
            that.receivedEvent.user = user;
          }
        )
      }

      angular.extend(this.receivedEvent, eventData);
    }

    function toSpecimenAttrs(sr) {
      sr.reqId = sr.id;
      sr.reqLabel = sr.name;
      sr.poolSpecimen = !!sr.pooledSpecimenReqId;

      if (sr.lineage == 'New' && !sr.poolSpecimen) {
        sr.collectionEvent = {user: sr.collector, procedure: sr.collectionProcedure, container: sr.collectionContainer};
        sr.receivedEvent   = {user: sr.receiver, receivedQuality: 'Acceptable'};
      }

      var attrs = [
        'id', 'name', 'pooledSpecimenReqId',
        'collector', 'collectionProcedure', 'collectionContainer',
        'receiver', 'labelPrintCopies'
      ];

      attrs.forEach(function(attr) {
        delete sr[attr];
      });

      if (sr.children) {
        sr.children = sr.children.map(toSpecimenAttrs);
      }

      if (sr.specimensPool) {
        sr.specimensPool = sr.specimensPool.map(toSpecimenAttrs);
      }

      return sr;
    };

    function getEventsList(eventsRecs) { /* eventsRecs: [{event info, records: [event records]}] */
      var eventsList = [];
      angular.forEach(eventsRecs, function(eventRecs) {
        angular.forEach(eventRecs.records, function(record) {
          var user = null, time = null;
          for (var i = 0; i < record.fieldValues.length; ++i) {
            if (record.fieldValues[i].name == 'user') {
              user = record.fieldValues[i].value;
            } else if (record.fieldValues[i].name == 'time') {
              time = record.fieldValues[i].value;
            }
          }

          var formName = eventRecs.name;
          eventsList.push({
            id: record.recordId,
            formId: eventRecs.id,
            formCtxtId: record.fcId,
            sysForm: record.sysForm,
            name: eventRecs.caption,
            updatedBy: record.user,
            updateTime: record.updateTime,
            user: user,
            time: time,
            isEditable: !record.sysForm || formName == 'SpecimenCollectionEvent' || formName == 'SpecimenReceivedEvent'
          });
        });
      });

      eventsList.sort(
        function(e1, e2) {
          var t1 = e1.time || 0;
          var t2 = e2.time || 0;
          return t2 - t1;
        }
      );
      return eventsList;
    }

    function updateSpecimenStatus(specimen, statusSpec) {
      return $http.put(Specimen.url() + '/' + specimen.$id() + '/status', statusSpec).then(
        function(result) {
          angular.extend(specimen, result.data);
          return new Specimen(result);
        }
      );
    }

    function hasOnlyPendingChildren(specimens) {
      if (!specimens || specimens.length == 0) {
        return true;
      }

      return specimens.every(
        function(spmn) {
          return !spmn.status || spmn.status == 'Pending';
        }
      );
    }

    function hasImage(specimens) {
      return (specimens || []).some(
        function(spmn) {
          return !!spmn.imageId || !!spmn.$$childrenHaveImg;
        }
      );
    }

    return Specimen;
  });
<|endoftext|>


<commit_before><commit_msg>Updates session deletion script<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('rangeNumberSpinnerApp')
	.directive('rangeSpinner',  function() {
		return {
			restrict : 'AE',
			scope : {
				rangeMin:"@",
				rangeStep:"@",
				rangeMax:"@",
				rangeDefaultValue:"@",
				acceptDecimal:"@",
				rangeModel:"=",
				nameOfField:"@",
				idOfField:"@",
				rangeDecimalPrecision:"@"
			},
			templateUrl : 'tmpl/rangeSpinner.html',
			controller : function($scope,$element,$attrs) {

				//Initializing minRange, step and maxRange with default Value if not provided.
				$scope.minRange = +(angular.isDefined($attrs.rangeMin)?$attrs.rangeMin:0);
				$scope.step = +(angular.isDefined($attrs.rangeStep)?$attrs.rangeStep:0);
				$scope.maxRange = +(angular.isDefined($attrs.rangeMax)?$attrs.rangeMax:100);
				$scope.rangeDecPrec = +(angular.isDefined($attrs.rangeDecimalPrecision)?$attrs.rangeDecimalPrecision:1);

				//Initializing rangeModel with default Value if supplied rangeDefaultValue is not between minRange and maxRange.
				if(angular.isDefined($scope.rangeDefaultValue) && !isNaN($scope.rangeDefaultValue)){
				 var rangeDefaultVal = parseFloat($scope.rangeDefaultValue);
				 if(rangeDefaultVal >= $scope.minRange && rangeDefaultVal <= $scope.maxRange){
					$scope.rangeModel = parseFloat($scope.rangeDefaultValue).toFixed($scope.rangeDecPrec);
				 }else{
					$scope.rangeModel = parseFloat($scope.minRange).toFixed($scope.rangeDecPrec);
				 }
				}

				//Plus Button Method
				$scope.queueRangePlus = function() {
					if (angular.isUndefined($scope.rangeModel) || isNaN($scope.rangeModel) || $scope.rangeModel===""){
						$scope.rangeModel = $scope.minRange;
					}else{
						if ($scope.rangeModel < $scope.maxRange) {
							if($scope.acceptDecimal == 'true'){
								$scope.rangeModel = (parseFloat(parseFloat($scope.rangeModel) + parseFloat($scope.step))).toFixed($scope.rangeDecPrec);
							}else{
								$scope.rangeModel = (parseInt(parseInt($scope.rangeModel) + parseInt($scope.step)));
							}
						}
					}
				};

				//Minus Button Method
				$scope.queueRangeMinus = function() {
					if (angular.isUndefined($scope.rangeModel) || isNaN($scope.rangeModel) || $scope.rangeModel===""){
						$scope.rangeModel = $scope.minRange;
					}else{
						if ($scope.rangeModel > $scope.minRange) {
							if($scope.acceptDecimal == 'true'){
								$scope.rangeModel = (parseFloat(parseFloat($scope.rangeModel) - parseFloat($scope.step))).toFixed($scope.rangeDecPrec);
							}else{
								$scope.rangeModel = (parseInt(parseInt($scope.rangeModel) - parseInt($scope.step)));
							}

						}
					}
				};

				//For Direct Editing
				$scope.$watch(function(){
					return $scope.rangeModel;
				}, function(newvalue, oldvalue){

					if(angular.isDefined($scope.rangeModel)){
						if (!isNaN($scope.rangeModel)){
							if ($scope.rangeModel > $scope.maxRange){
								$scope.rangeModel = $scope.maxRange;
							}else if ($scope.rangeModel < $scope.minRange){
								$scope.rangeModel = $scope.minRange;
							}else{

								if($scope.acceptDecimal == 'true'){
									var precision = String($scope.rangeModel).split(".");
									if(precision.length>1 && precision[1].length>$scope.rangeDecPrec){
										$scope.rangeModel = (parseFloat($scope.rangeModel)).toFixed($scope.rangeDecPrec);
									}
								}else{
									$scope.rangeModel = parseInt($scope.rangeModel);
								}
							}
						}else{
							$scope.rangeModel = oldvalue;
						}
					}
				},true);

			}
		};
	})
	.run(['$templateCache',function($templateCache){
		console.log("In the spinner run method of the module");
		$templateCache.put('tmpl/rangeSpinner.html',
				'
 \

 \
						<button type="button" class="minus" ng-click="queueRangeMinus()">-</button> \
						<input name="{{nameOfField}}" id="{{idOfField}}" type="text" class="queueFactorRange" range-min="{{rangeMin}}" range-step="{{rangeStep}}" range-max="{{rangeMax}}" ng-model="rangeModel" required> \
						<button type="button" class="plus" ng-click="queueRangePlus()">+</button>\

 \

');
	}]);

<commit_msg>Delete directive.js<commit_after><|endoftext|>


<commit_before>(function() {

  var _slice = Array.prototype.slice;

  /**
   * Takes id and returns an element with that id (if one exists in a document)
   * @memberOf fabric.util
   * @param {String|HTMLElement} id
   * @return {HTMLElement|null}
   */
  function getById(id) {
    return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  }

  /**
   * Converts an array-like object (e.g. arguments or NodeList) to an array
   * @memberOf fabric.util
   * @param {Object} arrayLike
   * @return {Array}
   */
  var toArray = function(arrayLike) {
    return _slice.call(arrayLike, 0);
  };

  var sliceCanConvertNodelists;
  try {
    sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  }
  catch(err) { }

  if (!sliceCanConvertNodelists) {
    toArray = function(arrayLike) {
      var arr = new Array(arrayLike.length), i = arrayLike.length;
      while (i--) {
        arr[i] = arrayLike[i];
      }
      return arr;
    };
  }

  /**
   * Creates specified element with specified attributes
   * @memberOf fabric.util
   * @param {String} tagName Type of an element to create
   * @param {Object} [attributes] Attributes to set on an element
   * @return {HTMLElement} Newly created element
   */
  function makeElement(tagName, attributes) {
    var el = fabric.document.createElement(tagName);
    for (var prop in attributes) {
      if (prop === 'class') {
        el.className = attributes[prop];
      }
      else if (prop === 'for') {
        el.htmlFor = attributes[prop];
      }
      else {
        el.setAttribute(prop, attributes[prop]);
      }
    }
    return el;
  }

  /**
   * Adds class to an element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to add class to
   * @param {String} className Class to add to an element
   */
  function addClass(element, className) {
    if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
      element.className += (element.className ? ' ' : '') + className;
    }
  }

  /**
   * Wraps element with another element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to wrap
   * @param {HTMLElement|String} wrapper Element to wrap with
   * @param {Object} [attributes] Attributes to set on a wrapper
   * @return {HTMLElement} wrapper
   */
  function wrapElement(element, wrapper, attributes) {
    if (typeof wrapper === 'string') {
      wrapper = makeElement(wrapper, attributes);
    }
    if (element.parentNode) {
      element.parentNode.replaceChild(wrapper, element);
    }
    wrapper.appendChild(element);
    return wrapper;
  }

  /**
   * Returns offset for a given element
   * @function
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to get offset for
   * @return {Object} Object with "left" and "top" properties
   */
  function getElementOffset(element) {
    // TODO (kangax): need to fix this method
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    }
    while (element);
    return ({ left: valueL, top: valueT });
  }

  /**
  * Returns position of a given element
  * @function
  * @memberOf fabric.util
  * @param {HTMLElement} element Element to get offset for
  * @return {Object} position of the given element.
  */
  var getElementPosition;
  if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
    getElementPosition = function (element) {
      return fabric.document.defaultView.getComputedStyle(element, null).position;
    };
  }
  else {
    /** @ignore */
    getElementPosition = function (element) {
      var value = element.style.position;
      if (!value && element.currentStyle) value = element.currentStyle.position;
      return value;
    };
  }

  (function () {
    var style = fabric.document.documentElement.style;

    var selectProp = 'userSelect' in style
      ? 'userSelect'
      : 'MozUserSelect' in style
        ? 'MozUserSelect'
        : 'WebkitUserSelect' in style
          ? 'WebkitUserSelect'
          : 'KhtmlUserSelect' in style
            ? 'KhtmlUserSelect'
            : '';

    /**
     * Makes element unselectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make unselectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementUnselectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = fabric.util.falseFunction;
      }
      if (selectProp) {
        element.style[selectProp] = 'none';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = 'on';
      }
      return element;
    }

    /**
     * Makes element selectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make selectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementSelectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = null;
      }
      if (selectProp) {
        element.style[selectProp] = '';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = '';
      }
      return element;
    }

    fabric.util.makeElementUnselectable = makeElementUnselectable;
    fabric.util.makeElementSelectable = makeElementSelectable;
  })();

  (function() {

    /**
     * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
     * @memberOf fabric.util
     * @param {String} url URL of a script to load
     * @param {Function} callback Callback to execute when script is finished loading
     */
    function getScript(url, callback) {
      var headEl = fabric.document.getElementsByTagName("head")[0],
          scriptEl = fabric.document.createElement('script'),
          loading = true;

      scriptEl.type = 'text/javascript';
      scriptEl.setAttribute('runat', 'server');

      /** @ignore */
      scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
        if (loading) {
          if (typeof this.readyState === 'string' &&
              this.readyState !== 'loaded' &&
              this.readyState !== 'complete') return;
          loading = false;
          callback(e || fabric.window.event);
          scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
        }
      };
      scriptEl.src = url;
      headEl.appendChild(scriptEl);
      // causes issue in Opera
      // headEl.removeChild(scriptEl);
    }

    fabric.util.getScript = getScript;
  })();

  fabric.util.getById = getById;
  fabric.util.toArray = toArray;
  fabric.util.makeElement = makeElement;
  fabric.util.addClass = addClass;
  fabric.util.wrapElement = wrapElement;
  fabric.util.getElementOffset = getElementOffset;
  fabric.util.getElementPosition = getElementPosition;

})();
<commit_msg>Remove unnecessary script attributes<commit_after>(function() {

  var _slice = Array.prototype.slice;

  /**
   * Takes id and returns an element with that id (if one exists in a document)
   * @memberOf fabric.util
   * @param {String|HTMLElement} id
   * @return {HTMLElement|null}
   */
  function getById(id) {
    return typeof id === 'string' ? fabric.document.getElementById(id) : id;
  }

  /**
   * Converts an array-like object (e.g. arguments or NodeList) to an array
   * @memberOf fabric.util
   * @param {Object} arrayLike
   * @return {Array}
   */
  var toArray = function(arrayLike) {
    return _slice.call(arrayLike, 0);
  };

  var sliceCanConvertNodelists;
  try {
    sliceCanConvertNodelists = toArray(fabric.document.childNodes) instanceof Array;
  }
  catch(err) { }

  if (!sliceCanConvertNodelists) {
    toArray = function(arrayLike) {
      var arr = new Array(arrayLike.length), i = arrayLike.length;
      while (i--) {
        arr[i] = arrayLike[i];
      }
      return arr;
    };
  }

  /**
   * Creates specified element with specified attributes
   * @memberOf fabric.util
   * @param {String} tagName Type of an element to create
   * @param {Object} [attributes] Attributes to set on an element
   * @return {HTMLElement} Newly created element
   */
  function makeElement(tagName, attributes) {
    var el = fabric.document.createElement(tagName);
    for (var prop in attributes) {
      if (prop === 'class') {
        el.className = attributes[prop];
      }
      else if (prop === 'for') {
        el.htmlFor = attributes[prop];
      }
      else {
        el.setAttribute(prop, attributes[prop]);
      }
    }
    return el;
  }

  /**
   * Adds class to an element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to add class to
   * @param {String} className Class to add to an element
   */
  function addClass(element, className) {
    if ((' ' + element.className + ' ').indexOf(' ' + className + ' ') === -1) {
      element.className += (element.className ? ' ' : '') + className;
    }
  }

  /**
   * Wraps element with another element
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to wrap
   * @param {HTMLElement|String} wrapper Element to wrap with
   * @param {Object} [attributes] Attributes to set on a wrapper
   * @return {HTMLElement} wrapper
   */
  function wrapElement(element, wrapper, attributes) {
    if (typeof wrapper === 'string') {
      wrapper = makeElement(wrapper, attributes);
    }
    if (element.parentNode) {
      element.parentNode.replaceChild(wrapper, element);
    }
    wrapper.appendChild(element);
    return wrapper;
  }

  /**
   * Returns offset for a given element
   * @function
   * @memberOf fabric.util
   * @param {HTMLElement} element Element to get offset for
   * @return {Object} Object with "left" and "top" properties
   */
  function getElementOffset(element) {
    // TODO (kangax): need to fix this method
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    }
    while (element);
    return ({ left: valueL, top: valueT });
  }

  /**
  * Returns position of a given element
  * @function
  * @memberOf fabric.util
  * @param {HTMLElement} element Element to get offset for
  * @return {Object} position of the given element.
  */
  var getElementPosition;
  if (fabric.document.defaultView && fabric.document.defaultView.getComputedStyle) {
    getElementPosition = function (element) {
      return fabric.document.defaultView.getComputedStyle(element, null).position;
    };
  }
  else {
    /** @ignore */
    getElementPosition = function (element) {
      var value = element.style.position;
      if (!value && element.currentStyle) value = element.currentStyle.position;
      return value;
    };
  }

  (function () {
    var style = fabric.document.documentElement.style;

    var selectProp = 'userSelect' in style
      ? 'userSelect'
      : 'MozUserSelect' in style
        ? 'MozUserSelect'
        : 'WebkitUserSelect' in style
          ? 'WebkitUserSelect'
          : 'KhtmlUserSelect' in style
            ? 'KhtmlUserSelect'
            : '';

    /**
     * Makes element unselectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make unselectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementUnselectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = fabric.util.falseFunction;
      }
      if (selectProp) {
        element.style[selectProp] = 'none';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = 'on';
      }
      return element;
    }

    /**
     * Makes element selectable
     * @memberOf fabric.util
     * @param {HTMLElement} element Element to make selectable
     * @return {HTMLElement} Element that was passed in
     */
    function makeElementSelectable(element) {
      if (typeof element.onselectstart !== 'undefined') {
        element.onselectstart = null;
      }
      if (selectProp) {
        element.style[selectProp] = '';
      }
      else if (typeof element.unselectable === 'string') {
        element.unselectable = '';
      }
      return element;
    }

    fabric.util.makeElementUnselectable = makeElementUnselectable;
    fabric.util.makeElementSelectable = makeElementSelectable;
  })();

  (function() {

    /**
     * Inserts a script element with a given url into a document; invokes callback, when that script is finished loading
     * @memberOf fabric.util
     * @param {String} url URL of a script to load
     * @param {Function} callback Callback to execute when script is finished loading
     */
    function getScript(url, callback) {
      var headEl = fabric.document.getElementsByTagName("head")[0],
          scriptEl = fabric.document.createElement('script'),
          loading = true;

      /** @ignore */
      scriptEl.onload = /** @ignore */ scriptEl.onreadystatechange = function(e) {
        if (loading) {
          if (typeof this.readyState === 'string' &&
              this.readyState !== 'loaded' &&
              this.readyState !== 'complete') return;
          loading = false;
          callback(e || fabric.window.event);
          scriptEl = scriptEl.onload = scriptEl.onreadystatechange = null;
        }
      };
      scriptEl.src = url;
      headEl.appendChild(scriptEl);
      // causes issue in Opera
      // headEl.removeChild(scriptEl);
    }

    fabric.util.getScript = getScript;
  })();

  fabric.util.getById = getById;
  fabric.util.toArray = toArray;
  fabric.util.makeElement = makeElement;
  fabric.util.addClass = addClass;
  fabric.util.wrapElement = wrapElement;
  fabric.util.getElementOffset = getElementOffset;
  fabric.util.getElementPosition = getElementPosition;

})();
<|endoftext|>


<commit_before>var http = require('http'),
  url = require('url'),
  core = require("runtime/core"),
  stream = require("runtime/stream"),
  reader = require("compiler/reader"),
  compiler = require("compiler/compiler");

function handler (req, res) {
    var code = "";
    req.on('data', function(chunk) {
               code += chunk.toString();
           });

    req.on('end', function() {
               try {
                   var sourceStream =
                       core.make(stream._CL_stringStream, core._k("string"),
                                 "(begin " + code + ")");
                   sourceStream.line = 1;
                   var form = reader.read(sourceStream);
                   var options = url.parse(req.url, true).query;
                   var compiled = compiler.compile(form,
                                                   core._k('statements?'), ((options && options.hasOwnProperty('statements'))
                                                                            ? !!options.statements : true),
                                                   core._k('asynchronous?'), options && !!options.asynchronous);
                   if (options.optimize) {
                       var req2 = http.request({host: 'closure-compiler.appspot.com',
                                                path: '/compile',
                                                method: 'POST',
                                                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                                               },
                                               function (res2) {
                                                   var optimized = '';

                                                   res2.on('data', function (chunk) {
                                                               optimized += chunk.toString();
                                                           });

                                                   res2.on('end', function () {
                                                               res.writeHead(200, {'Content-Type': 'text/javascript'});
                                                               res.end(optimized);
                                                           });
                                               });
                       req2.write("compilation_level=ADVANCED_OPTIMIZATIONS&js_code="
                                  + encodeURIComponent(compiled)
                                  + "&output_format=text&output_info=compiled_code");
                       req2.end();
                   } else {
                       res.writeHead(200, {'Content-Type': 'text/javascript'});
                       res.end(compiled);
                   }
               } catch (e) {
                   res.writeHead(500);
                   res.end(e.stack.toString());
               }
           });
}

http.createServer(handler).listen(5000, "127.0.0.1");
console.log('POST Ralph code to http://127.0.0.1:5000/');
<commit_msg>server: just use simple optimizations<commit_after>var http = require('http'),
  url = require('url'),
  core = require("runtime/core"),
  stream = require("runtime/stream"),
  reader = require("compiler/reader"),
  compiler = require("compiler/compiler");

function handler (req, res) {
    var code = "";
    req.on('data', function(chunk) {
               code += chunk.toString();
           });

    req.on('end', function() {
               try {
                   var sourceStream =
                       core.make(stream._CL_stringStream, core._k("string"),
                                 "(begin " + code + ")");
                   sourceStream.line = 1;
                   var form = reader.read(sourceStream);
                   var options = url.parse(req.url, true).query;
                   var compiled = compiler.compile(form,
                                                   core._k('statements?'), ((options && options.hasOwnProperty('statements'))
                                                                            ? !!options.statements : true),
                                                   core._k('asynchronous?'), options && !!options.asynchronous);
                   if (options.optimize) {
                       var req2 = http.request({host: 'closure-compiler.appspot.com',
                                                path: '/compile',
                                                method: 'POST',
                                                headers: {'Content-Type': 'application/x-www-form-urlencoded'}
                                               },
                                               function (res2) {
                                                   var optimized = '';

                                                   res2.on('data', function (chunk) {
                                                               optimized += chunk.toString();
                                                           });

                                                   res2.on('end', function () {
                                                               res.writeHead(200, {'Content-Type': 'text/javascript'});
                                                               res.end(optimized);
                                                           });
                                               });
                       req2.write("compilation_level=SIMPLE_OPTIMIZATIONS&js_code="
                                  + encodeURIComponent(compiled)
                                  + "&output_format=text&output_info=compiled_code");
                       req2.end();
                   } else {
                       res.writeHead(200, {'Content-Type': 'text/javascript'});
                       res.end(compiled);
                   }
               } catch (e) {
                   res.writeHead(500);
                   res.end(e.stack.toString());
               }
           });
}

http.createServer(handler).listen(5000, "127.0.0.1");
console.log('POST Ralph code to http://127.0.0.1:5000/');
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';
import AbstractComponent from './AbstractComponent';
import Dialog from './Dialog';

/**
 * 全屏加载弹出框
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/24
 */
class LoadingDialog extends AbstractComponent {

  static propTypes = {
    children: PropTypes.node,
    hideAnimation: PropTypes.object,
    loadProps: PropTypes.object,
    minShowTime: PropTypes.number,
    showAnimation: PropTypes.object,
    statusBarAutoHidden: PropTypes.bool
  };

  static defaultProps = {
    children: 'loading ...',
    hideAnimation: {
      animation: 'fadeOut'
    },
    minShowTime: 1500,
    loadProps: {
      color: '#FFF'
    },
    showAnimation: {
      animation: 'fadeIn'
    },
    statusBarAutoHidden: false
  };

  constructor(props) {
    super(props);
    this.state = {
      visible: props.visible
    };

    setTimeout(()=> {
      this.canClose = true;
    }, props.minShowTime);
  }

  state = {};

  taskId;
  canClose = false;

  componentWillReceiveProps(nextProps) {
    if (this.props.visible !== nextProps.visible) {
      if (nextProps.visible) {
        this.setState({visible: true});
      } else {
        this.close();
      }
    }
  }

  componentWillUnmount() {
    this.taskId && clearTimeout(this.taskId);
  }

  close() {
    if (this.canClose) {
      this.setState({visible: false});
    }
  }

  render() {
    let {children, ...other} = this.props;
    return (
      <Dialog {...other}
        loadChildren={children}
        loading
        visible={this.state.visible}
      />
    );
  }
}

export default LoadingDialog;
<commit_msg>dialog 不关闭bug修复<commit_after>import React, { PropTypes } from 'react';
import AbstractComponent from './AbstractComponent';
import Dialog from './Dialog';

/**
 * 全屏加载弹出框
 * @author 田尘殇Sean(sean.snow@live.com)
 * @date 16/5/24
 */
class LoadingDialog extends AbstractComponent {

  static propTypes = {
    children: PropTypes.node,
    hideAnimation: PropTypes.object,
    loadProps: PropTypes.object,
    minShowTime: PropTypes.number,
    showAnimation: PropTypes.object,
    statusBarAutoHidden: PropTypes.bool
  };

  static defaultProps = {
    children: 'loading ...',
    hideAnimation: {
      animation: 'fadeOut'
    },
    minShowTime: 1500,
    loadProps: {
      color: '#FFF'
    },
    showAnimation: {
      animation: 'fadeIn'
    },
    statusBarAutoHidden: false
  };

  constructor(props) {
    super(props);
    this.state = {
      visible: props.visible
    };

    setTimeout(()=> {
      this.canClose = true;
      if (!this.props.visible) {
        this.close();
      }
    }, props.minShowTime);
  }

  state = {};

  taskId;
  canClose = false;

  componentWillReceiveProps(nextProps) {
    if (this.props.visible !== nextProps.visible) {
      if (nextProps.visible) {
        this.setState({visible: true});
      } else {
        this.close();
      }
    }
  }

  componentWillUnmount() {
    this.taskId && clearTimeout(this.taskId);
  }

  close() {
    if (this.canClose) {
      this.setState({visible: false});
    }
  }

  render() {
    let {children, ...other} = this.props;
    return (
      <Dialog {...other}
        loadChildren={children}
        loading
        visible={this.state.visible}
      />
    );
  }
}

export default LoadingDialog;
<|endoftext|>


<commit_before>//PacaClass.include('jquery-1.7.2.min.js');
//PacaClass.include('pure_min.js');
//PacaClass.include('pacaclass.event.js');

/*********************************************
 *
 * DisplayEvent(template_selector, [directives])
 * Events associated with display
 *
 */
/**
 *
 * @class
 * @extends {Event}
 */
window.DisplayEvent = PacaClass('DisplayEvent', Event); (function(){ var public = DisplayEvent.prototype;

    DisplayEvent.TEMPLATE_RENDERED = "TEMPLATE_RENDERED";
    DisplayEvent.ADDED_TO_CONTAINER = "ADDED_TO_CONTAINER";

    /** @lends DisplayEvent */

    /**
     * @constructor
     * @param eventName {String}
     * @param eventTarget {Object}
     */
    public.constructor = function(eventName, eventTarget) {
        this.getSuper(Event).constructor.call(this, eventName);
        this.target = eventTarget;
    }

})();

/***************************
 *  PageEvent
 *      El único evento que necesita el game controller (classe Citroen):
 *
 */
window.PageEvent = PacaClass('PageEvent', Event); (function(){ var public = PageEvent.prototype;

    PageEvent.PAGE_EVENT = "PAGE_EVENT";

    public.constructor = function(pageName, effect, data) {
        this.getSuper(Event).constructor.call(this, PageEvent.PAGE_EVENT);
        this.pageName = pageName;
        this.effect = effect;
        this.data = data;
    }

})();

/*********************************************
 *
 * @DisplayObject(template_selector, [directives])
 * Basically, it is just an alternate signature for EventDispatcher used to certificate calls to DisplayObjectContainer's addChild
 *
 * events:
 *      DisplayEvent.ADDED_TO_CONTAINER
 *          triggered when the display object gets added to a DisplayObjectContainer
 *
 */
window.DisplayObject = PacaClass('DisplayObject', EventDispatcher); (function () { var public = DisplayObject.prototype;

    public.node;

    public.constructor = function(){
        this.getSuper(EventDispatcher).constructor.call(this);
    }

})();

/*********************************************
 *
 * @DisplayObjectContainer(template_selector, [directives])
 * A class that has contentNode attribute set to a jquery object that allows us to add childs to it.
 *
 * methods:
 *      addChild(child): add given child to this.contentNode
 *      clear(): removes all childs
 *      TODO: addChildAt? getChildIndex? prependChild? numChildren? etc
 *
 * USAGE:
 *      you have to fill [Template instance].data before the template gets added to a DisplayObjectContainer.
 *
 */
window.DisplayObjectContainer = PacaClass('DisplayObjectContainer'); (function() { var public = DisplayObjectContainer.prototype;

    public.children = [];

    public.constructor = function(){
        // Empty constructor
    }

    public.addChild = function(child, effect) {

        if (!child.isInstance(DisplayObject)) {
            throw new Error("DisplayObjectContainer.appendChild: child must be a DisplayObject instance.");
        }
        if (!this.contentNode) {
            throw new Error("DisplayObjectContainer.appendChild: this.contentNode must be set to a jquery object.");
        }
        var node;
        if (child.isInstance(Template)) {
            node = child.render();
        } else {
            node = child.node;
        }

        if (effect == "right") {
            node.css('left', '-64em');
        } else if (effect == "fade") {
            node.css('opacity', 0);
        } else {
            // TODO: Así el efecto queda más chulo, pero habría que poder definir independiente el efecto de entrada y el de salida
            node.css('opacity', 0);
            //node.css('left', '64em');
        }
        this.contentNode.append(node);
        setTimeout(function(){
            node.css({
                'left':'0',
                'opacity':'1'
            });
        },0);

        this.children.push(child);

        child.dispatchEvent(new DisplayEvent(DisplayEvent.ADDED_TO_CONTAINER, child));

    };

    public.clear = function(effect) {
        for (var i = 0; i < this.children.length; i++) {
            this.children[i].destroy();
        }
        this.contentNode.children().each(function(){

            var jthis = $(this);

            // Hacemos que no se note si hemos scrolado
            var scrollTop = $(window).scrollTop();
            if (scrollTop) {
                jthis.css('top', Citroen.instance.toEms(-scrollTop) + "em");
                $(window).scrollTop(0);
            }

            if (effect == "right") {
                jthis.css({
                    'left':'64em'
                });
            } else {
                jthis.css({
                    'left':'-64em'
                });
            }

            setTimeout(
                delegate(function(){
                    $(this).remove();
                }, this),
                550
            );

        });
        this.children = [];
        //this.contentNode.empty();
    };

})();

/*********************************************
 *
 * @DomObject(selector, [content_selector])
 * Representation of an element of the dom
 *
 * arguments:
 *      selector: selector for the dom element to associate to
 *      content_selector: optional. target for addChild calls. allows us to handle complex structures in a simpler way.
 *
 */
window.DomObject = PacaClass('DomObject', DisplayObject, DisplayObjectContainer); (function() { var public = DomObject.prototype;

    public.constructor = function(selector, content_selector) {

        this.getSuper(DisplayObject).constructor.call(this);

        if (!selector) {
            throw new Error("DomElement.constructor: a jquery selector must be given")
        }
        this.node = $(selector);

        if (content_selector) {
            this.contentNode = $(content_selector);
        } else {
            this.contentNode = this.node;
        }

    }

})();

///*********************************************
// *
// * @class Template
// * @inherits DisplayObject, DisplayObjectContainer
// * (template_selector, [directives])
// * Wrapper for pure templates.
// *
// * arguments:
// *      template_selector: uses the selector target as a template
// *      content_selector: optional. directives to feed the pure template
// *
// * events:
// *      DisplayEvent.TEMPLATE_RENDERED
// *          This is a good moment associate jquery events to the content.
// *          [DisplayEvent instance].target points to the jquery node to be added
// *
// * USAGE:
// *      you have to fill [Template instance].data before the template gets added to a DisplayObjectContainer.
// *
// */
//window.Template = PacaClass('Template', DisplayObject, DisplayObjectContainer); (function() { var public = Template.prototype;
//
//    // Set this if you want to feed the pure template
//    public.data = null;
//    public.renderedNode;
//
//    public.constructor = function (template_selector, directives) {
//
//        this.getSuper(DisplayObject).constructor.call(this);
//        this.directives = directives;
//
//        var templateNode;
//        try {
//            templateNode = $(template_selector).clone(true, true);
//        } catch (e) {
//            throw new Error("No se encuentra el selector '" + template_selector + "'");
//        }
//        if (templateNode.length == 0) {
//            throw new Error("Template.constructor: template_selector did not match any dom element -> " + template_selector);
//        }
//        templateNode.remove();
//        this.templateNode = templateNode;
//
//        if (arguments.length > 2) {
//            this.contentNode = $(arguments[2]);
//        } else {
//            this.contentNode = this.node;
//        }
//
//    }
//
//    public.render = function() {
//        //var copy = $(this.template_html);
//        var rendered = this.templateNode.clone(true, true);
//        rendered = rendered.directives(this.directives).render(this.data);
//        rendered.data('templateInstance', this);
//        this.renderedNode = rendered;
//        this.dispatchEvent(new DisplayEvent(DisplayEvent.TEMPLATE_RENDERED, rendered));
//        return rendered;
//    }
//
//})();

///**
// * @class Page
// * @inherits Template
// * Template subclass that accepts the data attribute in the constructor.
// */
//window.Page = PacaClass('Page', Template); (function(){ var public = Page.prototype;
//
//    /**
//     * @constructor Page
//     * Creates a new Page
//     * @parent Page}
//     * @param {String} template_selector    see template
//     * @param {Object} directives           see template
//     * @param {Object} data
//     */
//    public.constructor = function(template_selector, directives, data) {
//        this.getSuper(Template).constructor.call(this, template_selector, directives);
//        this.data = data;
//    }
//
//})();
//
//
///***************************
// *
// * @ScalableLayout(target_width)
// *  Layout to help with scalable sites (for mobiles) working with ems.
// *
// *  arguments:
// *      target_width (in pixels)
// *          - makes 1em = 100px
// *
// */
//window.ScalableLayout = PacaClass(); ('ScalableLayout', function() { var public = ScalableLayout.prototype;
//
//    // Private static
//    var _target_width;
//    public.scaleRatio;
//
//    public.resize = function () {
//        this.scaleRatio = $('body').width() / _target_width;
//        $('body').css('font-size', this.scaleRatio + 'px');
//    };
//
//    public.toEms = function (value) {
//        return value / this.scaleRatio / 10;
//    }
//    public.toPixels = function (value) {
//        return value * this.scaleRatio * 10;
//    }
//
//    public.constructor = function(target_width) {
//        if (document.readyState !== 'loaded' && document.readyState !== 'complete' && document.readyState !== 'interactive') {
//            throw new Error("ScalableLayout.constructor: document is not ready. Defer ScalableLayout instantiation");
//        }
//        if (!target_width) {
//            throw new Error("ScalableLayout.constructor: must specify a target width");
//        }
//        _target_width = target_width;
//        $(window).resize(delegate(this.resize, this));
//        this.resize();
//        this.resize(); // A second resize call is needed the first time...
//    }
//
//})();
//
//
//window.Pages = PacaClass(); (function(){ var public = Pages.constructor;
//
//    /**
//     * Page list
//     * @static
//     * @type {Object}
//     */
//    Pages.pages = {}
//
//
//    public.constructor = function() {
//
//        throw new Error("Pages class only has static methods");
//
//    }
//
//    /**
//     * @static
//     * @type void
//     * @param name {String} page name
//     * @param _class {Page} page class
//     * @param data {Object} page parameters
//     * @type {String}
//     */
//    Pages.add = function(name, _class, parameters) {
//
//        if (Pages.pages[name]) {
//            throw new Error("Page '" + name + "' already declared.");
//        }
//
//        parameters["name"] = name;
//        parameters["class"] = _class;
//        Pages.pages[name] = parameters;
//
//        return name;
//
//    }
//
//    /**
//     * get a page by name
//     * @param name {String} page regisitered with Pages.add
//     * @param [additionalData] {Object} Data to pass/override to/from the registered page
//     * @return {Object}
//     */
//    Pages.get = function(name, additionalData) {
//        var resp = Pages.pages[name];
//        if (!resp) {
//            throw new Error("Page '" + name + "' not declared.");
//        }
//        resp = Utils.oSum(resp, additionalData);
//        return resp;
//    }
//
//})();
//
//
window.DeviceSetup = PacaClass('DeviceSetup'); (function(){ var public = DeviceSetup.prototype;

    DeviceSetup.dragStartEvent;
    DeviceSetup.moveEvent;
    DeviceSetup.dragEndEvent;

    /**
     * Initializes device setup
     * @param [isMobile] {Boolean}
     */
    DeviceSetup.initialize = function(isMobile) {
        if (isMobile) {
            DeviceSetup.dragStartEvent = "touchstart";
            DeviceSetup.moveEvent = "touchmove";
            DeviceSetup.dragEndEvent = "touchend";
        } else {
            DeviceSetup.dragStartEvent = "mousedown";
            DeviceSetup.moveEvent = "mousemove";
            DeviceSetup.dragEndEvent = "mouseup";
        }
    }

})();
//
//
///*********************************************
// *
// * @DisplayObject(template_selector, [directives])
// * Basically, it is just an alternate signature for EventDispatcher used to certificate calls to DisplayObjectContainer's addChild
// *
// * events:
// *      DisplayEvent.ADDED_TO_CONTAINER
// *          triggered when the display object gets added to a DisplayObjectContainer
// *
// */
//window.NativeDisplayObject = PacaClass('NativeDisplayObject', EventDispatcher);
//(function () {
//    var public = NativeDisplayObject.prototype;
//
//    public.node;
//
//    public.constructor = function (node) {
//        this.getSuper(EventDispatcher).constructor.call(this);
//    }
//
//})();
//
//
//window.NativeDisplayObjectContainer = PacaClass('NativeDisplayObjectContainer');
//(function () {
//    var public = NativeDisplayObjectContainer.prototype;
//
//    public.children = [];
//
//    public.constructor = function () {
//        // Empty constructor
//    }
//
//    public.addChild = function (child) {
//
//        if (!child.isInstance(NativeDisplayObject)) {
//            throw new Error("NativeDisplayObjectContainer.appendChild: child must be a NativeDisplayObject instance.");
//        }
//        if (!this.contentNode) {
//            throw new Error("NativeDisplayObjectContainer.appendChild: this.contentNode must be set to a dom object.");
//        }
//
//        this.contentNode.appendChild(child.node);
//        this.children.push(child);
//
//        child.dispatchEvent(new DisplayEvent(DisplayEvent.ADDED_TO_CONTAINER, child));
//    };
//
//    public.clear = function (effect) {
//        for (var i = 0; i < this.children.length; i++) {
//            var child = this.children[i];
//            this.contentNode.removeChild(child.node)
//            child.destroy();
//        }
//        this.children = [];
//    };
//
//})();
//
//window.NativeDomObject = PacaClass('NativeDomObject', NativeDisplayObject, NativeDisplayObjectContainer);
//(function () {
//    var public = NativeDomObject.prototype;
//
//    public.constructor = function (node, content_node) {
//
//        this.getSuper(NativeDisplayObject).constructor.call(this);
//
//        if (!node) {
//            throw new Error("NativeDomObject.constructor: a dom object must be given")
//        }
//        this.node = node;
//
//        if (content_node) {
//            this.contentNode = content_node;
//        } else {
//            this.contentNode = this.node;
//        }
//
//    }
//
//})();<commit_msg>remove too dirty lib<commit_after><|endoftext|>


<commit_before>const Kafka = require('no-kafka');
const Loki = require('lokijs');
const objectid = require('objectid')
const RxCollection = require('./rx-collection');

const consumer = new Kafka.SimpleConsumer();

const adapter = new Loki.LokiMemoryAdapter;
const db = new Loki('test', {
  adapter,
});

const items = db.addCollection('items');

// var mydv = items.addDynamicView('test');  // default is non-persistent
// mydv.applyFind({ _id: { $gt: 10 } });
// mydv.on('rebuild', (ev) => {
//   var results = mydv.data();
//   // console.log({ ev, rs: ev.resultset, results });
//   console.log(results);
// });

const rxItems = new RxCollection(items);

rxItems.find({ _id: { $gte: 10 } })
  .subscribe(result => console.log(result))
;

// items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' });

// data handler function can return a Promise
var dataHandler = function (messageSet, topic, partition) {
  messageSet.forEach(function (m) {
    const { op, value } = JSON.parse(m.message.value.toString('utf8'));

    switch (op) {
      case 'insert': {
        items.insert(value);
        break
      }
      case 'update': {
        const [filter, update] = value;
        items.findAndUpdate(
          filter,
          (doc) => Object.assign(doc, update)
        );
        break
      }
      case 'remove': {
        items.findAndRemove(value);
        break
      }
    }
    // console.log(topic, partition, m.offset, m.message.value.toString('utf8'));
    console.log(op, value);
  });
};

consumer
  .init()
  .then(() => consumer.subscribe(
    'kafka-test-topic',
    [0, 1],
    dataHandler
  ))
;
<commit_msg>less verbose consumer<commit_after>const Kafka = require('no-kafka');
const Loki = require('lokijs');
const objectid = require('objectid')
const RxCollection = require('./rx-collection');

const consumer = new Kafka.SimpleConsumer();

const adapter = new Loki.LokiMemoryAdapter;
const db = new Loki('test', {
  adapter,
});

const items = db.addCollection('items');

// var mydv = items.addDynamicView('test');  // default is non-persistent
// mydv.applyFind({ _id: { $gt: 10 } });
// mydv.on('rebuild', (ev) => {
//   var results = mydv.data();
//   // console.log({ ev, rs: ev.resultset, results });
//   console.log(results);
// });

const rxItems = new RxCollection(items);

rxItems.find({ _id: { $gte: 10 } })
  .subscribe(result => console.log(result))
;

// items.insert({ name : 'mjolnir', owner: 'thor', maker: 'dwarves' });

// data handler function can return a Promise
var dataHandler = function (messageSet, topic, partition) {
  messageSet.forEach(function (m) {
    const { op, value } = JSON.parse(m.message.value.toString('utf8'));

    switch (op) {
      case 'insert': {
        items.insert(value);
        break
      }
      case 'update': {
        const [filter, update] = value;
        items.findAndUpdate(
          filter,
          (doc) => Object.assign(doc, update)
        );
        break
      }
      case 'remove': {
        items.findAndRemove(value);
        break
      }
    }
    // console.log(topic, partition, m.offset, m.message.value.toString('utf8'));
    // console.log(op, value);
  });
};

consumer
  .init()
  .then(() => consumer.subscribe(
    'kafka-test-topic',
    [0],
    dataHandler
  ))
;
<|endoftext|>