<commit_before>'use strict';

(function() {
	var cnpjPattern = new StringMask('00.000.000\/0000-00');
	var cpfPattern = new StringMask('000.000.000-00');

	function validateCPF (ctrl, value) {
		var valid = ctrl.$isEmpty(value) || BrV.cpf.validate(value);
		ctrl.$setValidity('cpf', valid);
		return value;
	}

	function validateCNPJ (ctrl, value) {
		var valid = ctrl.$isEmpty(value) || BrV.cnpj.validate(value);
		ctrl.$setValidity('cnpj', valid);
		return value;
	}

	function validateCPForCNPJ (ctrl, value) {
		if(!value || value.length <= 11) {
			validateCNPJ(ctrl, '');
			return validateCPF(ctrl, value);
		}else {
			validateCPF(ctrl, '');
			return validateCNPJ(ctrl, value);
		}
	}

	function uiBrCpfMask() {
		function applyCpfMask (value) {
			if(!value) {
				return value;
			}
			var formatedValue = cpfPattern.apply(value);
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}

		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					return applyCpfMask(validateCPF(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if(!value) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]/g,'');
					var formatedValue = applyCpfMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g,'');
				});

				ctrl.$parsers.push(function(value) {
					return validateCPF(ctrl, value);
				});
			}
		};
	}

	function uiBrCnpjMask() {
		function applyCnpjMask (value) {
			if(!value) {
				return value;
			}
			var formatedValue = cnpjPattern.apply(value);
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}
		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					return applyCnpjMask(validateCNPJ(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if(!value) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]+/g,'');
					var formatedValue = applyCnpjMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g,'');
				});

				ctrl.$parsers.push(function(value) {
					return validateCNPJ(ctrl, value);
				});
			}
		};
	}

	function uiBrCpfCnpjMask() {
		function applyCpfCnpjMask (value) {
			if(!value) {
				return value;
			}
			var formatedValue;
			if (value.length > 11) {
				formatedValue = cnpjPattern.apply(value);
			} else {
				formatedValue = cpfPattern.apply(value);
			}
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}
		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					return applyCpfCnpjMask(validateCPForCNPJ(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if(!value) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]+/g,'');
					var formatedValue = applyCpfCnpjMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g,'');
				});

				ctrl.$parsers.push(function(value) {
					return validateCPForCNPJ(ctrl, value);
				});
			}
		};
	}

	angular.module('ui.utils.masks.br.cpfCnpj', [])
	.directive('uiBrCpfMask', [uiBrCpfMask])
	.directive('uiBrCnpjMask', [uiBrCnpjMask])
	.directive('uiBrCpfcnpjMask', [uiBrCpfCnpjMask])
	// deprecated: will be removed in the next major version
	.directive('uiCpfMask', [uiBrCpfMask])
	// deprecated: will be removed in the next major version
	.directive('uiCnpjMask', [uiBrCnpjMask])
	// deprecated: will be removed in the next major version
	.directive('uiCpfcnpjMask', [uiBrCpfCnpjMask]);
})();
<commit_msg>refactor(ui-br-cpf-mask,ui-br-cnpj-mask,ui-br-cpfcnpj-mask): use ctrl.$isEmpty<commit_after>'use strict';

(function() {
	var cnpjPattern = new StringMask('00.000.000\/0000-00');
	var cpfPattern = new StringMask('000.000.000-00');

	function validateCPF (ctrl, value) {
		var valid = ctrl.$isEmpty(value) || BrV.cpf.validate(value);
		ctrl.$setValidity('cpf', valid);
		return value;
	}

	function validateCNPJ (ctrl, value) {
		var valid = ctrl.$isEmpty(value) || BrV.cnpj.validate(value);
		ctrl.$setValidity('cnpj', valid);
		return value;
	}

	function validateCPForCNPJ (ctrl, value) {
		if(!value || value.length <= 11) {
			validateCNPJ(ctrl, '');
			return validateCPF(ctrl, value);
		}else {
			validateCPF(ctrl, '');
			return validateCNPJ(ctrl, value);
		}
	}

	function uiBrCpfMask() {
		function applyCpfMask (value) {
			var formatedValue = cpfPattern.apply(value);
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}

		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					return applyCpfMask(validateCPF(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]/g,'');
					var formatedValue = applyCpfMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g,'');
				});

				ctrl.$parsers.push(function(value) {
					return validateCPF(ctrl, value);
				});
			}
		};
	}

	function uiBrCnpjMask() {
		function applyCnpjMask (value) {
			var formatedValue = cnpjPattern.apply(value);
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}

		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					return applyCnpjMask(validateCNPJ(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]+/g, '');
					var formatedValue = applyCnpjMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g, '');
				});

				ctrl.$parsers.push(function(value) {
					return validateCNPJ(ctrl, value);
				});
			}
		};
	}

	function uiBrCpfCnpjMask() {
		function applyCpfCnpjMask (value) {
			var formatedValue;
			if (value.length > 11) {
				formatedValue = cnpjPattern.apply(value);
			} else {
				formatedValue = cpfPattern.apply(value);
			}
			return formatedValue.trim().replace(/[^0-9]$/, '');
		}

		return {
			restrict: 'A',
			require: 'ngModel',
			link: function (scope, element, attrs, ctrl) {
				ctrl.$formatters.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					return applyCpfCnpjMask(validateCPForCNPJ(ctrl, value));
				});

				ctrl.$parsers.push(function(value) {
					if (ctrl.$isEmpty(value)) {
						return value;
					}

					var actualNumber = value.replace(/[^\d]+/g, '');
					var formatedValue = applyCpfCnpjMask(actualNumber);

					if (ctrl.$viewValue !== formatedValue) {
						ctrl.$setViewValue(formatedValue);
						ctrl.$render();
					}

					return formatedValue.replace(/[^\d]+/g, '');
				});

				ctrl.$parsers.push(function(value) {
					return validateCPForCNPJ(ctrl, value);
				});
			}
		};
	}

	angular.module('ui.utils.masks.br.cpfCnpj', [])
	.directive('uiBrCpfMask', [uiBrCpfMask])
	.directive('uiBrCnpjMask', [uiBrCnpjMask])
	.directive('uiBrCpfcnpjMask', [uiBrCpfCnpjMask])
	// deprecated: will be removed in the next major version
	.directive('uiCpfMask', [uiBrCpfMask])
	// deprecated: will be removed in the next major version
	.directive('uiCnpjMask', [uiBrCnpjMask])
	// deprecated: will be removed in the next major version
	.directive('uiCpfcnpjMask', [uiBrCpfCnpjMask]);
})();
<|endoftext|>


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

  const ADIDAS_URL = 'https://www.adidas.com';
  const NIKE_URL = 'https://www.nike.com';

  const LEFT = 'left';
  const CENTER = 'center';
  const RIGHT = 'right';

  let adidas = document.querySelector('#adidas');
  let nike = document.querySelector('#nike');

  document.addEventListener('keydown', event => {
    if (event.keyCode === 39 /* right */) {
      if (nike.className === 'center') {
        return;
      }
      adidas.className = 'left';
      nike.className = 'center';
      updateCurrentAdvertisement(NIKE_URL);
      return;
    }
    if (event.keyCode === 37 /* left */) {
      if (adidas.className === 'center') {
        return;
      }
      nike.className = 'right';
      adidas.className = 'center';
      updateCurrentAdvertisement(ADIDAS_URL);
      return;
    }
  });

  let current_adv;
  let updateCurrentAdvertisement = (newURL) => {
    let new_adv = {
      type: 'url',
      url: newURL,
      advertisedTxPower: -100
    };
    if (eddystone.advertisements.length === 0) {
      eddystone.registerAdvertisement(new_adv)
        .then(adv => current_adv = adv);
      return;
    }
    current_adv.unregisterAdvertisment()
      .then(() => eddystone.registerAdvertisement(new_adv))
      .then(adv => current_adv = adv);
  };

  updateCurrentAdvertisement(ADIDAS_URL);
})();
<commit_msg>Fix typoe<commit_after>(() => {
  'use strict';

  const ADIDAS_URL = 'https://www.adidas.com';
  const NIKE_URL = 'https://www.nike.com';

  const LEFT = 'left';
  const CENTER = 'center';
  const RIGHT = 'right';

  let adidas = document.querySelector('#adidas');
  let nike = document.querySelector('#nike');

  document.addEventListener('keydown', event => {
    if (event.keyCode === 39 /* right */) {
      if (nike.className === 'center') {
        return;
      }
      adidas.className = 'left';
      nike.className = 'center';
      updateCurrentAdvertisement(NIKE_URL);
      return;
    }
    if (event.keyCode === 37 /* left */) {
      if (adidas.className === 'center') {
        return;
      }
      nike.className = 'right';
      adidas.className = 'center';
      updateCurrentAdvertisement(ADIDAS_URL);
      return;
    }
  });

  let current_adv;
  let updateCurrentAdvertisement = (newURL) => {
    let new_adv = {
      type: 'url',
      url: newURL,
      advertisedTxPower: -100
    };
    if (eddystone.advertisements.length === 0) {
      eddystone.registerAdvertisement(new_adv)
        .then(adv => current_adv = adv);
      return;
    }
    current_adv.unregisterAdvertisement()
      .then(() => eddystone.registerAdvertisement(new_adv))
      .then(adv => current_adv = adv);
  };

  updateCurrentAdvertisement(ADIDAS_URL);
})();
<|endoftext|>


<commit_before>'use strict';

var utils = require('../../../util/utils');
var NetworkClient = require('./networkClient');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var network = cli.category('network')
      .description($('Commands to manage your network resources'));

  var loadbalancer = network.category('loadbalancer')
      .description($('Commands to manage your load balancers'));

  loadbalancer.command('list [resourceGroup]')
    .description($('Lists the load balancers within a resource group'))
    .usage('[options] <resourceGroup>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.listLoadBalancers(resourceGroup, options, _);
    });

  loadbalancer.command('show [resourceGroup] [name]')
    .description($('Gets one load balancer within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the load balancer name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Load balancer name: '), name, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.showLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('delete [resourceGroup] [name]')
    .description($('Deletes one load balancer within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the load balancer name'))
    .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Load balancer name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.deleteLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('export <resourceGroup> <name> [file-path]')
    .usage('[options] <resourceGroup> <name> <file-path>')
    .description($('Exports the load balancer configuration to a file'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, filepath, options, _) {
      options.filepath = cli.interaction.promptIfNotGiven($('File path: '), filepath, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.exportLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('import <resourceGroup> <name> [file-path]')
    .usage('[options] <resourceGroup> <name> <file-path>')
    .description($('Imports the load balancer configuration from a file'))
    .option('-s, --subscription <id>', $('the subscription id'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, filepath, options, _) {
      options.filepath = cli.interaction.promptIfNotGiven($('File path: '), filepath, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.importLoadBalancer(resourceGroup, name, options, _);
    });

  var publicip = network.category('publicip')
      .description($('Commands to manage your public IP addresses'));

  publicip.command('create <resourceGroup> <name>')
      .description($('Creates a public ip address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-l, --location <location>', $('the location'))
      .option('-n, --domain-name <domainName>', $('the public ip domain name, this set DNS to <domain-name>.<location>.cloudapp.azure.com'))
      .option('-m, --allocation-method <allocationmethod>', $('the public ip allocation method, valid values are "Dynamic"'))
      .option('-t, --idletimeout <idletimeout>', $('the public ip idle timeout'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        options.location = cli.interaction.promptIfNotGiven($('Location: '), options.location, _);
        options.domainName = cli.interaction.promptIfNotGiven($('Domain name: '), options.domainName, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.createPublicIP(resourceGroup, name, options, _);
      });

  publicip.command('show [resourceGroup] [name]')
      .description($('Gets one public address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('-n, --name <name>', $('the virtual machine name'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        name = cli.interaction.promptIfNotGiven($('Public ip address name: '), name, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.showPublicIP(resourceGroup, name, options, _);
      });

  publicip.command('delete [resourceGroup] [name]')
      .description($('Deletes one public address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('-n, --name <name>', $('the virtual machine name'))
      .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        name = cli.interaction.promptIfNotGiven($('Public ip address name: '), name, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.deletePublicIP(resourceGroup, name, options, _);
      });

  publicip.command('list [resourceGroup]')
      .description($('Lists the public ip addresses within a resource group'))
      .usage('[options] <resourceGroup>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.listPublicIPs(resourceGroup, options, _);
      });

  var nic = network.category('nic')
    .description($('Commands to manage your NIC'));

  nic.command('create <resourceGroup> <name>')
    .description($('Creates a network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-l, --location <location>', $('the location'))
    .option('-p, --ip-name <ipname>', $('the name of ip address'))
    .option('-t, --subnet-id <subnetid>', $('the subnet id'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      options.location = cli.interaction.promptIfNotGiven($('Location: '), options.location, _);
      options.ipAddressName = cli.interaction.promptIfNotGiven($('IP Address name: '), options.ipAddressName, _);
      options.subnetId = cli.interaction.promptIfNotGiven($('Subnet ID: '), options.subnetId, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.createNIC(resourceGroup, name, options, _);
    });

  nic.command('list [resourceGroup]')
    .description($('Lists the network interfaces within a resource group'))
    .usage('[options] <resourceGroup>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.listNICs(resourceGroup, options, _);
    });

  nic.command('show [resourceGroup] [name]')
    .description($('Gets one network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resourc-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the network interface name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Network interface name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.showNIC(resourceGroup, name, options, _);
    });

  nic.command('delete [resourceGroup] [name]')
    .description($('Deletes one network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the virtual machine name'))
    .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Network interface name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.deleteNIC(resourceGroup, name, options, _);
    });

};<commit_msg>'nic show' typo fixed<commit_after>'use strict';

var utils = require('../../../util/utils');
var NetworkClient = require('./networkClient');
var $ = utils.getLocaleString;

exports.init = function (cli) {
  var network = cli.category('network')
      .description($('Commands to manage your network resources'));

  var loadbalancer = network.category('loadbalancer')
      .description($('Commands to manage your load balancers'));

  loadbalancer.command('list [resourceGroup]')
    .description($('Lists the load balancers within a resource group'))
    .usage('[options] <resourceGroup>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.listLoadBalancers(resourceGroup, options, _);
    });

  loadbalancer.command('show [resourceGroup] [name]')
    .description($('Gets one load balancer within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the load balancer name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Load balancer name: '), name, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.showLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('delete [resourceGroup] [name]')
    .description($('Deletes one load balancer within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the load balancer name'))
    .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Load balancer name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.deleteLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('export <resourceGroup> <name> [file-path]')
    .usage('[options] <resourceGroup> <name> <file-path>')
    .description($('Exports the load balancer configuration to a file'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, filepath, options, _) {
      options.filepath = cli.interaction.promptIfNotGiven($('File path: '), filepath, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.exportLoadBalancer(resourceGroup, name, options, _);
    });

  loadbalancer.command('import <resourceGroup> <name> [file-path]')
    .usage('[options] <resourceGroup> <name> <file-path>')
    .description($('Imports the load balancer configuration from a file'))
    .option('-s, --subscription <id>', $('the subscription id'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, filepath, options, _) {
      options.filepath = cli.interaction.promptIfNotGiven($('File path: '), filepath, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.importLoadBalancer(resourceGroup, name, options, _);
    });

  var publicip = network.category('publicip')
      .description($('Commands to manage your public IP addresses'));

  publicip.command('create <resourceGroup> <name>')
      .description($('Creates a public ip address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-l, --location <location>', $('the location'))
      .option('-n, --domain-name <domainName>', $('the public ip domain name, this set DNS to <domain-name>.<location>.cloudapp.azure.com'))
      .option('-m, --allocation-method <allocationmethod>', $('the public ip allocation method, valid values are "Dynamic"'))
      .option('-t, --idletimeout <idletimeout>', $('the public ip idle timeout'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        options.location = cli.interaction.promptIfNotGiven($('Location: '), options.location, _);
        options.domainName = cli.interaction.promptIfNotGiven($('Domain name: '), options.domainName, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.createPublicIP(resourceGroup, name, options, _);
      });

  publicip.command('show [resourceGroup] [name]')
      .description($('Gets one public address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('-n, --name <name>', $('the virtual machine name'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        name = cli.interaction.promptIfNotGiven($('Public ip address name: '), name, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.showPublicIP(resourceGroup, name, options, _);
      });

  publicip.command('delete [resourceGroup] [name]')
      .description($('Deletes one public address within a resource group'))
      .usage('[options] <resourceGroup> <name>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('-n, --name <name>', $('the virtual machine name'))
      .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, name, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        name = cli.interaction.promptIfNotGiven($('Public ip address name: '), name, _);

        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.deletePublicIP(resourceGroup, name, options, _);
      });

  publicip.command('list [resourceGroup]')
      .description($('Lists the public ip addresses within a resource group'))
      .usage('[options] <resourceGroup>')
      .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
      .option('--subscription <subscription>', $('the subscription identifier'))
      .execute(function (resourceGroup, options, _) {
        resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
        var networkClient = new NetworkClient(cli, options.subscription);
        networkClient.listPublicIPs(resourceGroup, options, _);
      });

  var nic = network.category('nic')
    .description($('Commands to manage your NIC'));

  nic.command('create <resourceGroup> <name>')
    .description($('Creates a network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-l, --location <location>', $('the location'))
    .option('-p, --ip-name <ipname>', $('the name of ip address'))
    .option('-t, --subnet-id <subnetid>', $('the subnet id'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      options.location = cli.interaction.promptIfNotGiven($('Location: '), options.location, _);
      options.ipAddressName = cli.interaction.promptIfNotGiven($('IP Address name: '), options.ipAddressName, _);
      options.subnetId = cli.interaction.promptIfNotGiven($('Subnet ID: '), options.subnetId, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.createNIC(resourceGroup, name, options, _);
    });

  nic.command('list [resourceGroup]')
    .description($('Lists the network interfaces within a resource group'))
    .usage('[options] <resourceGroup>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.listNICs(resourceGroup, options, _);
    });

  nic.command('show [resourceGroup] [name]')
    .description($('Gets one network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the network interface name'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Network interface name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.showNIC(resourceGroup, name, options, _);
    });

  nic.command('delete [resourceGroup] [name]')
    .description($('Deletes one network interface within a resource group'))
    .usage('[options] <resourceGroup> <name>')
    .option('-g, --resource-group <resourceGroup>', $('the resource group name'))
    .option('-n, --name <name>', $('the virtual machine name'))
    .option('-q, --quiet', $('quiet mode, do not ask for delete confirmation'))
    .option('--subscription <subscription>', $('the subscription identifier'))
    .execute(function (resourceGroup, name, options, _) {
      resourceGroup = cli.interaction.promptIfNotGiven($('Resource group name: '), resourceGroup, _);
      name = cli.interaction.promptIfNotGiven($('Network interface name: '), name, _);

      var networkClient = new NetworkClient(cli, options.subscription);
      networkClient.deleteNIC(resourceGroup, name, options, _);
    });

};<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
;(function(w, $, TweenMax, TimelineLite, Power2, Quad) {
    'use strict';

    var article_height = 820;
    var parallax_offset = 120;
    var phone_offset = 200; // distance from top of article to top of phone

    // i heard document.ready isn't necessary anymore. just trying it out...
    //$(document).ready(function () {
        // set up foxtail sprite animation
        $('#foxtail').sprite({fps: 12, no_of_frames: 44, rewind: true});

        // Smooth scroll-to for left menu navigation
        $('#partner-nav a[class!="no-scroll"], #nav-main-menu a').click(function(e) {
            var elementClicked = $(this).attr("href");
            var destination;

            // all <article>'s have set height and position
            switch (elementClicked) {
                case '#overview':
                    destination = 0;
                    break;
                case '#os':
                    destination = (article_height - parallax_offset);
                    break;
                case '#marketplace':
                    destination = ((article_height * 2) - (parallax_offset * 2));
                    break;
                case '#android':
                    destination = ((article_height * 3) - (parallax_offset * 3));
                    break;
            }

            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 700);
            return false;
        });

        // move form out of overlay
        var $form = $('#form').detach();
        $('#article-wrapper').after($form);

        // activate form drawer
        $('#toggle-form').pageslide({
            direction: 'left'
        });

        var $giantfox = $('#giantfox');
        var $giantfox_tail = $('#giantfox-foreground');
        var $phone = $('#phone-common');
        var $phone_android = $('#phone-android');
        var $overview = $('#overview');
        var $os = $('#os');
        var $marketplace = $('#marketplace');
        var $android = $('#android');

        // side scrolling sections
        $('.view-section').on('click', function(e) {
            e.preventDefault();

            // needed to calculate percentage offsets?
            var doc_width = $(w.document).width();

            var link = $(this);

            var article = link.parents('article:first');

            // which section is currently displayed?
            var orig = article.find('section[data-current="1"]:first');
            var orig_pos = Number(orig.data('pos'));

            // which section are we going to?
            var dest = $('#' + link.data('section'));
            var dest_pos = Number(dest.data('pos'));

            // what's the difference in position? multiply by 100 to get percentage
            var delta = (dest_pos - orig_pos) * 100;

            article.find('section').each(function(i, el) {
                var section = $(el);

                // percentage position of this section
                // (left will be in px and will be multiple of doc_width)
                var el_left = (section.position().left/doc_width) * 100;

                var new_left = el_left - delta;

                section.css('left', new_left + '%').attr('data-current', 0);
            });

            // update current section
            dest.attr('data-current', 1);

            // slide phone?
            if (dest_pos > 1) {
                $phone.animate({ 'left': '-50%' }, 500);
            } else {
                $phone.animate({ 'left': '50%' }, 500);
            }
        });

        $('a[data-section="os-operators"]').on('click', function() {
            $giantfox.css('left', '-45%');
        });

        $('a[data-section="os-overview"]').on('click', function() {
            $giantfox.css('left', '45%');
        });

        var _move_phone = function(factor, slide, new_z) {
            var cur_left = $phone.position().left;
            var doc_width = $(w.document).width();

            // when jumping more than one section with nav, phone may
            // not make it all the way to -50%
            // if phone is less than halfway across current viewport,
            // assume it's not visible
            var visible = (cur_left >= (doc_width/2));

            var top_pos = ((article_height * factor) - (parallax_offset * factor)) + phone_offset;

            // would like to abstract this more, but each scenario requires specific sequencing
            if (Number(slide.find('section:first').attr('data-current')) === 1) {
                if (!visible) {
                    if (new_z) {
                        $phone.css('z-index', new_z);
                    }

                    $phone.animate({
                        top: top_pos
                    }, 100, function() {
                        $phone.animate({ 'left': '50%' }, 500);
                    });
                } else {
                    $phone.animate({ 'top': top_pos + 'px' }, 500, function() {
                        if (new_z) {
                            $phone.css('z-index', new_z);
                        }
                    });
                }
            } else {
                if (visible) {
                    $phone.animate({
                        'left': '-50%'
                    }, 500, function() {
                        $phone.css('top', top_pos + 'px');

                        if (new_z) {
                            $phone.css('z-index', new_z);
                        }
                    });
                } else {
                    if (new_z) {
                        $phone.css('z-index', new_z);
                    }

                    $phone.animate({ 'top': top_pos + 'px' }, 500);
                }
            }
        };

        var controller = $.superscrollorama();

        var tweens = {};

        tweens.slide_up = {
            from: {
                css: { top: 120, opacity: 0 },
                immediateRender: true
            },
            to: { css: { top: 0, opacity: 1 } }
        };

        tweens.article_os = {
            from: {
                css: { top: 0, ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-1) },
                onStart: function() {
                    $phone.css('z-index', 110);
                },
                onComplete: function() {
                    _move_phone(1, $os);
                },
                onReverseComplete: function() {
                    _move_phone(0, $overview);
                }
            }
        };

        tweens.article_marketplace = {
            from: {
                css: { top: (parallax_offset*-1), ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-2) },
                onStart: function() {
                    $phone.css('z-index', 120);
                },
                onComplete: function() {
                    _move_phone(2, $marketplace);
                },
                onReverseComplete: function() {
                    _move_phone(1, $os, 110);
                }
            }
        };

        tweens.article_android = {
            from: {
                css: { top: (parallax_offset*-2), ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-3) },
                onComplete: function() {
                    _move_phone(3, $android);
                    $phone_android.addClass('android-phone-visible');
                },
                onReverseComplete: function() {
                    _move_phone(2, $marketplace);
                    $phone_android.removeClass('android-phone-visible');
                }
            }
        };

        var prev_article = '#overview';

        $('.partner-article').each(function(i, article) {
            var $article = $(article);

            var my_tweens = [], tween, $tweener;

            if ($article.attr('id') !== 'overview') {
                tween = TweenMax.fromTo(
                    $article,
                    0.5,
                    tweens['article_' + $article.attr('id')].from,
                    tweens['article_' + $article.attr('id')].to
                );

                my_tweens.push(tween);
            }

            // build tween for each element in $article with class of tween
            $article.find('.tween').each(function(i, tweener) {
                $tweener = $(tweener);

                tween = TweenMax.fromTo(
                    $tweener,
                    0.6,
                    tweens.slide_up.from,
                    tweens.slide_up.to
                );

                my_tweens.push(tween);
            });

            if (my_tweens.length > 0) {
                controller.addTween(
                    prev_article,
                    (new TimelineLite()).append(my_tweens),
                    350, // scroll duration
                    500 // start offset
                );
            }

            if ($article.attr('id') !== 'overview') {
                prev_article = '#' + $article.attr('id');
            }
        });
    //});
})(window, window.jQuery, window.TweenMax, window.TimelineLite, window.Power2, window.Quad);

<commit_msg>Animate Android phone left/right.<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
;(function(w, $, TweenMax, TimelineLite, Power2, Quad) {
    'use strict';

    var article_height = 820;
    var parallax_offset = 120;
    var phone_offset = 200; // distance from top of article to top of phone

    // i heard document.ready isn't necessary anymore. just trying it out...
    //$(document).ready(function () {
        // set up foxtail sprite animation
        $('#foxtail').sprite({fps: 12, no_of_frames: 44, rewind: true});

        // Smooth scroll-to for left menu navigation
        $('#partner-nav a[class!="no-scroll"], #nav-main-menu a').click(function(e) {
            var elementClicked = $(this).attr("href");
            var destination;

            // all <article>'s have set height and position
            switch (elementClicked) {
                case '#overview':
                    destination = 0;
                    break;
                case '#os':
                    destination = (article_height - parallax_offset);
                    break;
                case '#marketplace':
                    destination = ((article_height * 2) - (parallax_offset * 2));
                    break;
                case '#android':
                    destination = ((article_height * 3) - (parallax_offset * 3));
                    break;
            }

            $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 700);
            return false;
        });

        // move form out of overlay
        var $form = $('#form').detach();
        $('#article-wrapper').after($form);

        // activate form drawer
        $('#toggle-form').pageslide({
            direction: 'left'
        });

        var $giantfox = $('#giantfox');
        var $giantfox_tail = $('#giantfox-foreground');
        var $phone = $('#phone-common');
        var $phone_android = $('#phone-android');
        var $overview = $('#overview');
        var $os = $('#os');
        var $marketplace = $('#marketplace');
        var $android = $('#android');

        // side scrolling sections
        $('.view-section').on('click', function(e) {
            e.preventDefault();

            // needed to calculate percentage offsets?
            var doc_width = $(w.document).width();

            var link = $(this);

            var article = link.parents('article:first');

            // which section is currently displayed?
            var orig = article.find('section[data-current="1"]:first');
            var orig_pos = Number(orig.data('pos'));

            // which section are we going to?
            var dest = $('#' + link.data('section'));
            var dest_pos = Number(dest.data('pos'));

            // what's the difference in position? multiply by 100 to get percentage
            var delta = (dest_pos - orig_pos) * 100;

            article.find('section').each(function(i, el) {
                var section = $(el);

                // percentage position of this section
                // (left will be in px and will be multiple of doc_width)
                var el_left = (section.position().left/doc_width) * 100;

                var new_left = el_left - delta;

                section.css('left', new_left + '%').attr('data-current', 0);
            });

            // update current section
            dest.attr('data-current', 1);

            // which phone should we move?
            var $cur_phone = (article.attr('id') === 'android') ? $phone_android : $phone;

            // slide phone?
            if (dest_pos > 1) {
                $cur_phone.animate({ 'left': '-50%' }, 500);
            } else {
                $cur_phone.animate({ 'left': '50%' }, 500);
            }
        });

        $('a[data-section="os-operators"]').on('click', function() {
            $giantfox.css('left', '-45%');
        });

        $('a[data-section="os-overview"]').on('click', function() {
            $giantfox.css('left', '45%');
        });

        var _move_phone = function(factor, slide, new_z) {
            var cur_left = $phone.position().left;
            var doc_width = $(w.document).width();

            // when jumping more than one section with nav, phone may
            // not make it all the way to -50%
            // if phone is less than halfway across current viewport,
            // assume it's not visible
            var visible = (cur_left >= (doc_width/2));

            var top_pos = ((article_height * factor) - (parallax_offset * factor)) + phone_offset;

            // would like to abstract this more, but each scenario requires specific sequencing
            if (slide.attr('id') === 'android') {
                $phone.animate({ 'top': top_pos + 'px' }, 500);
            } else {
                if (Number(slide.find('section:first').attr('data-current')) === 1) {
                    if (!visible) {
                        if (new_z) {
                            $phone.css('z-index', new_z);
                        }

                        $phone.animate({
                            top: top_pos
                        }, 100, function() {
                            $phone.animate({ 'left': '50%' }, 500);
                        });
                    } else {
                        $phone.animate({ 'top': top_pos + 'px' }, 500, function() {
                            if (new_z) {
                                $phone.css('z-index', new_z);
                            }
                        });
                    }
                } else {
                    if (visible) {
                        $phone.animate({
                            'left': '-50%'
                        }, 500, function() {
                            $phone.css('top', top_pos + 'px');

                            if (new_z) {
                                $phone.css('z-index', new_z);
                            }
                        });
                    } else {
                        if (new_z) {
                            $phone.css('z-index', new_z);
                        }

                        $phone.animate({ 'top': top_pos + 'px' }, 500);
                    }
                }
            }
        };

        var controller = $.superscrollorama();

        var tweens = {};

        tweens.slide_up = {
            from: {
                css: { top: 120, opacity: 0 },
                immediateRender: true
            },
            to: { css: { top: 0, opacity: 1 } }
        };

        tweens.article_os = {
            from: {
                css: { top: 0, ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-1) },
                onStart: function() {
                    $phone.css('z-index', 110);
                },
                onComplete: function() {
                    _move_phone(1, $os);
                },
                onReverseComplete: function() {
                    _move_phone(0, $overview);
                }
            }
        };

        tweens.article_marketplace = {
            from: {
                css: { top: (parallax_offset*-1), ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-2) },
                onStart: function() {
                    $phone.css('z-index', 120);
                },
                onComplete: function() {
                    _move_phone(2, $marketplace);
                },
                onReverseComplete: function() {
                    _move_phone(1, $os, 110);
                }
            }
        };

        tweens.article_android = {
            from: {
                css: { top: (parallax_offset*-2), ease: Power2.easeOut },
                immediateRender: true
            },
            to: {
                css: { top: (parallax_offset*-3) },
                onComplete: function() {
                    _move_phone(3, $android);
                    $phone_android.addClass('android-phone-visible');
                },
                onReverseComplete: function() {
                    _move_phone(2, $marketplace);
                    $phone_android.removeClass('android-phone-visible');
                }
            }
        };

        var prev_article = '#overview';

        $('.partner-article').each(function(i, article) {
            var $article = $(article);

            var my_tweens = [], tween, $tweener;

            if ($article.attr('id') !== 'overview') {
                tween = TweenMax.fromTo(
                    $article,
                    0.5,
                    tweens['article_' + $article.attr('id')].from,
                    tweens['article_' + $article.attr('id')].to
                );

                my_tweens.push(tween);
            }

            // build tween for each element in $article with class of tween
            $article.find('.tween').each(function(i, tweener) {
                $tweener = $(tweener);

                tween = TweenMax.fromTo(
                    $tweener,
                    0.6,
                    tweens.slide_up.from,
                    tweens.slide_up.to
                );

                my_tweens.push(tween);
            });

            if (my_tweens.length > 0) {
                controller.addTween(
                    prev_article,
                    (new TimelineLite()).append(my_tweens),
                    350, // scroll duration
                    500 // start offset
                );
            }

            if ($article.attr('id') !== 'overview') {
                prev_article = '#' + $article.attr('id');
            }
        });
    //});
})(window, window.jQuery, window.TweenMax, window.TimelineLite, window.Power2, window.Quad);

<|endoftext|>


<commit_before><commit_msg>[EDIT] 更新异步请求url<commit_after><|endoftext|>


<commit_before>/**
 * main Control extend Class Contorl;
 * pageStucture mainly composed by {form} and {table} control
 *
 * @author xuyihan@bravowhale.com
 * @date 2016.8.2
**/
import Control from 'static/js/controller.js';

import Util from 'widget/util/util';

/**
 * page consists of widgets
 * @type {Object}
 */
var widgets  = {

    header:
        { widget: 'header',data: { username : 'yaweiyihan'},container: '.header-box' },
    topbanner :
        { widget: 'topbanner', data: {},container: '.topbanner-wrapper' },
    editform :
        { widget: 'editform', data: {},container: '.form-wrapper' },
    menu :
        { widget: 'menu', container: '.menu-box' },
    backtotop :
        { widget: 'backtotop', container: '.form-wrapper' },
    footer :
        { widget: 'footer', container: '.footer-box' },
};

class addProControl extends Control{

    constructor(data){
        super(data);
    }
    /**
     * data from router
     * @param  {object} data
     * @return void
     */
    init(data){

        let structure = `

`;
        var me = this;
        this.widgets = this.createPageStructure(structure, widgets ,'.cnt-box');

        /**
         * has no data ,can render directly
         */
        me.getViews([widgets.header,widgets.backtotop,widgets.footer]);
        /**
         * render with widget's own data
         */
        me.getViews([widgets.menu],menusConfig);
        me.getViews([widgets.topbanner],data.topbanner);
        me.getModel('productinfo', (model) => {
            model.getData(data.url, {id: _APP_HASH.id}).then((res) => {
                let dictData = {};
                $.extend(dictData, data);

                dictData.item = Util.processData(res.item);
                me.getViews([me.widgets.editform], $.extend(dictData, data));
            });
        });

        listener.trigger('page', 'loaded', {info: 'load success'});
    }
}

export default addProControl;
<commit_msg>edit page ladder info<commit_after>/**
 * main Control extend Class Contorl;
 * pageStucture mainly composed by {form} and {table} control
 *
 * @author xuyihan@bravowhale.com
 * @date 2016.8.2
**/
import Control from 'static/js/controller.js';

import Util from 'widget/util/util';

/**
 * page consists of widgets
 * @type {Object}
 */
var widgets  = {

    header:
        { widget: 'header',data: { username : 'yaweiyihan'},container: '.header-box' },
    topbanner :
        { widget: 'topbanner', data: {},container: '.topbanner-wrapper' },
    editform :
        { widget: 'editform', data: {},container: '.form-wrapper' },
    menu :
        { widget: 'menu', container: '.menu-box' },
    backtotop :
        { widget: 'backtotop', container: '.form-wrapper' },
    footer :
        { widget: 'footer', container: '.footer-box' },
};

class addProControl extends Control{

    constructor(data){
        super(data);
    }
    /**
     * data from router
     * @param  {object} data
     * @return void
     */
    init(data){

        let structure = `

`;
        var me = this;
        this.widgets = this.createPageStructure(structure, widgets ,'.cnt-box');

        /**
         * has no data ,can render directly
         */
        me.getViews([widgets.header,widgets.backtotop,widgets.footer]);
        /**
         * render with widget's own data
         */
        me.getViews([widgets.menu],menusConfig);
        me.getViews([widgets.topbanner],data.topbanner);
        me.getModel('productinfo', (model) => {
            model.getData(data.url, {id: _APP_HASH.id}).then((res) => {
                let dictData = {};
                // $.extend(dictData, data);

                dictData.item = $.extend(res.item, Util.processData(res.item))
                me.getViews([me.widgets.editform], $.extend(dictData, data));
            });
        });

        listener.trigger('page', 'loaded', {info: 'load success'});
    }
}

export default addProControl;
<|endoftext|>


<commit_before>fabric.util.object.extend(fabric.StaticCanvas.prototype, {

  /**
   * Populates canvas with data from the specified dataless JSON
   * JSON format must conform to the one of `fabric.Canvas#toDatalessJSON`
   * @method loadFromDatalessJSON
   * @param {String} json JSON string
   * @param {Function} callback Callback, invoked when json is parsed
   *                            and corresponding objects (e.g: fabric.Image)
   *                            are initialized
   * @return {fabric.Canvas} instance
   * @chainable
   */
  loadFromDatalessJSON: function (json, callback) {

    if (!json) {
      return;
    }

    // serialize if it wasn't already
    var serialized = (typeof json === 'string')
      ? JSON.parse(json)
      : json;

    if (!serialized || (serialized && !serialized.objects)) return;

    this.clear();

    // TODO: test this
    this.backgroundColor = serialized.background;
    this._enlivenDatalessObjects(serialized.objects, callback);
  },

  /**
   * @method _enlivenDatalessObjects
   * @param {Array} objects
   * @param {Function} callback
   */
  _enlivenDatalessObjects: function (objects, callback) {

    /** @ignore */
    function onObjectLoaded(object, index) {
      _this.insertAt(object, index, true);
      object.setCoords();
      if (++numLoadedObjects === numTotalObjects) {
        callback && callback();
      }
    }

    var _this = this,
        numLoadedObjects = 0,
        numTotalObjects = objects.length;

    if (numTotalObjects === 0 && callback) {
      callback();
    }

    try {
      objects.forEach(function (obj, index) {

        var pathProp = obj.paths ? 'paths' : 'path';
        var path = obj[pathProp];

        delete obj[pathProp];

        if (typeof path !== 'string') {
          switch (obj.type) {
            case 'image':
            case 'text':
              fabric[fabric.util.string.capitalize(obj.type)].fromObject(obj, function (o) {
                onObjectLoaded(o, index);
              });
              break;
            default:
              var klass = fabric[fabric.util.string.camelize(fabric.util.string.capitalize(obj.type))];
              if (klass && klass.fromObject) {
                // restore path
                if (path) {
                  obj[pathProp] = path;
                }
                onObjectLoaded(klass.fromObject(obj), index);
              }
              break;
          }
        }
        else {
          if (obj.type === 'image') {
            fabric.util.loadImage(path, function (image) {
              var oImg = new fabric.Image(image);

              oImg.setSourcePath(path);

              fabric.util.object.extend(oImg, obj);
              oImg.setAngle(obj.angle);

              onObjectLoaded(oImg, index);
            });
          }
          else if (obj.type === 'text') {

            obj.path = path;
            var object = fabric.Text.fromObject(obj);
            var onscriptload = function () {
              // TODO (kangax): find out why Opera refuses to work without this timeout
              if (Object.prototype.toString.call(fabric.window.opera) === '[object Opera]') {
                setTimeout(function () {
                  onObjectLoaded(object, index);
                }, 500);
              }
              else {
                onObjectLoaded(object, index);
              }
            }

            fabric.util.getScript(path, onscriptload);
          }
          else {
            fabric.loadSVGFromURL(path, function (elements, options) {
              if (elements.length > 1) {
                var object = new fabric.PathGroup(elements, obj);
              }
              else {
                var object = elements[0];
              }
              object.setSourcePath(path);

              // copy parameters from serialied json to object (left, top, scaleX, scaleY, etc.)
              // skip this step if an object is a PathGroup, since we already passed it options object before
              if (!(object instanceof fabric.PathGroup)) {
                fabric.util.object.extend(object, obj);
                if (typeof obj.angle !== 'undefined') {
                  object.setAngle(obj.angle);
                }
              }

              onObjectLoaded(object, index);
            });
          }
        }
      }, this);
    }
    catch(e) {
      fabric.log(e.message);
    }
  },

  /**
   * Populates canvas with data from the specified JSON
   * JSON format must conform to the one of `fabric.Canvas#toJSON`
   * @method loadFromJSON
   * @param {String} json JSON string
   * @param {Function} callback Callback, invoked when json is parsed
   *                            and corresponding objects (e.g: fabric.Image)
   *                            are initialized
   * @return {fabric.Canvas} instance
   * @chainable
   */
  loadFromJSON: function (json, callback) {
    if (!json) return;

    var serialized = JSON.parse(json);
    if (!serialized || (serialized && !serialized.objects)) return;

    this.clear();
    var _this = this;
    this._enlivenObjects(serialized.objects, function () {
      _this.backgroundColor = serialized.background;
      if (callback) {
        callback();
      }
    });

    return this;
  },

  /**
   * @method _enlivenObjects
   * @param {Array} objects
   * @param {Function} callback
   */
  _enlivenObjects: function (objects, callback) {
    var numLoadedImages = 0,
        // get length of all images
        numTotalImages = objects.filter(function (o) {
          return o.type === 'image';
        }).length;

    var _this = this;

    objects.forEach(function (o, index) {
      if (!o.type) {
        return;
      }
      switch (o.type) {
        case 'image':
        case 'font':
          fabric[fabric.util.string.capitalize(o.type)].fromObject(o, function (o) {
            _this.insertAt(o, index, true);
            if (++numLoadedImages === numTotalImages) {
              if (callback) {
                callback();
              }
            }
          });
          break;
        default:
          var klass = fabric[fabric.util.string.camelize(fabric.util.string.capitalize(o.type))];
          if (klass && klass.fromObject) {
            _this.insertAt(klass.fromObject(o), index, true);
          }
          break;
      }
    });

    if (numTotalImages === 0 && callback) {
      callback();
    }
  },

  /**
   * @private
   * @method _toDataURL
   * @param {String} format
   * @param {Function} callback
   */
  _toDataURL: function (format, callback) {
    this.clone(function (clone) {
      callback(clone.toDataURL(format));
    });
  },

  /**
   * @private
   * @method _toDataURLWithMultiplier
   * @param {String} format
   * @param {Number} multiplier
   * @param {Function} callback
   */
  _toDataURLWithMultiplier: function (format, multiplier, callback) {
    this.clone(function (clone) {
      callback(clone.toDataURLWithMultiplier(format, multiplier));
    });
  },

  /**
   * Clones canvas instance
   * @method clone
   * @param {Object} [callback] Expects `onBeforeClone` and `onAfterClone` functions
   * @return {fabric.Canvas} Clone of this instance
   */
  clone: function (callback) {
    var el = fabric.document.createElement('canvas');

    el.width = this.getWidth();
    el.height = this.getHeight();

    // cache
    var clone = this.__clone || (this.__clone = new fabric.Canvas(el));
    clone.clipTo = this.clipTo;

    return clone.loadFromJSON(JSON.stringify(this.toJSON()), function () {
      if (callback) {
        callback(clone);
      }
    });
  }
});<commit_msg>fixed bug when text object are not being loaded with loadFromDatalessJSON method<commit_after>fabric.util.object.extend(fabric.StaticCanvas.prototype, {

  /**
   * Populates canvas with data from the specified dataless JSON
   * JSON format must conform to the one of `fabric.Canvas#toDatalessJSON`
   * @method loadFromDatalessJSON
   * @param {String} json JSON string
   * @param {Function} callback Callback, invoked when json is parsed
   *                            and corresponding objects (e.g: fabric.Image)
   *                            are initialized
   * @return {fabric.Canvas} instance
   * @chainable
   */
  loadFromDatalessJSON: function (json, callback) {

    if (!json) {
      return;
    }

    // serialize if it wasn't already
    var serialized = (typeof json === 'string')
      ? JSON.parse(json)
      : json;

    if (!serialized || (serialized && !serialized.objects)) return;

    this.clear();

    // TODO: test this
    this.backgroundColor = serialized.background;
    this._enlivenDatalessObjects(serialized.objects, callback);
  },

  /**
   * @method _enlivenDatalessObjects
   * @param {Array} objects
   * @param {Function} callback
   */
  _enlivenDatalessObjects: function (objects, callback) {

    /** @ignore */
    function onObjectLoaded(object, index) {
      _this.insertAt(object, index, true);
      object.setCoords();
      if (++numLoadedObjects === numTotalObjects) {
        callback && callback();
      }
    }

    var _this = this,
        numLoadedObjects = 0,
        numTotalObjects = objects.length;

    if (numTotalObjects === 0 && callback) {
      callback();
    }

    try {
      objects.forEach(function (obj, index) {

        var pathProp = obj.paths ? 'paths' : 'path';
        var path = obj[pathProp];

        delete obj[pathProp];

        if (typeof path !== 'string') {
          switch (obj.type) {
            case 'image':
              fabric[fabric.util.string.capitalize(obj.type)].fromObject(obj, function (o) {
                onObjectLoaded(o, index);
              });
              break;
            default:
              var klass = fabric[fabric.util.string.camelize(fabric.util.string.capitalize(obj.type))];
              if (klass && klass.fromObject) {
                // restore path
                if (path) {
                  obj[pathProp] = path;
                }
                onObjectLoaded(klass.fromObject(obj), index);
              }
              break;
          }
        }
        else {
          if (obj.type === 'image') {
            fabric.util.loadImage(path, function (image) {
              var oImg = new fabric.Image(image);

              oImg.setSourcePath(path);

              fabric.util.object.extend(oImg, obj);
              oImg.setAngle(obj.angle);

              onObjectLoaded(oImg, index);
            });
          }
          else if (obj.type === 'text') {

            obj.path = path;
            var object = fabric.Text.fromObject(obj);
            var onscriptload = function () {
              // TODO (kangax): find out why Opera refuses to work without this timeout
              if (Object.prototype.toString.call(fabric.window.opera) === '[object Opera]') {
                setTimeout(function () {
                  onObjectLoaded(object, index);
                }, 500);
              }
              else {
                onObjectLoaded(object, index);
              }
            }

            fabric.util.getScript(path, onscriptload);
          }
          else {
            fabric.loadSVGFromURL(path, function (elements, options) {
              if (elements.length > 1) {
                var object = new fabric.PathGroup(elements, obj);
              }
              else {
                var object = elements[0];
              }
              object.setSourcePath(path);

              // copy parameters from serialied json to object (left, top, scaleX, scaleY, etc.)
              // skip this step if an object is a PathGroup, since we already passed it options object before
              if (!(object instanceof fabric.PathGroup)) {
                fabric.util.object.extend(object, obj);
                if (typeof obj.angle !== 'undefined') {
                  object.setAngle(obj.angle);
                }
              }

              onObjectLoaded(object, index);
            });
          }
        }
      }, this);
    }
    catch(e) {
      fabric.log(e.message);
    }
  },

  /**
   * Populates canvas with data from the specified JSON
   * JSON format must conform to the one of `fabric.Canvas#toJSON`
   * @method loadFromJSON
   * @param {String} json JSON string
   * @param {Function} callback Callback, invoked when json is parsed
   *                            and corresponding objects (e.g: fabric.Image)
   *                            are initialized
   * @return {fabric.Canvas} instance
   * @chainable
   */
  loadFromJSON: function (json, callback) {
    if (!json) return;

    var serialized = JSON.parse(json);
    if (!serialized || (serialized && !serialized.objects)) return;

    this.clear();
    var _this = this;
    this._enlivenObjects(serialized.objects, function () {
      _this.backgroundColor = serialized.background;
      if (callback) {
        callback();
      }
    });

    return this;
  },

  /**
   * @method _enlivenObjects
   * @param {Array} objects
   * @param {Function} callback
   */
  _enlivenObjects: function (objects, callback) {
    var numLoadedImages = 0,
        // get length of all images
        numTotalImages = objects.filter(function (o) {
          return o.type === 'image';
        }).length;

    var _this = this;

    objects.forEach(function (o, index) {
      if (!o.type) {
        return;
      }
      switch (o.type) {
        case 'image':
        case 'font':
          fabric[fabric.util.string.capitalize(o.type)].fromObject(o, function (o) {
            _this.insertAt(o, index, true);
            if (++numLoadedImages === numTotalImages) {
              if (callback) {
                callback();
              }
            }
          });
          break;
        default:
          var klass = fabric[fabric.util.string.camelize(fabric.util.string.capitalize(o.type))];
          if (klass && klass.fromObject) {
            _this.insertAt(klass.fromObject(o), index, true);
          }
          break;
      }
    });

    if (numTotalImages === 0 && callback) {
      callback();
    }
  },

  /**
   * @private
   * @method _toDataURL
   * @param {String} format
   * @param {Function} callback
   */
  _toDataURL: function (format, callback) {
    this.clone(function (clone) {
      callback(clone.toDataURL(format));
    });
  },

  /**
   * @private
   * @method _toDataURLWithMultiplier
   * @param {String} format
   * @param {Number} multiplier
   * @param {Function} callback
   */
  _toDataURLWithMultiplier: function (format, multiplier, callback) {
    this.clone(function (clone) {
      callback(clone.toDataURLWithMultiplier(format, multiplier));
    });
  },

  /**
   * Clones canvas instance
   * @method clone
   * @param {Object} [callback] Expects `onBeforeClone` and `onAfterClone` functions
   * @return {fabric.Canvas} Clone of this instance
   */
  clone: function (callback) {
    var el = fabric.document.createElement('canvas');

    el.width = this.getWidth();
    el.height = this.getHeight();

    // cache
    var clone = this.__clone || (this.__clone = new fabric.Canvas(el));
    clone.clipTo = this.clipTo;

    return clone.loadFromJSON(JSON.stringify(this.toJSON()), function () {
      if (callback) {
        callback(clone);
      }
    });
  }
});<|endoftext|>


<commit_before>/*

*/

var moment = require('moment');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;

var PATTERN = /(\W|^)(within|in)\s*([0-9]+)\s*(minutes?|hours?|days?)\s*(?=(?:\W|$))/i;

exports.Parser = function ENDeadlineFormatParser(){
    Parser.call(this);

    this.pattern = function() { return PATTERN; }

    this.extract = function(text, ref, match, opt){

        var index = match.index + match[1].length;
        var text  = match[0];
        text  = match[0].substr(match[1].length, match[0].length - match[1].length);

        var result = new ParsedResult({
            index: index,
            text: text,
            ref: ref,
        });

        var num = match[3];
        num = parseInt(num);

        var date = moment(ref);
        if (match[4].match(/day/)) {
            date.add(num, 'd');

            result.start.assign('year', date.year());
            result.start.assign('month', date.month() + 1);
            result.start.assign('day', date.date());
            return result;
        }

        if (match[4].match(/hour/)) {

            date.add(num, 'hour');

        } else if (match[4].match(/minute/)) {

            date.add(num, 'minute');
        }

        result.start.imply('year', date.year());
        result.start.imply('month', date.month() + 1);
        result.start.imply('day', date.date());
        result.start.assign('hour', date.hour());
        result.start.assign('minute', date.minute());
        result.tags['ENDeadlineFormatParser'] = true;
        return result;
    };
}

<commit_msg>Added `a` and `an` to deadlines, to<commit_after>/*

*/

var moment = require('moment');
var Parser = require('../parser').Parser;
var ParsedResult = require('../../result').ParsedResult;

var PATTERN = /(\W|^)(within|in)\s*([0-9]+|an?)\s*(minutes?|hours?|days?)\s*(?=(?:\W|$))/i;

exports.Parser = function ENDeadlineFormatParser(){
    Parser.call(this);

    this.pattern = function() { return PATTERN; }

    this.extract = function(text, ref, match, opt){

        var index = match.index + match[1].length;
        var text  = match[0];
        text  = match[0].substr(match[1].length, match[0].length - match[1].length);

        var result = new ParsedResult({
            index: index,
            text: text,
            ref: ref,
        });

        var num = match[3];
        if (num === 'a' || num === 'an'){
            num = 1;
        } else {
            num = parseInt(num);
        }

        var date = moment(ref);
        if (match[4].match(/day/)) {
            date.add(num, 'd');

            result.start.assign('year', date.year());
            result.start.assign('month', date.month() + 1);
            result.start.assign('day', date.date());
            return result;
        }

        if (match[4].match(/hour/)) {

            date.add(num, 'hour');

        } else if (match[4].match(/minute/)) {

            date.add(num, 'minute');
        }

        result.start.imply('year', date.year());
        result.start.imply('month', date.month() + 1);
        result.start.imply('day', date.date());
        result.start.assign('hour', date.hour());
        result.start.assign('minute', date.minute());
        result.tags['ENDeadlineFormatParser'] = true;
        return result;
    };
}

<|endoftext|>


<commit_before>var Api = require('./../models/apiModel');

var get = function(req, res){
  Api.find(function(err, Api){
    if(err){
      res.status(500);
      res.send("Error del servidor.");
    }
    else{
      res.status(200);
      res.send(Api);
    }
  });
};

var add = function(req, res){
  var api = new Api(req.body);
  api.save(function(err){
    if(err){
      res.status(500);
      res.send("Error al añadir.");
    }
    else{
      res.status(200);
      res.send(api);
    }
  });
};

var del = function(req, res){
  Api.findById(req.params.id,function(err,api){
    if(err){
      res.status(500);
      res.send("Error.");
    }
    else{
      api.remove(function(err){
        if(err){
          res.status(500);
          res.send("Error al añadir.");
        }
        else{
          res.status(200);
          res.send("Eliminado.");
        }
      });
    }
  });
};

  var update = function(req, res){
    Api.findById(req.params.id,function(err,api){
      if(err){
        res.status(500);
        res.send("Error Update.");
      }
      else{

        var api;
        api.title = req.body.title;
        api.save(function(err){
          if(err){
            res.status(500);
            res.send("Error al añadir.");
          }
          else{
            res.status(200);
            res.send(api);
          }
        });
      }
    });
  };

  var getById = function(req, res){
    Api.findById(req.params.id,function(err,api){
      if(err){
        res.status(500);
        res.send("Error.");
      }
      else{
        res.status(200);
        res.send(api);
      }
    });
  };

module.exports = {
  add:add,
  get:get,
  del:del,
  update:update,
  getById:getById
};
<commit_msg>Finalización de la estructura de la API REST..<commit_after>var Api = require('./../models/apiModel');

var get = function(req, res){
  Api.find(function(err, Api){
    if(err){
      res.status(500);
      res.send("Error del servidor.");
    }
    else{
      res.status(200);
      res.send(Api);
    }
  });
};

var add = function(req, res){
  var api = new Api(req.body);
  api.save(function(err){
    if(err){
      res.status(500);
      res.send("Error al añadir.");
    }
    else{
      res.status(200);
      res.send(api);
    }
  });
};

var del = function(req, res){
  Api.findById(req.params.id,function(err,api){
    if(err){
      res.status(500);
      res.send("Error.");
    }
    else{
      api.remove(function(err){
        if(err){
          res.status(500);
          res.send("Error al añadir.");
        }
        else{
          res.status(200);
          res.send("Eliminado.");
        }
      });
    }
  });
};

  var update = function(req, res){
    Api.findById(req.params.id,function(err,api){
      if(err){
        res.status(500);
        res.send("Error de actualización.");
      }
      else{

        var api;
        api.title = req.body.title;
        api.save(function(err){
          if(err){
            res.status(500);
            res.send("Error al añadir.");
          }
          else{
            res.status(200);
            res.send(api);
          }
        });
      }
    });
  };

  var getById = function(req, res){
    Api.findById(req.params.id,function(err,api){
      if(err){
        res.status(500);
        res.send("Error.");
      }
      else{
        res.status(200);
        res.send(api);
      }
    });
  };

module.exports = {
  add:add,
  get:get,
  del:del,
  update:update,
  getById:getById
};
<|endoftext|>


<commit_before><commit_msg>starting file parsing<commit_after><|endoftext|>


<commit_before>var models = require('../models');

exports.createStolperstein = function(req, res) {
	var stolperstein = new models.stolperstein.Stolperstein(req.body);
	stolperstein.save(function(err, stolperstein) {
		if (!err) {
			res.send(201, stolperstein);
		} else {
			res.send(400, err);
		}
	});
}

exports.retrieveStolpersteine = function(req, res) {
	var query = {};
	if (typeof req.query.q !== 'undefined') {
		var regex = new RegExp('^' + req.query.q, "i");
		query = {
			$or: [
				{"person.lastName": regex},
				{"person.firstName": regex},
				{"location.street": regex},
				{"location.zipCode": regex}
			]
		};
	}

	if (typeof req.query.street !== 'undefined') {
		var regex = new RegExp('^' + req.query.street, "i");
		query = {
			"location.street": regex
		};
	}

	// Use lean option to improve speed
	console.time('t1');
	var stream = models.stolperstein.Stolperstein.find(query).select('-__v').lean().batchSize(100).stream();
	stream.on('data', function(doc) {
		res.write(JSON.stringify(doc));
	}).on('close', function() {
		res.end();
	}).on('err', function(err) {
		res.end();
	});
}

exports.retrieveStolperstein = function(req, res) {
	models.stolperstein.Stolperstein.findById(req.params.id, function(err, stolperstein) {
		if (!err && stolperstein) {
			res.send(stolperstein);
		} else {
			res.send(404, err);
		}
	});
}

exports.deleteStolperstein = function(req, res) {
	models.stolperstein.Stolperstein.findByIdAndRemove(req.params.id, function(err, stolperstein) {
		if (!err && stolperstein) {
			res.send(204);
		} else {
			res.send(404, err);
		}
	});
}<commit_msg>Testing write/end<commit_after>var models = require('../models');

exports.createStolperstein = function(req, res) {
	var stolperstein = new models.stolperstein.Stolperstein(req.body);
	stolperstein.save(function(err, stolperstein) {
		if (!err) {
			res.send(201, stolperstein);
		} else {
			res.send(400, err);
		}
	});
}

exports.retrieveStolpersteine = function(req, res) {
	var query = {};
	if (typeof req.query.q !== 'undefined') {
		var regex = new RegExp('^' + req.query.q, "i");
		query = {
			$or: [
				{"person.lastName": regex},
				{"person.firstName": regex},
				{"location.street": regex},
				{"location.zipCode": regex}
			]
		};
	}

	if (typeof req.query.street !== 'undefined') {
		var regex = new RegExp('^' + req.query.street, "i");
		query = {
			"location.street": regex
		};
	}

	// Use lean option to improve speed
	console.time('t1');
	models.stolperstein.Stolperstein.find(query).select('-__v').lean().exec(function(err, stolpersteine) {
		console.timeEnd('t1');
		console.time('t2');
		if (!err) {
			for (var i = 0; i < stolpersteine.length; i++) {
				var stolperstein = stolpersteine[i];
				stolperstein.id = stolperstein._id;
				delete stolperstein._id;
			}
			res.write(JSON.stringify(stolpersteine));
			res.end();
		} else {
			res.send(400, err);
		}
		console.timeEnd('t2');
	});
}

exports.retrieveStolperstein = function(req, res) {
	models.stolperstein.Stolperstein.findById(req.params.id, function(err, stolperstein) {
		if (!err && stolperstein) {
			res.send(stolperstein);
		} else {
			res.send(404, err);
		}
	});
}

exports.deleteStolperstein = function(req, res) {
	models.stolperstein.Stolperstein.findByIdAndRemove(req.params.id, function(err, stolperstein) {
		if (!err && stolperstein) {
			res.send(204);
		} else {
			res.send(404, err);
		}
	});
}<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Playback = require('playback')
var JST = require('../../base/jst')
var Styler = require('../../base/styler')
var Browser = require('browser')
var Mousetrap = require('mousetrap')
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds

var _ = require('underscore')

class HTML5Video extends Playback {
  get name() { return 'html5_video' }
  get tagName() { return 'video' }
  get template() { return JST.html5_video }

  get attributes() {
    return {
      'data-html5-video': ''
    }
  }

  get events() {
    return {
      'timeupdate': 'timeUpdated',
      'progress': 'progress',
      'ended': 'ended',
      'playing': 'playing',
      'stalled': 'stalled',
      'waiting': 'waiting',
      'canplaythrough': 'bufferFull',
      'loadedmetadata': 'loadedMetadata'
    }
  }

  constructor(options) {
    super(options);
    this.options = options
    this.src = options.src
    this.el.src = options.src
    this.el.loop = options.loop
    this.isHLS = (this.src.indexOf('m3u8') > -1)
    this.settings = {default: ['seekbar']}
    if (this.isHLS) {
      this.settings.left = ["playstop"]
      this.settings.right = ["fullscreen", "volume"]
    } else {
      this.settings.left = ["playpause", "position", "duration"]
      this.settings.right = ["fullscreen", "volume"]
      this.settings.seekEnabled = true
    }
    this.bindEvents()
  }

  bindEvents() {
    _.each(_.range(1,10), function (i) { Mousetrap.bind([i.toString()], () => this.seek(i * 10)) }.bind(this))
  }

  loadedMetadata(e) {
    this.trigger('playback:loadedmetadata', e.target.duration)
    this.trigger('playback:settingsupdate')
    this.checkInitialSeek()
  }

  getPlaybackType() {
    return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'
  }

  isHighDefinitionInUse() {
    return false
  }

  play() {
    this.el.play()
    this.trigger('playback:play');
    if (this.isHLS) {
      this.trigger('playback:timeupdate', 1, 1, this.name)
    }
  }

  pause() {
    this.el.pause()
  }

  stop() {
    this.pause()
    if (this.el.readyState !== 0) {
      this.el.currentTime = 0
    }
  }

  volume(value) {
    this.el.volume = value / 100
  }

  mute() {
    this.el.volume = 0
  }

  unmute() {
    this.el.volume = 1
  }

  isMuted() {
    return !!this.el.volume
  }

  isPlaying() {
    return !this.el.paused && !this.el.ended
  }

  ended() {
    this.trigger('playback:ended', this.name)
    this.trigger('playback:timeupdate', 0, this.el.duration, this.name)
  }

  stalled() {
    if (this.getPlaybackType() === 'vod') {
      this.trigger('playback:buffering', this.name)
    }
  }

  waiting() {
    this.trigger('playback:buffering', this.name)
  }

  bufferFull() {
    this.trigger('playback:bufferfull', this.name)
  }

  destroy() {
    this.stop()
    this.el.src = ''
    this.$el.remove()
  }

  seek(seekBarValue) {
    var time = this.el.duration * (seekBarValue / 100)
    this.seekSeconds(time)
  }

  seekSeconds(time) {
    this.el.currentTime = time
  }

  checkInitialSeek() {
    var seekTime = seekStringToSeconds(window.location.href)
    this.seekSeconds(seekTime)
  }

  getCurrentTime() {
    return this.el.currentTime
  }

  getDuration() {
    return this.el.duration
  }

  timeUpdated() {
    if (this.getPlaybackType() !== 'live') {
      this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name)
    }
  }

  progress() {
    if (!this.el.buffered.length) return
    var bufferedPos = 0
    for (var i = 0;  i < this.el.buffered.length; i++) {
      if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
        bufferedPos = i
        break
      }
    }
    this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name)
  }

  typeFor(src) {
    return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'
  }

  render() {
    var style = Styler.getStyleFor(this.name)
    this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) }))
    this.$el.append(style)
    this.trigger('playback:ready', this.name)
    process.nextTick(() => this.options.autoPlay && this.play())
    return this
  }
}

HTML5Video.canPlay = function(resource) {
    return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App)
}

module.exports = HTML5Video
<commit_msg>html5 video: fix wrong behavior in safari(fixes #244)<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Playback = require('playback')
var JST = require('../../base/jst')
var Styler = require('../../base/styler')
var Browser = require('browser')
var Mousetrap = require('mousetrap')
var seekStringToSeconds = require('../../base/utils').seekStringToSeconds

var _ = require('underscore')

class HTML5Video extends Playback {
  get name() { return 'html5_video' }
  get tagName() { return 'video' }
  get template() { return JST.html5_video }

  get attributes() {
    return {
      'data-html5-video': ''
    }
  }

  get events() {
    return {
      'timeupdate': 'timeUpdated',
      'progress': 'progress',
      'ended': 'ended',
      'stalled': 'stalled',
      'waiting': 'waiting',
      'canplaythrough': 'bufferFull',
      'loadedmetadata': 'loadedMetadata'
    }
  }

  constructor(options) {
    super(options);
    this.options = options
    this.src = options.src
    this.el.src = options.src
    this.el.loop = options.loop
    this.isHLS = (this.src.indexOf('m3u8') > -1)
    this.settings = {default: ['seekbar']}
    if (this.isHLS) {
      this.settings.left = ["playstop"]
      this.settings.right = ["fullscreen", "volume"]
    } else {
      this.settings.left = ["playpause", "position", "duration"]
      this.settings.right = ["fullscreen", "volume"]
      this.settings.seekEnabled = true
    }
    this.bindEvents()
  }

  bindEvents() {
    _.each(_.range(1,10), function (i) { Mousetrap.bind([i.toString()], () => this.seek(i * 10)) }.bind(this))
  }

  loadedMetadata(e) {
    this.trigger('playback:loadedmetadata', e.target.duration)
    this.trigger('playback:settingsupdate')
    this.checkInitialSeek()
  }

  getPlaybackType() {
    return this.isHLS && _.contains([0, undefined, Infinity], this.el.duration) ? 'live' : 'vod'
  }

  isHighDefinitionInUse() {
    return false
  }

  play() {
    this.el.play()
    this.trigger('playback:play');
    if (this.isHLS) {
      this.trigger('playback:timeupdate', 1, 1, this.name)
    }
  }

  pause() {
    this.el.pause()
  }

  stop() {
    this.pause()
    if (this.el.readyState !== 0) {
      this.el.currentTime = 0
    }
  }

  volume(value) {
    this.el.volume = value / 100
  }

  mute() {
    this.el.volume = 0
  }

  unmute() {
    this.el.volume = 1
  }

  isMuted() {
    return !!this.el.volume
  }

  isPlaying() {
    return !this.el.paused && !this.el.ended
  }

  ended() {
    this.trigger('playback:ended', this.name)
    this.trigger('playback:timeupdate', 0, this.el.duration, this.name)
  }

  stalled() {
    if (this.getPlaybackType() === 'vod' && this.el.readyState < this.el.HAVE_FUTURE_DATA) {
      this.trigger('playback:buffering', this.name)
    }
  }

  waiting() {
    if(this.el.readyState < this.el.HAVE_FUTURE_DATA) {
      this.trigger('playback:buffering', this.name)
    }
  }

  bufferFull() {
    this.trigger('playback:bufferfull', this.name)
  }

  destroy() {
    this.stop()
    this.el.src = ''
    this.$el.remove()
  }

  seek(seekBarValue) {
    var time = this.el.duration * (seekBarValue / 100)
    this.seekSeconds(time)
  }

  seekSeconds(time) {
    this.el.currentTime = time
  }

  checkInitialSeek() {
    var seekTime = seekStringToSeconds(window.location.href)
    this.seekSeconds(seekTime)
  }

  getCurrentTime() {
    return this.el.currentTime
  }

  getDuration() {
    return this.el.duration
  }

  timeUpdated() {
    if (this.getPlaybackType() !== 'live') {
      this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name)
    }
  }

  progress() {
    if (!this.el.buffered.length) return
    var bufferedPos = 0
    for (var i = 0;  i < this.el.buffered.length; i++) {
      if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
        bufferedPos = i
        break
      }
    }
    this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name)
  }

  typeFor(src) {
    return (src.indexOf('.m3u8') > 0) ? 'application/vnd.apple.mpegurl' : 'video/mp4'
  }

  render() {
    var style = Styler.getStyleFor(this.name)
    this.$el.html(this.template({ src: this.src, type: this.typeFor(this.src) }))
    this.$el.append(style)
    this.trigger('playback:ready', this.name)
    process.nextTick(() => this.options.autoPlay && this.play())
    return this
  }
}

HTML5Video.canPlay = function(resource) {
    return (!!resource.match(/(.*).mp4/) || Browser.isSafari || Browser.isMobile || Browser.isWin8App)
}

module.exports = HTML5Video
<|endoftext|>


<commit_before>'use strict';

var assert = require('assert');
const {escapejs, str, array, json} = require('../escapejs');

describe('Testing of the recursive escape', function(){

	it('send string must return string', function(){
		var string = "<string>";
		var resStr = "%3Cstring%3E";
		assert.equal(resStr, str(string), 'Testing String');
	});

	it('send json must return json', function(){
		var obj = {
			'a': '<script>',
			'b': ['a', '<script>', {'a': 1, 'b': '<script>'}]
		};
		var jsonp = { a: '%3Cscript%3E', b: [ 'a', '%3Cscript%3E', { a: 1, b: '%3Cscript%3E' } ] };
		assert.deepEqual(jsonp, json(obj), 'Testing JSON');
	});

	it('send array must return array', function(){
		var arr = [
			'<script>',
			['asdasd', '<script>',
				['<asdasd>',
					['a', '<script>', {'a': '12', 'b': '<script>'}]
				]
			]
		];
		var arrays = [ '%3Cscript%3E', [ 'asdasd', '%3Cscript%3E', [ '%3Casdasd%3E', [Object] ] ] ];
		assert.notStrictEqual(arrays, array(arr), 'Testing Array');
	});

	it('send any param and return param escape', function(){
		/*
		* String
		*/
		var string = "<string>";
		var resStr = "%3Cstring%3E";
		assert.equal(resStr, escapejs(string), 'Testing escapejs(string)');

		/*
		* Json
		*/
		var obj = {
			'a': '<script>',
			'b': ['a', '<script>', {'a': 1, 'b': '<script>'}]
		};
		var jsonp = { a: '%3Cscript%3E', b: [ 'a', '%3Cscript%3E', { a: 1, b: '%3Cscript%3E' } ] };
		assert.deepEqual(jsonp, json(obj), 'Testing escapejs(json)');

		/*
		* Array
		*/
		var arr = [
			'<script>',
			['asdasd', '<script>',
				['<asdasd>',
					['a', '<script>', {'a': '12', 'b': '<script>'}]
				]
			]
		];
		var arrays = [ '%3Cscript%3E', [ 'asdasd', '%3Cscript%3E', [ '%3Casdasd%3E', [Object] ] ] ];
		assert.notStrictEqual(arrays, array(arr), 'Testing escapejs(Array)');
	});
});
<commit_msg>[-] removed distructing assing import from tests<commit_after><|endoftext|>


<commit_before>'use strict';

var fs = require('fs');
var path = require('path');
var size = require('window-size');
var repeat = require('repeat-string');

function bench() {
  var filepath = path.join(__dirname, 'last.md');
  var str = fs.readFileSync(filepath, 'utf8');
  var sections = str.split(/(?=\n?(?:# benchmark))/);
  sections.shift();

  var len = sections.length;
  var idx = -1;
  var res = [];

  while (++idx < len) {
    var section = sections[idx].trim();
    var tok = parseSection(section);
    if (tok) res.push(tok);
  }

  return res.join('\n');
}

function parseSection(str) {
  var lines = str.split('\n').filter(Boolean);
  if (!lines.length) return;
  var title = lines.shift().trim();
  var m = /^.*\/fixtures\/match\/([^(]+)/.exec(title);

  var tok = {title: (m ? m[1] : title).trim()};
  tok.title = tok.title.slice(0, tok.title.length - 3);

  tok.micromatch = parseStats(lines);
  tok['minimatch '] = parseStats(lines);
  tok.multimatch = parseStats(lines);
  var vals = values(tok);
  var max = Math.max.apply(Math, vals);

  var str = '';
  str += ['#', tok.title].join(' ') + '\n';
  str += format('micromatch', tok, max, 100);
  str += format('minimatch ', tok, max, 100);
  str += format('multimatch', tok, max, 100);
  // console.log(str)
  return str;
}

function parseStats(lines) {
  var str = lines.shift().trim();
  var m = /^([^\s]+)\s*x\s*([\d,.]+)/.exec(str);
  if (!m) return 0;
  var str = m[2];
  var num = String(str).split(',').join('');
  return {
    num: num,
    str: str
  };
}

function values(obj) {
  var vals = [];
  for (var key in obj) {
    if (key === 'title') continue;
    vals.push(obj[key].num);
  }
  return vals;
}

function bar(tok, longest, diff) {
  return repeat('█', (tok.num / longest) * (size.width - diff));
}

function format(name, tok, max, diff) {
  return [name, bar(tok[name], max, diff), '(' + tok[name].str + ' ops/sec)', '\n'].join(' ');
}

/**
 * Expose `.bench` helper
 */

module.exports.bench = bench;
<commit_msg>fix chart formatting<commit_after>'use strict';

var fs = require('fs');
var path = require('path');
var repeat = require('repeat-string');

function bench() {
  var filepath = path.join(__dirname, 'last.md');
  var str = fs.readFileSync(filepath, 'utf8');
  var sections = str.split(/(?=\n?(?:# benchmark))/);
  sections.shift();

  var len = sections.length;
  var idx = -1;
  var res = [];

  while (++idx < len) {
    var section = sections[idx].trim();
    var tok = parseSection(section);
    if (tok) res.push(tok);
  }

  return res.join('\n');
}

function parseSection(str) {
  var lines = str.split('\n').filter(Boolean);
  if (!lines.length) return;
  var title = lines.shift().trim();
  var m = /^.*\/fixtures\/match\/([^(]+)/.exec(title);

  var tok = {title: (m ? m[1] : title).trim()};
  tok.title = tok.title.slice(0, tok.title.length - 3);

  tok.micromatch = parseStats(lines);
  tok['minimatch '] = parseStats(lines);
  tok.multimatch = parseStats(lines);
  var vals = values(tok);
  var max = Math.max.apply(Math, vals);

  var str = '';
  str += ['#', tok.title].join(' ') + '\n';
  str += format('micromatch', tok, max, 100);
  str += format('minimatch ', tok, max, 100);
  str += format('multimatch', tok, max, 100);
  // console.log(str)
  return str;
}

function parseStats(lines) {
  var str = lines.shift().trim();
  var m = /^([^\s]+)\s*x\s*([\d,.]+)/.exec(str);
  if (!m) return 0;
  var str = m[2];
  var num = String(str).split(',').join('');
  return {
    num: num,
    str: str
  };
}

function values(obj) {
  var vals = [];
  for (var key in obj) {
    if (key === 'title') continue;
    vals.push(obj[key].num);
  }
  return vals;
}

function bar(tok, longest, diff) {
  return repeat('█', (tok.num / longest) * 70);
}

function format(name, tok, max, diff) {
  return [name, bar(tok[name], max, diff), '(' + tok[name].str + ' ops/sec)', '\n'].join(' ');
}

/**
 * Expose `.bench` helper
 */

module.exports.bench = bench;
<|endoftext|>