text
stringlengths
3
1.05M
function MotdViewModel(data) { this.Title = data.Title; this.Message = data.Message; this.Hash = data.Hash; }
var should = require('should'), assert = require('assert'), Iyzipay = require('../lib/Iyzipay'), options = require('./data/options'); describe('Iyzipay API Test', function () { var iyzipay; before(function (done) { iyzipay = new Iyzipay(options); done(); }); describe('ApiTest', function () { it('should test api', function (done) { iyzipay.apiTest.retrieve({}, function (err, result) { should.not.exist(err); should.exist(result); result.should.have.property('status', 'success'); result.should.have.property('locale', 'tr'); result.should.have.property('systemTime').and.is.a.Number(); done(); }); }); }); describe('TLSv_1_2Test', function () { it('should success tls v1.2 secure protocol', function (done) { // Clone options var tlsOptions = JSON.parse(JSON.stringify(options)); tlsOptions.uri = 'https://sandbox-api-tls12.iyzipay.com/'; var iyzipay = new Iyzipay(tlsOptions); iyzipay.apiTest.retrieve({}, function (err, result) { should.not.exist(err); should.exist(result); result.should.have.property('status', 'success'); result.should.have.property('locale', 'tr'); result.should.have.property('systemTime').and.is.a.Number(); done(); }); }); }); describe('Approval', function () { it('should approve payment item', function (done) { iyzipay.approval.create({ locale: Iyzipay.LOCALE.TR, conversationId: "123456789", paymentTransactionId: "1" }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Disapproval', function () { it('should disapprove payment item', function (done) { iyzipay.disapproval.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentTransactionId: '1' }, function (err, result) { console.log(err, result); done(); }); }) }); describe('BinNumber', function () { it('should retrieve bin', function (done) { iyzipay.binNumber.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', binNumber: '554960' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Bkm', function () { it('should initialize bkm', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', basketId: 'B67832', paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, callbackUrl: 'https://www.merchant.com/callback', enabledInstallments: [2, 3, 6, 9], buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.bkmInitialize.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve bkm result', function (done) { iyzipay.bkm.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', token: 'token' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Cancel', function () { it('should cancel payment', function (done) { iyzipay.cancel.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentId: '1', ip: '85.34.78.112' }, function (err, result) { console.log(err, result); done(); }); }); it('should cancel payment with reason and description', function (done) { iyzipay.cancel.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentId: '1', ip: '85.34.78.112', reason: Iyzipay.REFUND_REASON.OTHER, description: 'customer requested for default sample' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Card', function () { it('should create user and add card', function (done) { iyzipay.card.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', email: '[email protected]', externalId: 'external id', card: { cardAlias: 'card alias', cardHolderName: 'John Doe', cardNumber: '5528790000000008', expireMonth: '12', expireYear: '2030' } }, function (err, result) { console.log(err, result); done(); }); }); it('should create card', function (done) { iyzipay.card.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', cardUserKey: 'card user key', card: { cardAlias: 'card alias', cardHolderName: 'John Doe', cardNumber: '5528790000000008', expireMonth: '12', expireYear: '2030' } }, function (err, result) { console.log(err, result); done(); }); }); it('should delete card', function (done) { iyzipay.card.delete({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', cardToken: 'card token', cardUserKey: 'card user key' }, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve cards', function (done) { iyzipay.cardList.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', cardUserKey: 'card user key' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Checkout Form', function () { it('should initialize checkout form', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.TRY, basketId: 'B67832', paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, callbackUrl: 'https://www.merchant.com/callback', enabledInstallments: [2, 3, 6, 9], buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.checkoutFormInitialize.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve checkout form result', function (done) { iyzipay.checkoutForm.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', token: 'token' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Installment', function () { it('should retrieve installments', function (done) { iyzipay.installmentInfo.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', binNumber: '554960', price: '100' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Payment', function () { it('should create payment', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.TRY, installment: '1', basketId: 'B67832', paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB, paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, paymentCard: { cardHolderName: 'John Doe', cardNumber: '5528790000000008', expireMonth: '12', expireYear: '2030', cvc: '123', registerCard: '0' }, buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.payment.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should create marketplace payment', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.TRY, installment: '1', basketId: 'B67832', paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB, paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, paymentCard: { cardHolderName: 'John Doe', cardNumber: '5528790000000008', expireMonth: '12', expireYear: '2030', cvc: '123', registerCard: '0' }, buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3', subMerchantKey: 'sub merchant key', subMerchantPrice: '0.27' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5', subMerchantKey: 'sub merchant key', subMerchantPrice: '0.42' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2', subMerchantKey: 'sub merchant key', subMerchantPrice: '0.18' } ] }; iyzipay.payment.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should create payment with registered card', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.TRY, installment: '1', basketId: 'B67832', paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB, paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, paymentCard: { cardUserKey: 'card user key', cardToken: 'card token' }, buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.payment.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve payment result', function (done) { iyzipay.payment.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentId: '1', paymentConversationId: '123456789' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Pecco', function () { it('should initialize pecco', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '100000', paidPrice: '120000', currency: Iyzipay.CURRENCY.IRR, basketId: 'B67832', paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, callbackUrl: 'https://www.merchant.com/callback', buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '30000' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '50000' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '20000' } ] }; iyzipay.peccoInitialize.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should create pecco payment', function (done) { iyzipay.peccoPayment.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', token: 'token' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Refund', function () { it('should refund', function (done) { iyzipay.refund.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentTransactionId: '1', price: '0.5', currency: Iyzipay.CURRENCY.TRY, ip: '85.34.78.112' }, function (err, result) { console.log(err, result); done(); }); }); it('should refund with reason and description', function (done) { iyzipay.refund.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentTransactionId: '1', price: '0.5', currency: Iyzipay.CURRENCY.TRY, ip: '85.34.78.112', reason: Iyzipay.REFUND_REASON.OTHER, description: 'customer requested for default sample' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Retrieve Transactions Sample', function () { it('should retrieve payout completed transactions', function (done) { iyzipay.payoutCompletedTransactionList.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', date: '2016-01-22 19:13:00' }, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve bounced bank transfers', function (done) { iyzipay.bouncedBankTransferList.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', date: '2016-01-22 19:13:00' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Sub Merchant', function () { it('should create personal sub merchant', function (done) { iyzipay.subMerchant.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantExternalId: 'B49224', subMerchantType: Iyzipay.SUB_MERCHANT_TYPE.PERSONAL, address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', contactName: 'John', contactSurname: 'Doe', email: '[email protected]', gsmNumber: '+905350000000', name: 'John\'s market', iban: 'TR180006200119000006672315', identityNumber: '31300864726', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should create private sub merchant', function (done) { iyzipay.subMerchant.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantExternalId: 'S49222', subMerchantType: Iyzipay.SUB_MERCHANT_TYPE.PRIVATE_COMPANY, address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', taxOffice: 'Tax office', legalCompanyTitle: 'John Doe inc', email: '[email protected]', gsmNumber: '+905350000000', name: 'John\'s market', iban: 'TR180006200119000006672315', identityNumber: '31300864726', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should create limited company sub merchant', function (done) { iyzipay.subMerchant.create({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantExternalId: 'AS49224', subMerchantType: Iyzipay.SUB_MERCHANT_TYPE.LIMITED_OR_JOINT_STOCK_COMPANY, address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', taxOffice: 'Tax office', taxNumber: '9261877', legalCompanyTitle: 'XYZ inc', email: '[email protected]', gsmNumber: '+905350000000', name: 'John\'s market', iban: 'TR180006200119000006672315', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should update personal sub merchant', function (done) { iyzipay.subMerchant.update({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantKey: 'sub merchant key', iban: 'TR630006200027700006678204', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', contactName: 'Jane', contactSurname: 'Doe', email: '[email protected]', gsmNumber: '+905350000000', name: 'Jane\'s market', identityNumber: '31300864726', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should update private sub merchant', function (done) { iyzipay.subMerchant.update({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantKey: 'sub merchant key', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', taxOffice: 'Tax office', legalCompanyTitle: 'Jane Doe inc', email: '[email protected]', gsmNumber: '+905350000000', name: 'Jane\'s market', iban: 'TR180006200119000006672315', identityNumber: '31300864726', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should update limited company sub merchant', function (done) { iyzipay.subMerchant.update({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantKey: 'sub merchant key', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', taxOffice: 'Tax office', taxNumber: '9261877', legalCompanyTitle: 'ABC inc', email: '[email protected]', gsmNumber: '+905350000000', name: 'Jane\'s market', iban: 'TR180006200119000006672315', currency: Iyzipay.CURRENCY.TRY }, function (err, result) { console.log(err, result); done(); }); }); it('should retrieve sub merchant', function (done) { iyzipay.subMerchant.retrieve({ locale: Iyzipay.LOCALE.TR, conversationId: '123456789', subMerchantExternalId: 'AS49224' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Threeds', function () { it('should initialize threeds', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.TRY, installment: '1', basketId: 'B67832', paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB, paymentGroup: Iyzipay.PAYMENT_GROUP.PRODUCT, callbackUrl: 'https://www.merchant.com/callback', paymentCard: { cardHolderName: 'John Doe', cardNumber: '5528790000000008', expireMonth: '12', expireYear: '2030', cvc: '123', registerCard: '0' }, buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.threedsInitialize.create(request, function (err, result) { console.log(err, result); done(); }); }); it('should create threeds payment', function (done) { iyzipay.threedsPayment.create({ conversationId: '123456789', locale: Iyzipay.LOCALE.TR, paymentId: '1', conversationData: 'conversation data' }, function (err, result) { console.log(err, result); done(); }); }); }); describe('Apm', function () { it('should initialize apm payment', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', price: '1', paidPrice: '1.2', currency: Iyzipay.CURRENCY.EUR, countryCode: 'DE', paymentChannel: Iyzipay.PAYMENT_CHANNEL.WEB, paymentGroup: Iyzipay.PAYMENT_GROUP.LISTING, accountHolderName : 'Jane Doe', merchantNotificationUrl: 'https://www.merchant.com/notification', merchantCallbackUrl: 'https://www.merchant.com/callback', merchantErrorUrl: 'https://www.merchant.com/error', apmType: Iyzipay.APM_TYPE.SOFORT, buyer: { id: 'BY789', name: 'John', surname: 'Doe', gsmNumber: '+905350000000', email: '[email protected]', identityNumber: '74300864791', lastLoginDate: '2015-10-05 12:43:35', registrationDate: '2013-04-21 15:12:09', registrationAddress: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', ip: '85.34.78.112', city: 'Istanbul', country: 'Turkey', zipCode: '34732' }, shippingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, billingAddress: { contactName: 'Jane Doe', city: 'Istanbul', country: 'Turkey', address: 'Nidakule Göztepe, Merdivenköy Mah. Bora Sok. No:1', zipCode: '34742' }, basketItems: [ { id: 'BI101', name: 'Binocular', category1: 'Collectibles', category2: 'Accessories', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.3' }, { id: 'BI102', name: 'Game code', category1: 'Game', category2: 'Online Game Items', itemType: Iyzipay.BASKET_ITEM_TYPE.VIRTUAL, price: '0.5' }, { id: 'BI103', name: 'Usb', category1: 'Electronics', category2: 'Usb / Cable', itemType: Iyzipay.BASKET_ITEM_TYPE.PHYSICAL, price: '0.2' } ] }; iyzipay.apm.create(request, function (err, result) { console.log(err, result); done(); }); }); it('retrieve apm payment result', function (done) { var request = { locale: Iyzipay.LOCALE.TR, conversationId: '123456789', paymentId: '1' }; iyzipay.apm.retrieve(request, function (err, result) { console.log(err, result); done(); }); }); }); });
import os import tensorflow import util.config as config import recognition.ml_util import numpy as np import jsonpickle from unittest import TestCase from recognition import ml_util from recognition.ml_data import MlData class TestMlUtil(TestCase): def setUp(self): self.ml_data = MlData([],[],[],[], {}, {}, {}, {}, [],[],[],[]) def test_check_is_augmented_image_name(self): not_aug_image_name = 'DSC_V2_6408_2593.JPG-crop-mask0.jpg' self.assertFalse(ml_util.check_is_augmented_image_name(not_aug_image_name)) aug_image_name = '0-DSC_V2_6408_2593.JPG-crop-mask0.jpg' self.assertTrue(ml_util.check_is_augmented_image_name(aug_image_name)) ml_data = self.ml_data ml_data.x_test ml_data.pig_dict[0] = '6440' ml_data.x_train.append(np.array([1, 2, 3]).tolist()) ml_data.y_train.append(0) ml_data_json = jsonpickle.encode(ml_data) print(ml_data_json) self.assertIsNotNone(ml_data_json,'JSON is None')
# -*- coding: utf-8 -*- # # Copyright (c) 2018 Leland Stanford Junior University # Copyright (c) 2018 The Regents of the University of California # # This file is part of pelicun. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, # this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors # may be used to endorse or promote products derived from this software without # specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # You should have received a copy of the BSD 3-Clause License along with # pelicun. If not, see <http://www.opensource.org/licenses/>. # # Contributors: # Adam Zsarnóczay """ This module has classes and methods that control the loss assessment. .. rubric:: Contents .. autosummary:: Assessment FEMA_P58_Assessment """ from .base import * from .uq import * from .model import * from .file_io import * class Assessment(object): """ A high-level class that collects features common to all supported loss assessment methods. This class will only rarely be called directly when using pelicun. """ def __init__(self): # initialize the basic data containers # inputs self._AIM_in = None self._EDP_in = None self._POP_in = None self._FG_in = None # random variables and loss model self._RV_dict = None # dictionary to store random variables self._EDP_dict = None self._FG_dict = None # results self._TIME = None self._POP = None self._COL = None self._ID_dict = None self._DMG = None self._DV_dict = None self._SUMMARY = None def read_inputs(self, path_DL_input, path_EDP_input, verbose=False): """ Read and process the input files to describe the loss assessment task. Parameters ---------- path_DL_input: string Location of the Damage and Loss input file. The file is expected to be a JSON with data stored in a standard format described in detail in the Input section of the documentation. path_EDP_input: string Location of the EDP input file. The file is expected to follow the output formatting of Dakota. The Input section of the documentation provides more information about the expected formatting. verbose: boolean, default: False If True, the method echoes the information read from the files. This can be useful to ensure that the information in the file is properly read by the method. """ # read SimCenter inputs ----------------------------------------------- # BIM file self._AIM_in = read_SimCenter_DL_input(path_DL_input, verbose=verbose) # EDP file self._EDP_in = read_SimCenter_EDP_input(path_EDP_input, verbose=verbose) def define_random_variables(self): """ Define the random variables used for loss assessment. """ pass def define_loss_model(self): """ Create the stochastic loss model based on the inputs provided earlier. """ pass def calculate_damage(self): """ Characterize the damage experienced in each random event realization. """ self._ID_dict = {} def calculate_losses(self): """ Characterize the consequences of damage in each random event realization. """ self._DV_dict = {} def write_outputs(self): """ Export the results. """ pass class FEMA_P58_Assessment(Assessment): """ An Assessment class that implements the loss assessment method in FEMA P58. """ def __init__(self, inj_lvls = 2): super(FEMA_P58_Assessment, self).__init__() # constants for the FEMA-P58 methodology self._inj_lvls = inj_lvls @property def beta_additional(self): """ Calculate the total additional uncertainty for post processing. The total additional uncertainty is the squared root of sum of squared uncertainties corresponding to ground motion and modeling. Returns ------- beta_tot: float The total uncertainty (logarithmic EDP standard deviation) to add to the EDP distribution. """ AU = self._AIM_in['general']['added_uncertainty'] beta_tot = 0. if AU['beta_m'] is not None: beta_tot += AU['beta_m']**2. if AU['beta_gm'] is not None: beta_tot += AU['beta_gm']**2. # if no uncertainty is assigned, we consider a minimum of 10^-4 if beta_tot == 0: beta_tot = 1e-4 else: beta_tot = np.sqrt(beta_tot) return beta_tot def read_inputs(self, path_DL_input, path_EDP_input, path_CMP_data=None, path_POP_data=None, verbose=False): """ Read and process the input files to describe the loss assessment task. Parameters ---------- path_DL_input: string Location of the Damage and Loss input file. The file is expected to be a JSON with data stored in a standard format described in detail in the Input section of the documentation. path_EDP_input: string Location of the EDP input file. The file is expected to follow the output formatting of Dakota. The Input section of the documentation provides more information about the expected formatting. path_CMP_data: string, default: None Location of the folder with component damage and loss data files. The default None value triggers the use of the FEMA P58 first edition data from pelicun/resources/component DL/FEMA P58 first edition/. path_POP_data: string, default: None Location of the JSON file that describes the temporal distribution of the population per the FEMA P58 method. The default None value triggers the use of the FEMA P58 first edition distribution from pelicun/resources/population.json. verbose: boolean, default: False If True, the method echoes the information read from the files. This can be useful to ensure that the information in the file is properly read by the method. """ super(FEMA_P58_Assessment, self).read_inputs(path_DL_input, path_EDP_input, verbose) # check if the component data path is provided by the user if path_CMP_data is None: warnings.warn(UserWarning( "The component database is not specified; using the default " "FEMA P58 first edition data." )) #path_CMP_data = '../../resources/component DL/FEMA P58 first edition/' path_CMP_data = pelicun_path path_CMP_data += '/resources/component DL/FEMA P58 first edition/' if path_POP_data is None: warnings.warn(UserWarning( "The population distribution is not specified; using the default " "FEMA P58 first edition data." )) #path_POP_data = '../../resources/population.json' path_POP_data = pelicun_path path_POP_data += '/resources/population.json' # assume that the asset is a building # TODO: If we want to apply FEMA-P58 to non-building assets, several parts of this methodology need to be extended. BIM = self._AIM_in # read component and population data ---------------------------------- # components self._FG_in = read_component_DL_data(path_CMP_data, BIM['components'], verbose=verbose) # population POP = read_population_distribution( path_POP_data, BIM['general']['occupancy_type'], verbose=verbose) POP['peak'] = BIM['general']['population'] self._POP_in = POP def define_random_variables(self): """ Define the random variables used for loss assessment. Following the FEMA P58 methodology, the groups of parameters below are considered random. Simple correlation structures within each group can be specified through the DL input file. The random decision variables are only created and used later if those particular decision variables are requested in the input file. 1. Demand (EDP) distribution Describe the uncertainty in the demands. Unlike other random variables, the EDPs are characterized by the EDP input data provided earlier. All EDPs are handled in one multivariate lognormal distribution. If more than one sample is provided, the distribution is fit to the EDP data. Otherwise, the provided data point is assumed to be the median value and the additional uncertainty prescribed describes the dispersion. See _create_RV_demands() for more details. 2. Component quantities Describe the uncertainty in the quantity of components in each Performance Group. All Fragility Groups are handled in the same multivariate distribution. Consequently, correlation between various groups of component quantities can be specified. See _create_RV_quantities() for details. 3. Fragility EDP limits Describe the uncertainty in the EDP limit that corresponds to exceedance of each Damage State. EDP limits are grouped by Fragility Groups. Consequently, correlation between fragility limits are currently are limited within Fragility Groups. See _create_RV_fragilities() for details. 4. Reconstruction cost and time Describe the uncertainty in the cost and duration of reconstruction of each component conditioned on the damage state of the component. All Fragility Groups are handled in the same multivariate distribution. Consequently, correlation between various groups of component reconstruction time and cost estimates can be specified. See _create_RV_repairs() for details. 5. Damaged component proportions that trigger a red tag Describe the uncertainty in the amount of damaged components needed to trigger a red tag for the building. All Fragility Groups are handled in the same multivariate distribution. Consequently, correlation between various groups of component proportion limits can be specified. See _create_RV_red_tags() for details. 6. Injuries Describe the uncertainty in the proportion of people in the affected area getting injuries exceeding a certain level of severity. FEMA P58 uses two severity levels: injury and fatality. Both levels for all Fragility Groups are handled in the same multivariate distribution. Consequently, correlation between various groups of component injury expectations can be specified. See _create_RV_injuries() for details. """ super(FEMA_P58_Assessment, self).define_random_variables() # create the random variables ----------------------------------------- DEP = self._AIM_in['dependencies'] self._RV_dict = {} # quantities 100 self._RV_dict.update({'QNT': self._create_RV_quantities(DEP['quantities'])}) # fragilities 300 s_fg_keys = sorted(self._FG_in.keys()) for c_id, c_name in enumerate(s_fg_keys): comp = self._FG_in[c_name] self._RV_dict.update({ 'FR-' + c_name: self._create_RV_fragilities(c_id, comp, DEP['fragilities'])}) # consequences 400 DVs = self._AIM_in['decision_variables'] if DVs['red_tag']: self._RV_dict.update({'DV_RED': self._create_RV_red_tags(DEP['red_tags'])}) if DVs['rec_time'] or DVs['rec_cost']: self._RV_dict.update({'DV_REP': self._create_RV_repairs( DEP['rec_costs'], DEP['rec_times'], DEP['cost_and_time'])}) if DVs['injuries']: self._RV_dict.update({'DV_INJ': self._create_RV_injuries( DEP['injuries'], DEP['injury_lvls'])}) # demands 200 self._RV_dict.update({'EDP': self._create_RV_demands( self.beta_additional)}) # sample the random variables ----------------------------------------- s_rv_keys = sorted(self._RV_dict.keys()) for r_i in s_rv_keys: rv = self._RV_dict[r_i] if rv is not None: rv.sample_distribution(self._AIM_in['general']['realizations']) def define_loss_model(self): """ Create the stochastic loss model based on the inputs provided earlier. Following the FEMA P58 methodology, the components specified in the Damage and Loss input file are used to create Fragility Groups. Each Fragility Group corresponds to a component that might be present in the building at several locations. See _create_fragility_groups() for more details about the creation of Fragility Groups. """ super(FEMA_P58_Assessment, self).define_loss_model() # fragility groups self._FG_dict = self._create_fragility_groups() # demands self._EDP_dict = dict( [(tag, RandomVariableSubset(self._RV_dict['EDP'],tags=tag)) for tag in self._RV_dict['EDP']._dimension_tags]) def calculate_damage(self): """ Characterize the damage experienced in each random event realization. First, the time of the event (month, weekday/weekend, hour) is randomly generated for each realization. Given the event time, the number of people present at each floor of the building is calculated. Second, the realizations that led to collapse are filtered. See _calc_collapses() for more details on collapse estimation. Finally, the realizations that did not lead to building collapse are further investigated and the quantities of components in each damage state are estimated. See _calc_damage() for more details on damage estimation. """ super(FEMA_P58_Assessment, self).calculate_damage() # event time - month, weekday, and hour realizations self._TIME = self._sample_event_time() # get the population conditioned on event time self._POP = self._get_population() # collapses self._COL, collapsed_IDs = self._calc_collapses() self._ID_dict.update({'collapse':collapsed_IDs}) # select the non-collapse cases for further analyses non_collapsed_IDs = self._POP[ ~self._POP.index.isin(collapsed_IDs)].index.values.astype(int) self._ID_dict.update({'non-collapse': non_collapsed_IDs}) # damage in non-collapses self._DMG = self._calc_damage() def calculate_losses(self): """ Characterize the consequences of damage in each random event realization. For the sake of efficiency, only the decision variables requested in the input file are estimated. The following consequences are handled by this method: Reconstruction time and cost Estimate the irrepairable cases based on residual drift magnitude and the provided irrepairable drift limits. Realizations that led to irrepairable damage or collapse are assigned the replacement cost and time of the building when reconstruction cost and time is estimated. Repairable cases get a cost and time estimate for each Damage State in each Performance Group. For more information about estimating irrepairability see _calc_irrepairable() and reconstruction cost and time see _calc_repair_cost_and_time() methods. Injuries Collapse-induced injuries are based on the collapse modes and corresponding injury characterization. Injuries conditioned on no collapse are based on the affected area and the probability of injuries of various severity specified in the component data file. For more information about estimating injuries conditioned on collapse and no collapse, see _calc_collapse_injuries() and _calc_non_collapse_injuries, respecitvely. Red Tag The probability of getting an unsafe placard or red tag is a function of the amount of damage experienced in various Damage States for each Performance Group. The damage limits that trigger an unsafe placard are specified in the component data file. For more information on assigning red tags to realizations see the _calc_red_tag() method. """ super(FEMA_P58_Assessment, self).calculate_losses() DVs = self._AIM_in['decision_variables'] # red tag probability if DVs['red_tag']: DV_RED = self._calc_red_tag() self._DV_dict.update({'red_tag': DV_RED}) # reconstruction cost and time if DVs['rec_cost'] or DVs['rec_time']: # irrepairable cases irrepairable_IDs = self._calc_irrepairable() # collect the IDs of repairable realizations P_NC = self._POP.loc[self._ID_dict['non-collapse']] repairable_IDs = P_NC[ ~P_NC.index.isin(irrepairable_IDs)].index.values.astype(int) self._ID_dict.update({'repairable': repairable_IDs}) self._ID_dict.update({'irrepairable': irrepairable_IDs}) # reconstruction cost and time for repairable cases DV_COST, DV_TIME = self._calc_repair_cost_and_time() self._DV_dict.update({ 'rec_cost': DV_COST, 'rec_time': DV_TIME, }) # injuries due to collapse if DVs['injuries']: COL_INJ = self._calc_collapse_injuries() # injuries in non-collapsed cases DV_INJ_dict = self._calc_non_collapse_injuries() # store results if COL_INJ is not None: self._COL = pd.concat([self._COL, COL_INJ], axis=1) self._DV_dict.update({'injuries': DV_INJ_dict}) def aggregate_results(self): """ Returns ------- """ DVs = self._AIM_in['decision_variables'] MI_raw = [ ('event time', 'month'), ('event time', 'weekday?'), ('event time', 'hour'), ('inhabitants', ''), ('collapses', 'collapsed?'), ('collapses', 'mode'), ('red tagged?', ''), ('reconstruction', 'irrepairable?'), ('reconstruction', 'cost impractical?'), ('reconstruction', 'cost'), ('reconstruction', 'time impractical?'), ('reconstruction', 'time-sequential'), ('reconstruction', 'time-parallel'), ('injuries', 'casualties'), ('injuries', 'fatalities'), ] ncID = self._ID_dict['non-collapse'] colID = self._ID_dict['collapse'] if DVs['rec_cost'] or DVs['rec_time']: repID = self._ID_dict['repairable'] irID = self._ID_dict['irrepairable'] MI = pd.MultiIndex.from_tuples(MI_raw) SUMMARY = pd.DataFrame(np.empty(( self._AIM_in['general']['realizations'], len(MI))), columns=MI) SUMMARY[:] = np.NaN # event time for prop in ['month', 'weekday?', 'hour']: offset = 0 if prop == 'month': offset = 1 SUMMARY.loc[:, ('event time', prop)] = \ self._TIME.loc[:, prop] + offset # inhabitants SUMMARY.loc[:, ('inhabitants', '')] = self._POP.sum(axis=1) # collapses SUMMARY.loc[:, ('collapses', 'collapsed?')] = self._COL.iloc[:, 0] # red tag if DVs['red_tag']: SUMMARY.loc[ncID, ('red tagged?', '')] = \ self._DV_dict['red_tag'].max(axis=1) # reconstruction cost if DVs['rec_cost']: SUMMARY.loc[ncID, ('reconstruction', 'cost')] = \ self._DV_dict['rec_cost'].sum(axis=1) repl_cost = self._AIM_in['general']['replacement_cost'] SUMMARY.loc[colID, ('reconstruction', 'cost')] = repl_cost if DVs['rec_cost'] or DVs['rec_time']: SUMMARY.loc[ncID, ('reconstruction', 'irrepairable?')] = 0 SUMMARY.loc[irID, ('reconstruction', 'irrepairable?')] = 1 if DVs['rec_cost']: SUMMARY.loc[irID, ('reconstruction', 'cost')] = repl_cost repair_impractical_IDs = SUMMARY.loc[ SUMMARY.loc[:, ('reconstruction', 'cost')] > repl_cost].index SUMMARY.loc[repID, ('reconstruction', 'cost impractical?')] = 0 SUMMARY.loc[repair_impractical_IDs, ('reconstruction', 'cost impractical?')] = 1 SUMMARY.loc[ repair_impractical_IDs, ('reconstruction', 'cost')] = repl_cost # reconstruction time if DVs['rec_time']: SUMMARY.loc[ncID, ('reconstruction', 'time-sequential')] = \ self._DV_dict['rec_time'].sum(axis=1) SUMMARY.loc[ncID, ('reconstruction', 'time-parallel')] = \ self._DV_dict['rec_time'].max(axis=1) rep_time = self._AIM_in['general']['replacement_time'] for t_label in ['time-sequential', 'time-parallel']: SUMMARY.loc[colID, ('reconstruction', t_label)] = rep_time SUMMARY.loc[irID, ('reconstruction', t_label)] = rep_time repair_impractical_IDs = \ SUMMARY.loc[SUMMARY.loc[:, ('reconstruction', 'time-parallel')] > rep_time].index SUMMARY.loc[repID, ('reconstruction', 'time impractical?')] = 0 SUMMARY.loc[repair_impractical_IDs,('reconstruction', 'time impractical?')] = 1 SUMMARY.loc[repair_impractical_IDs, ('reconstruction', 'time-parallel')] = rep_time # injuries if DVs['injuries']: if 'CM' in self._COL.columns: SUMMARY.loc[colID, ('collapses', 'mode')] = self._COL.loc[:, 'CM'] SUMMARY.loc[colID, ('injuries', 'casualties')] = \ self._COL.loc[:, 'INJ-0'] SUMMARY.loc[colID, ('injuries', 'fatalities')] = \ self._COL.loc[:, 'INJ-1'] SUMMARY.loc[ncID, ('injuries', 'casualties')] = \ self._DV_dict['injuries'][0].sum(axis=1) SUMMARY.loc[ncID, ('injuries', 'fatalities')] = \ self._DV_dict['injuries'][1].sum(axis=1) self._SUMMARY = SUMMARY.dropna(axis=1,how='all') def write_outputs(self): """ Returns ------- """ super(FEMA_P58_Assessment, self).write_outputs() def _create_correlation_matrix(self, rho_target, c_target=-1, include_CSG=False, include_DSG=False, include_DS=False): """ Parameters ---------- rho_target c_target include_CSG include_DSG include_DS Returns ------- """ # set the correlation structure rho_FG, rho_PG, rho_LOC, rho_DIR, rho_CSG, rho_DS = np.zeros(6) if rho_target in ['FG', 'PG', 'DIR', 'LOC', 'CSG', 'ATC', 'DS']: rho_DS = 1.0 if rho_target in ['FG', 'PG', 'DIR', 'LOC', 'CSG']: rho_CSG = 1.0 if rho_target in ['FG', 'PG', 'DIR']: rho_DIR = 1.0 if rho_target in ['FG', 'PG', 'LOC']: rho_LOC = 1.0 if rho_target in ['FG', 'PG']: rho_PG = 1.0 if rho_target == 'FG': rho_FG = 1.0 L_D_list = [] dims = [] DS_list = [] ATC_rho = [] s_fg_keys = sorted(self._FG_in.keys()) for c_id, c_name in enumerate(s_fg_keys): comp = self._FG_in[c_name] if ((c_target == -1) or (c_id == c_target)): c_L_D_list = [] c_DS_list = [] ATC_rho.append(comp['correlation']) if include_DSG: DS_count = 0 s_dsg_keys = sorted(comp['DSG_set'].keys()) for dsg_i in s_dsg_keys: DSG = comp['DSG_set'][dsg_i] if include_DS: DS_count += len(DSG['DS_set']) else: DS_count += 1 else: DS_count = 1 for loc in comp['locations']: if include_CSG: u_dirs = comp['directions'] else: u_dirs = np.unique(comp['directions']) c_L_D_list.append([]) for dir_ in u_dirs: c_DS_list.append(DS_count) for ds_i in range(DS_count): c_L_D_list[-1].append(dir_) c_dims = sum([len(loc) for loc in c_L_D_list]) dims.append(c_dims) L_D_list.append(c_L_D_list) DS_list.append(c_DS_list) rho = np.ones((sum(dims), sum(dims))) * rho_FG f_pos_id = 0 for c_id, (c_L_D_list, c_dims, c_DS_list) in enumerate( zip(L_D_list, dims, DS_list)): c_rho = np.ones((c_dims, c_dims)) * rho_PG # dependencies btw directions if rho_DIR != 0: c_pos_id = 0 for loc_D_list in c_L_D_list: l_dim = len(loc_D_list) c_rho[c_pos_id:c_pos_id + l_dim, c_pos_id:c_pos_id + l_dim] = rho_DIR c_pos_id = c_pos_id + l_dim # dependencies btw locations if rho_LOC != 0: flat_dirs = [] [[flat_dirs.append(dir_i) for dir_i in dirs] for dirs in c_L_D_list] flat_dirs = np.array(flat_dirs) for u_dir in np.unique(flat_dirs): dir_ids = np.where(flat_dirs == u_dir)[0] for i in dir_ids: for j in dir_ids: c_rho[i, j] = rho_LOC if ((rho_CSG != 0) or (rho_target == 'ATC')): c_pos_id = 0 if rho_target == 'ATC': rho_to_use = float(ATC_rho[c_id]) else: rho_to_use = rho_CSG for loc_D_list in c_L_D_list: flat_dirs = np.array(loc_D_list) for u_dir in np.unique(flat_dirs): dir_ids = np.where(flat_dirs == u_dir)[0] for i in dir_ids: for j in dir_ids: c_rho[c_pos_id + i, c_pos_id + j] = rho_to_use c_pos_id = c_pos_id + len(loc_D_list) if rho_DS != 0: c_pos_id = 0 for l_dim in c_DS_list: c_rho[c_pos_id:c_pos_id + l_dim, c_pos_id:c_pos_id + l_dim] = rho_DS c_pos_id = c_pos_id + l_dim rho[f_pos_id:f_pos_id + c_dims, f_pos_id:f_pos_id + c_dims] = c_rho f_pos_id = f_pos_id + c_dims np.fill_diagonal(rho, 1.0) return rho def _create_RV_quantities(self, rho_qnt): """ Parameters ---------- rho_qnt Returns ------- """ q_theta, q_sig, q_tag, q_dist = [np.array([]) for i in range(4)] # collect the parameters for each quantity dimension s_fg_keys = sorted(self._FG_in.keys()) for c_id in s_fg_keys: comp = self._FG_in[c_id] u_dirs = np.unique(comp['directions']) dir_weights = comp['dir_weights'] theta_list = [] [[theta_list.append(qnt * dw) for dw in dir_weights] for qnt in comp['quantities']] q_theta = np.append(q_theta, theta_list) if comp['distribution_kind'] == 'normal': q_sig = np.append(q_sig, ( comp['cov'] * np.asarray(theta_list)).tolist()) else: q_sig = np.append(q_sig, ( np.ones(len(theta_list)) * comp['cov']).tolist()) q_tag = np.append(q_tag, [[c_id + '-QNT-' + str(s_i) + '-' + str(d_i) for d_i in u_dirs] for s_i in comp['locations']]) q_dist = np.append(q_dist, [[comp['distribution_kind'] for d_i in u_dirs] for s_i in comp['locations']]) dims = len(q_theta) rho = self._create_correlation_matrix(rho_qnt) q_COV = np.outer(q_sig, q_sig) * rho # add lower limits to ensure only positive quantities # zero is probably too low, and it might make sense to introduce upper # limits as well tr_lower = [0. for d in range(dims)] tr_upper = [None for d in range(dims)] # to avoid truncations affecting other dimensions when rho_QNT is large, # assign a post-truncation correlation structure corr_ref = 'post' # create a random variable for component quantities in performance groups if q_tag.size > 0: quantity_RV = RandomVariable(ID=100, dimension_tags=q_tag, distribution_kind=q_dist, theta=q_theta, COV=q_COV, truncation_limits=[tr_lower, tr_upper], corr_ref=corr_ref) else: quantity_RV = None return quantity_RV def _create_RV_fragilities(self, c_id, comp, rho_fr): """ Parameters ---------- c_id comp rho_fr Returns ------- """ # prepare the basic multivariate distribution data for one component subgroup considering all damage states d_theta, d_sig, d_tag = [np.array([]) for i in range(3)] s_dsg_keys = sorted(comp['DSG_set'].keys()) for d_id in s_dsg_keys: DSG = comp['DSG_set'][d_id] d_theta = np.append(d_theta, DSG['theta']) d_sig = np.append(d_sig, DSG['sig']) d_tag = np.append(d_tag, comp['ID'] + '-' + str(d_id)) dims = len(d_theta) # get the total number of random variables for this fragility group rv_count = len(comp['locations']) * len(comp['directions']) * dims # create the (empty) input arrays for the RV c_theta = np.zeros(rv_count) c_tag = np.empty(rv_count, dtype=object) c_sig = np.zeros(rv_count) pos_id = 0 for l_id in comp['locations']: # for each location-direction pair) for d_id, __ in enumerate(comp['directions']): # for each component-subgroup c_theta[pos_id:pos_id + dims] = d_theta c_sig[pos_id:pos_id + dims] = d_sig c_tag[pos_id:pos_id + dims] = [ t + '-LOC-{}-CSG-{}'.format(l_id, d_id) for t in d_tag] pos_id += dims # create the covariance matrix c_rho = self._create_correlation_matrix(rho_fr, c_target=c_id, include_DSG=True, include_CSG=True) c_COV = np.outer(c_sig, c_sig) * c_rho if c_tag.size > 0: fragility_RV = RandomVariable(ID=300 + c_id, dimension_tags=c_tag, distribution_kind='lognormal', theta=c_theta, COV=c_COV) else: fragility_RV = None return fragility_RV def _create_RV_red_tags(self, rho_target): f_theta, f_sig, f_tag = [np.array([]) for i in range(3)] s_fg_keys = sorted(self._FG_in.keys()) for c_id, c_name in enumerate(s_fg_keys): comp = self._FG_in[c_name] d_theta, d_sig, d_tag = [np.array([]) for i in range(3)] s_dsg_keys = sorted(comp['DSG_set'].keys()) for dsg_i in s_dsg_keys: DSG = comp['DSG_set'][dsg_i] s_ds_keys = sorted(DSG['DS_set'].keys()) for ds_i in s_ds_keys: DS = DSG['DS_set'][ds_i] theta = DS['red_tag']['theta'] d_theta = np.append(d_theta, theta) d_sig = np.append(d_sig, DS['red_tag']['cov']) d_tag = np.append(d_tag, comp['ID'] + '-' + str(dsg_i) + '-' + str( ds_i)) for loc in comp['locations']: for dir_ in np.unique(comp['directions']): f_theta = np.append(f_theta, d_theta) f_sig = np.append(f_sig, d_sig) f_tag = np.append(f_tag, [t + '-LOC-{}-DIR-{}'.format(loc, dir_) for t in d_tag]) rho = self._create_correlation_matrix(rho_target, c_target=-1, include_DSG=True, include_DS=True) # remove the unnecessary fields to_remove = np.where(f_theta == 0)[0] rho = np.delete(rho, to_remove, axis=0) rho = np.delete(rho, to_remove, axis=1) f_theta, f_sig, f_tag = [np.delete(f_vals, to_remove) for f_vals in [f_theta, f_sig, f_tag]] f_COV = np.outer(f_sig, f_sig) * rho tr_upper = 1. + (1. - f_theta) / f_theta if f_tag.size > 0: red_tag_RV = RandomVariable(ID=400, dimension_tags=f_tag, distribution_kind='normal', theta=np.ones(len(f_theta)), COV=f_COV, corr_ref='post', truncation_limits=[np.zeros(len(f_theta)), tr_upper]) else: red_tag_RV = None return red_tag_RV def _create_RV_repairs(self, rho_cost, rho_time, rho_cNt): # prepare the cost and time parts of the data separately ct_sig, ct_tag, ct_dkind = [np.array([]) for i in range(3)] for rho_target, name in zip([rho_cost, rho_time], ['cost', 'time']): f_sig, f_tag, f_dkind = [np.array([]) for i in range(3)] s_fg_keys = sorted(self._FG_in.keys()) for c_id, c_name in enumerate(s_fg_keys): comp = self._FG_in[c_name] d_sig, d_tag, d_dkind = [np.array([]) for i in range(3)] s_dsg_keys = sorted(comp['DSG_set'].keys()) for dsg_i in s_dsg_keys: DSG = comp['DSG_set'][dsg_i] s_ds_keys = sorted(DSG['DS_set'].keys()) for ds_i in s_ds_keys: DS = DSG['DS_set'][ds_i] d_sig = np.append(d_sig, DS['repair_{}'.format(name)]['cov']) d_dkind = np.append(d_dkind, DS['repair_{}'.format(name)][ 'distribution_kind']) d_tag = np.append(d_tag, comp['ID'] + '-' + str( dsg_i) + '-' + str( ds_i) + '-{}'.format(name)) for loc in comp['locations']: for dir_ in np.unique(comp['directions']): f_sig = np.append(f_sig, d_sig) f_dkind = np.append(f_dkind, d_dkind) f_tag = np.append(f_tag, [t + '-LOC-{}-DIR-{}'.format(loc, dir_) for t in d_tag]) ct_sig = np.append(ct_sig, f_sig) ct_tag = np.append(ct_tag, f_tag) ct_dkind = np.append(ct_dkind, f_dkind) rho_c = self._create_correlation_matrix(rho_cost, c_target=-1, include_DSG=True, include_DS=True) rho_t = self._create_correlation_matrix(rho_time, c_target=-1, include_DSG=True, include_DS=True) dims = len(ct_tag) ct_rho = np.zeros((dims, dims)) dims = dims // 2 if rho_cNt == False: ct_rho[:dims, :dims] = rho_c ct_rho[dims:, dims:] = rho_t else: # if correlation between cost and time is considered, then the # envelope of rho_c and rho_t shall be applied rho_ct = np.maximum(rho_c, rho_t) ct_rho[:dims, :dims] = rho_ct ct_rho[dims:, dims:] = rho_ct # apply the same blocks to the off-diagonal positions ct_rho[:dims, dims:] = rho_ct ct_rho[dims:, :dims] = rho_ct ct_COV = np.outer(ct_sig, ct_sig) * ct_rho if ct_tag.size > 0: repair_RV = RandomVariable(ID=401, dimension_tags=ct_tag, distribution_kind=ct_dkind, theta=np.ones(len(ct_sig)), COV=ct_COV, corr_ref='post', truncation_limits=[np.zeros(len(ct_sig)), None]) else: repair_RV = None return repair_RV def _create_RV_injuries(self, rho_target, rho_lvls): inj_lvls = self._inj_lvls # prepare the cost and time parts of the data separately full_theta, full_sig, full_tag = [np.array([]) for i in range(3)] for i_lvl in range(inj_lvls): f_theta, f_sig, f_tag = [np.array([]) for i in range(3)] s_fg_keys = sorted(self._FG_in.keys()) for c_id, c_name in enumerate(s_fg_keys): comp = self._FG_in[c_name] d_theta, d_sig, d_tag = [np.array([]) for i in range(3)] s_dsg_keys = sorted(comp['DSG_set'].keys()) for dsg_i in s_dsg_keys: DSG = comp['DSG_set'][dsg_i] s_ds_keys = sorted(DSG['DS_set'].keys()) for ds_i in s_ds_keys: DS = DSG['DS_set'][ds_i] d_theta = np.append(d_theta, DS['injuries']['theta'][i_lvl]) d_sig = np.append(d_sig, DS['injuries']['cov'][i_lvl]) d_tag = np.append(d_tag, comp['ID'] + '-' + str( dsg_i) + '-' + str( ds_i) + '-{}'.format(i_lvl)) for loc in comp['locations']: for dir_ in np.unique(comp['directions']): f_theta = np.append(f_theta, d_theta) f_sig = np.append(f_sig, d_sig) f_tag = np.append(f_tag, [t + '-LOC-{}-DIR-{}'.format(loc, dir_) for t in d_tag]) full_theta = np.append(full_theta, f_theta) full_sig = np.append(full_sig, f_sig) full_tag = np.append(full_tag, f_tag) dims = len(full_tag) full_rho = np.zeros((dims, dims)) dims = dims // inj_lvls # if correlation between different levels of severity is considered, add that to the matrix if rho_lvls: rho_i = self._create_correlation_matrix(rho_target, c_target=-1, include_DSG=True, include_DS=True) for i in range(inj_lvls): for j in range(inj_lvls): full_rho[i * dims:(i + 1) * dims, j * dims:(j + 1) * dims] = rho_i # and now add the values around the main diagonal for i in range(inj_lvls): rho_i = self._create_correlation_matrix(rho_target, c_target=-1, include_DSG=True, include_DS=True) full_rho[i * dims:(i + 1) * dims, i * dims:(i + 1) * dims] = rho_i # finally, remove the unnecessary lines to_remove = np.where(full_theta == 0)[0] full_rho = np.delete(full_rho, to_remove, axis=0) full_rho = np.delete(full_rho, to_remove, axis=1) full_theta, full_sig, full_tag = [np.delete(f_vals, to_remove) for f_vals in [full_theta, full_sig, full_tag]] full_COV = np.outer(full_sig, full_sig) * full_rho tr_upper = 1. + (1. - full_theta) / full_theta if full_tag.size > 0: injury_RV = RandomVariable(ID=402, dimension_tags=full_tag, distribution_kind='normal', theta=np.ones(len(full_sig)), COV=full_COV, corr_ref='post', truncation_limits=[np.zeros(len(full_sig)), tr_upper]) else: injury_RV = None return injury_RV def _create_RV_demands(self, beta_added): # unlike other random variables, the demand RV is based on raw data # first, collect the raw values from the EDP dict demand_data = [] d_tags = [] detection_limits = [] s_edp_keys = sorted(self._EDP_in.keys()) for d_id in s_edp_keys: d_list = self._EDP_in[d_id] for i in range(len(d_list)): demand_data.append(d_list[i]['raw_data']) d_tags.append(str(d_id) + '-LOC-' + str(d_list[i]['location']) + '-DIR-' + str(d_list[i]['direction'])) det_lim = self._AIM_in['general']['detection_limits'][d_id] if det_lim is None: det_lim = np.inf detection_limits.append([0., det_lim]) detection_limits = np.transpose(np.asarray(detection_limits)) demand_data = np.transpose(np.asarray(demand_data)) # if more than one sample is provided if demand_data.shape[0] > 1: # get the number of censored samples EDP_filter = np.all([np.all(demand_data > detection_limits[0], axis=1), np.all(demand_data < detection_limits[1], axis=1)], axis=0) censored_count = len(EDP_filter) - sum(EDP_filter) demand_data = demand_data[EDP_filter] demand_data = np.transpose(demand_data) # create the random variable demand_RV = RandomVariable(ID=200, dimension_tags=d_tags, raw_data=demand_data, detection_limits=detection_limits, censored_count=censored_count ) # fit a multivariate lognormal distribution to the censored raw data demand_RV.fit_distribution('lognormal') else: # Since we only have one data point, the best we can do is assume # it is the median of the multivariate distribution. The dispersion # is assumed to be negligible. dim = len(demand_data[0]) if dim > 1: sig = np.ones(dim)*1e-4 rho = np.zeros((dim,dim)) np.fill_diagonal(rho, 1.0) COV = np.outer(sig,sig) * rho else: COV = np.asarray((1e-4)**2.) demand_RV = RandomVariable(ID=200, dimension_tags=d_tags, distribution_kind='lognormal', theta=demand_data[0], COV=COV) # if we want to add other sources of uncertainty, we will need to # redefine the random variable if beta_added > 0.: # get the covariance matrix with added uncertainty COV_orig = demand_RV.COV if COV_orig.shape is not (): sig_orig = np.sqrt(np.diagonal(COV_orig)) rho_orig = COV_orig / np.outer(sig_orig, sig_orig) sig_mod = np.sqrt(sig_orig ** 2. + beta_added ** 2.) COV_mod = np.outer(sig_mod, sig_mod) * rho_orig else: COV_mod = np.sqrt(COV_orig**2. + beta_added**2.) # redefine the random variable demand_RV = RandomVariable(ID=200, dimension_tags=demand_RV.dimension_tags, distribution_kind='lognormal', theta=demand_RV.theta, COV=COV_mod) return demand_RV def _create_fragility_groups(self): RVd = self._RV_dict DVs = self._AIM_in['decision_variables'] # create a list for the fragility groups FG_dict = dict() s_fg_keys = sorted(self._FG_in.keys()) for c_id in s_fg_keys: comp = self._FG_in[c_id] FG_ID = len(FG_dict.keys()) # create a list for the performance groups performance_groups = [] # one group for each of the stories prescribed by the user PG_locations = comp['locations'] PG_directions = np.unique(comp['directions']) for loc in PG_locations: for dir_ in PG_directions: PG_ID = 1000 + dir_*100 + FG_ID * 10 + loc # get the quantity QNT = RandomVariableSubset( RVd['QNT'], tags=[c_id + '-QNT-' + str(loc) + '-' + str(dir_), ]) # create the damage objects # consequences are calculated on a performance group level # create a list for the damage state groups and their tags DSG_list = [] d_tags = [] s_dsg_keys = sorted(comp['DSG_set'].keys()) for dsg_i, DSG_ID in enumerate(s_dsg_keys): DSG = comp['DSG_set'][DSG_ID] d_tags.append(c_id + '-' + DSG_ID) # create a list for the damage states DS_set = [] s_ds_keys = sorted(DSG['DS_set'].keys()) for ds_i, DS_ID in enumerate(s_ds_keys): DS = DSG['DS_set'][DS_ID] # create the consequence functions if DVs['rec_cost']: data = DS['repair_cost'] f_median = prep_bounded_linear_median_DV( **{k: data.get(k, None) for k in ('median_max', 'median_min', 'quantity_lower', 'quantity_upper')}) cf_tag = c_id + '-' + DSG_ID + '-' + DS_ID + \ '-cost' + \ '-LOC-{}-DIR-{}'.format(loc, dir_) CF_RV = RandomVariableSubset(RVd['DV_REP'], tags=cf_tag) CF_cost = ConsequenceFunction(DV_median=f_median, DV_distribution=CF_RV) else: CF_cost = None if DVs['rec_time']: data = DS['repair_time'] f_median = prep_bounded_linear_median_DV( **{k: data.get(k, None) for k in ('median_max', 'median_min', 'quantity_lower', 'quantity_upper')}) cf_tag = c_id + '-' + DSG_ID + '-' + DS_ID + \ '-time' + \ '-LOC-{}-DIR-{}'.format(loc, dir_) CF_RV = RandomVariableSubset(RVd['DV_REP'], tags=cf_tag) CF_time = ConsequenceFunction(DV_median=f_median, DV_distribution=CF_RV) else: CF_time = None if DVs['red_tag']: data = DS['red_tag'] if data['theta'] > 0: f_median = prep_constant_median_DV(data['theta']) cf_tag = c_id + '-' + DSG_ID + '-' + DS_ID + \ '-LOC-{}-DIR-{}'.format(loc, dir_) CF_RV = RandomVariableSubset(RVd['DV_RED'], tags=cf_tag) CF_red_tag = ConsequenceFunction(DV_median=f_median, DV_distribution=CF_RV) else: CF_red_tag = None else: CF_red_tag = None if DVs['injuries']: data = DS['injuries'] CF_inj_set = [] for inj_i, theta in enumerate(data['theta']): if theta > 0.: f_median = prep_constant_median_DV(theta) cf_tag = c_id + '-' + DSG_ID + '-' + DS_ID + \ '-{}-LOC-{}-DIR-{}'.format(inj_i, loc, dir_) CF_RV = RandomVariableSubset(RVd['DV_INJ'], tags=cf_tag) CF_inj_set.append(ConsequenceFunction( DV_median=f_median, DV_distribution=CF_RV)) else: CF_inj_set.append(None) else: CF_inj_set = [None,] # add the DS to the list DS_set.append(DamageState(ID=ds_i + 1, description=DS['description'], weight=DS['weight'], affected_area=DS[ 'affected_area'], repair_cost_CF=CF_cost, reconstruction_time_CF=CF_time, red_tag_CF=CF_red_tag, injuries_CF_set=CF_inj_set )) # add the DSG to the list DSG_list.append(DamageStateGroup(ID=dsg_i + 1, DS_set=DS_set, DS_set_kind=DSG[ 'DS_set_kind'], description=DSG[ 'description'] )) # create the fragility functions FF_set = [] CSG_this = np.where(comp['directions']==dir_)[0] PG_weights = np.asarray(comp['csg_weights'])[CSG_this] # normalize the weights PG_weights /= sum(PG_weights) for csg_id in CSG_this: # assign the appropriate random variable to the fragility # function ff_tags = [t + '-LOC-{}-CSG-{}'.format(loc, csg_id) for t in d_tags] EDP_limit = RandomVariableSubset(RVd['FR-' + c_id], tags=ff_tags) FF_set.append(FragilityFunction(EDP_limit)) # create the performance group PG = PerformanceGroup(ID=PG_ID, location=loc, quantity=QNT, fragility_functions=FF_set, DSG_set=DSG_list, csg_weights=PG_weights, direction=dir_ ) performance_groups.append(PG) # create the fragility group FG = FragilityGroup(ID=FG_ID, kind=comp['kind'], demand_type=comp['demand_type'], performance_groups=performance_groups, directional=comp['directional'], correlation=comp['correlation'], demand_location_offset=comp['offset'], incomplete=comp['incomplete'], name=str(FG_ID) + ' - ' + comp['ID'], description=comp['description'] ) FG_dict.update({comp['ID']:FG}) return FG_dict def _sample_event_time(self): sample_count = self._AIM_in['general']['realizations'] # month - uniform distribution over [0,11] month = np.random.randint(0, 12, size=sample_count) # weekday - binomial with p=5/7 weekday = np.random.binomial(1, 5. / 7., size=sample_count) # hour - uniform distribution over [0,23] hour = np.random.randint(0, 24, size=sample_count) data = pd.DataFrame(data={'month' : month, 'weekday?': weekday, 'hour' : hour}, dtype=int) return data def _get_population(self): """ Use the population characteristics to generate random population samples. Returns ------- """ POPin = self._POP_in TIME = self._TIME POP = pd.DataFrame( np.ones((len(TIME.index), len(POPin['peak']))) * POPin['peak'], columns=['LOC' + str(loc + 1) for loc in range(len(POPin['peak']))]) weekdays = TIME[TIME['weekday?'] == 1].index weekends = TIME[~TIME.index.isin(weekdays)].index for col in POP.columns.values: POP.loc[weekdays, col] = ( POP.loc[weekdays, col] * np.array(POPin['weekday']['daily'])[ TIME.loc[weekdays, 'hour'].values.astype(int)] * np.array(POPin['weekday']['monthly'])[ TIME.loc[weekdays, 'month'].values.astype(int)]) POP.loc[weekends, col] = ( POP.loc[weekends, col] * np.array(POPin['weekend']['daily'])[ TIME.loc[weekends, 'hour'].values.astype(int)] * np.array(POPin['weekend']['monthly'])[ TIME.loc[weekends, 'month'].values.astype(int)]) return POP def _calc_collapses(self): # filter the collapsed cases based on the demand samples collapsed_IDs = np.array([]) s_edp_keys = sorted(self._EDP_dict.keys()) for demand_ID in s_edp_keys: demand = self._EDP_dict[demand_ID] coll_df = pd.DataFrame() kind = demand_ID[:3] collapse_limit = self._AIM_in['general']['collapse_limits'][kind] if collapse_limit is not None: EDP_samples = demand.samples coll_df = EDP_samples[EDP_samples > collapse_limit] collapsed_IDs = np.concatenate( (collapsed_IDs, coll_df.index.values)) # get a list of IDs of the collapsed cases collapsed_IDs = np.unique(collapsed_IDs).astype(int) COL = pd.DataFrame(np.zeros(self._AIM_in['general']['realizations']), columns=['COL', ]) COL.loc[collapsed_IDs, 'COL'] = 1 return COL, collapsed_IDs def _calc_damage(self): ncID = self._ID_dict['non-collapse'] NC_samples = len(ncID) DMG = pd.DataFrame() s_fg_keys = sorted(self._FG_dict.keys()) for fg_id in s_fg_keys: FG = self._FG_dict[fg_id] PG_set = FG._performance_groups DS_list = [] for DSG in PG_set[0]._DSG_set: for DS in DSG._DS_set: DS_list.append(str(DSG._ID) + '-' + str(DS._ID)) d_count = len(DS_list) MI = pd.MultiIndex.from_product([[FG._ID, ], [pg._ID for pg in PG_set], DS_list], names=['FG', 'PG', 'DS']) FG_damages = pd.DataFrame(np.zeros((NC_samples, len(MI))), columns=MI, index=ncID) for pg_i, PG in enumerate(PG_set): PG_ID = PG._ID PG_qnt = PG._quantity.samples.loc[ncID] # get the corresponding demands demand_ID = (FG._demand_type + '-LOC-' + str(PG._location) + '-DIR-' + str(PG._direction+1)) if demand_ID in self._EDP_dict.keys(): EDP_samples = self._EDP_dict[demand_ID].samples.loc[ncID] else: # If the required demand is not available, then we are most # likely analyzing a 3D structure using results from a 2D # simulation. The best thing we can do in that particular # case is to use the EDP from the 0 direction for all other # directions. demand_ID = (FG._demand_type + '-LOC-' + str(PG._location) + '-DIR-1') EDP_samples = self._EDP_dict[demand_ID].samples.loc[ncID] csg_w_list = PG._csg_weights for csg_i, csg_w in enumerate(csg_w_list): DSG_df = PG._FF_set[csg_i].DSG_given_EDP(EDP_samples) for DSG in PG._DSG_set: in_this_DSG = DSG_df[DSG_df.values == DSG._ID].index if DSG._DS_set_kind == 'single': DS = DSG._DS_set[0] DS_tag = str(DSG._ID) + '-' + str(DS._ID) FG_damages.loc[in_this_DSG, (FG._ID, PG_ID, DS_tag)] += csg_w elif DSG._DS_set_kind == 'mutually exclusive': DS_weights = [DS._weight for DS in DSG._DS_set] DS_RV = RandomVariable( ID=-1, dimension_tags=['me_DS', ], distribution_kind='multinomial', p_set=DS_weights) DS_df = DS_RV.sample_distribution( len(in_this_DSG)) + 1 for DS in DSG._DS_set: DS_tag = str(DSG._ID) + '-' + str(DS._ID) in_this_DS = DS_df[DS_df.values == DS._ID].index FG_damages.loc[in_this_DSG[in_this_DS], (FG._ID, PG_ID, DS_tag)] += csg_w else: # TODO: simultaneous print(DSG._DS_set_kind) FG_damages.iloc[:,pg_i * d_count:(pg_i + 1) * d_count] = \ FG_damages.mul(PG_qnt.iloc[:, 0], axis=0) DMG = pd.concat((DMG, FG_damages), axis=1) DMG.index = ncID # sort the columns to enable index slicing later DMG = DMG.sort_index(axis=1, ascending=True) return DMG def _calc_red_tag(self): idx = pd.IndexSlice ncID = self._ID_dict['non-collapse'] NC_samples = len(ncID) DV_RED = pd.DataFrame() s_fg_keys = sorted(self._FG_dict.keys()) for fg_id in s_fg_keys: FG = self._FG_dict[fg_id] PG_set = FG._performance_groups DS_list = self._DMG.loc[:, idx[FG._ID, PG_set[0]._ID, :]].columns DS_list = DS_list.levels[2][DS_list.labels[2]].values MI = pd.MultiIndex.from_product([[FG._ID, ], [pg._ID for pg in PG_set], DS_list], names=['FG', 'PG', 'DS']) FG_RED = pd.DataFrame(np.zeros((NC_samples, len(MI))), columns=MI, index=ncID) for pg_i, PG in enumerate(PG_set): PG_ID = PG._ID PG_qnt = PG._quantity.samples.loc[ncID] PG_DMG = self._DMG.loc[:, idx[FG._ID, PG_ID, :]].div( PG_qnt.iloc[:, 0], axis=0) for d_i, d_tag in enumerate(DS_list): dsg_i = int(d_tag[0]) - 1 ds_i = int(d_tag[-1]) - 1 DS = PG._DSG_set[dsg_i]._DS_set[ds_i] if DS._red_tag_CF is not None: RED_samples = DS.red_tag_dmg_limit( sample_size=NC_samples) RED_samples.index = ncID is_red = PG_DMG.loc[:, (FG._ID, PG_ID, d_tag)].sub( RED_samples, axis=0) FG_RED.loc[:, (FG._ID, PG_ID, d_tag)] = ( is_red > 0.).astype(int) else: FG_RED.drop(labels=[(FG._ID, PG_ID, d_tag), ], axis=1, inplace=True) if FG_RED.size > 0: DV_RED = pd.concat((DV_RED, FG_RED), axis=1) # sort the columns to enable index slicing later DV_RED = DV_RED.sort_index(axis=1, ascending=True) return DV_RED def _calc_irrepairable(self): ncID = self._ID_dict['non-collapse'] NC_samples = len(ncID) # determine which realizations lead to irrepairable damage # get the max residual drifts RED_max = None PID_max = None s_edp_keys = sorted(self._EDP_dict.keys()) for demand_ID in s_edp_keys: demand = self._EDP_dict[demand_ID] kind = demand_ID[:3] if kind == 'RED': r_max = demand.samples.loc[ncID].values if RED_max is None: RED_max = r_max else: RED_max = np.max((RED_max, r_max), axis=0) elif kind == 'PID': d_max = demand.samples.loc[ncID].values if PID_max is None: PID_max = d_max else: PID_max = np.max((PID_max, d_max), axis=0) if (RED_max is None) and (PID_max is not None): # we need to estimate residual drifts based on peak drifts RED_max = np.zeros(NC_samples) # based on Appendix C in FEMA P-58 delta_y = self._AIM_in['general']['yield_drift'] small = PID_max < delta_y medium = PID_max < 4 * delta_y large = PID_max >= 4 * delta_y RED_max[large] = PID_max[large] - 3 * delta_y RED_max[medium] = 0.3 * (PID_max[medium] - delta_y) RED_max[small] = 0. else: # If no drift data is available, then we cannot provide an estimate # of irrepairability. We assume that all non-collapse realizations # are repairable in this case. return np.array([]) # get the probabilities of irrepairability irrep_frag = self._AIM_in['general']['irrepairable_res_drift'] RV_irrep = RandomVariable(ID=-1, dimension_tags=['RED_irrep', ], distribution_kind='lognormal', theta=irrep_frag['Median'], COV=irrep_frag['Sig'] ** 2. ) RED_irrep = RV_irrep.sample_distribution(NC_samples)['RED_irrep'].values # determine if the realizations are repairable irrepairable = RED_max > RED_irrep irrepairable_IDs = ncID[np.where(irrepairable)[0]] return irrepairable_IDs def _calc_repair_cost_and_time(self): idx = pd.IndexSlice DVs = self._AIM_in['decision_variables'] DMG_by_FG_and_DS = self._DMG.groupby(level=[0, 2], axis=1).sum() repID = self._ID_dict['repairable'] REP_samples = len(repID) DV_COST = pd.DataFrame(np.zeros((REP_samples, len(self._DMG.columns))), columns=self._DMG.columns, index=repID) DV_TIME = deepcopy(DV_COST) s_fg_keys = sorted(self._FG_dict.keys()) for fg_id in s_fg_keys: FG = self._FG_dict[fg_id] PG_set = FG._performance_groups DS_list = self._DMG.loc[:, idx[FG._ID, PG_set[0]._ID, :]].columns DS_list = DS_list.levels[2][DS_list.labels[2]].values for pg_i, PG in enumerate(PG_set): PG_ID = PG._ID for d_i, d_tag in enumerate(DS_list): dsg_i = int(d_tag[0]) - 1 ds_i = int(d_tag[-1]) - 1 DS = PG._DSG_set[dsg_i]._DS_set[ds_i] TOT_qnt = DMG_by_FG_and_DS.loc[repID, (FG._ID, d_tag)] PG_qnt = self._DMG.loc[repID, (FG._ID, PG_ID, d_tag)] # repair cost if DVs['rec_cost']: COST_samples = DS.unit_repair_cost(quantity=TOT_qnt) DV_COST.loc[:, (FG._ID, PG_ID, d_tag)] = COST_samples * PG_qnt if DVs['rec_time']: # repair time TIME_samples = DS.unit_reconstruction_time(quantity=TOT_qnt) DV_TIME.loc[:, (FG._ID, PG_ID, d_tag)] = TIME_samples * PG_qnt # sort the columns to enable index slicing later if DVs['rec_cost']: DV_COST = DV_COST.sort_index(axis=1, ascending=True) else: DV_COST = None if DVs['rec_time']: DV_TIME = DV_TIME.sort_index(axis=1, ascending=True) else: DV_TIME = None return DV_COST, DV_TIME def _calc_collapse_injuries(self): inj_lvls = self._inj_lvls # calculate casualties and injuries for the collapsed cases # generate collapse modes colID = self._ID_dict['collapse'] C_samples = len(colID) if C_samples > 0: inj_lvls = self._inj_lvls coll_modes = self._AIM_in['collapse_modes'] P_keys = [cmk for cmk in coll_modes.keys()] P_modes = [coll_modes[k]['w'] for k in P_keys] # create the DataFrame that collects the decision variables inj_cols = ['CM',] for i in range(inj_lvls): inj_cols.append('INJ-{}'.format(i)) COL_INJ = pd.DataFrame(np.zeros((C_samples, inj_lvls + 1)), columns=inj_cols, index=colID) CM_RV = RandomVariable(ID=-1, dimension_tags=['CM', ], distribution_kind='multinomial', p_set=P_modes) COL_INJ['CM'] = CM_RV.sample_distribution(C_samples).values # get the popoulation values corresponding to the collapsed cases P_sel = self._POP.loc[colID] # calculate the exposure of the popoulation for cm_i, cmk in enumerate(P_keys): mode_IDs = COL_INJ[COL_INJ['CM'] == cm_i].index CFAR = coll_modes[cmk]['affected_area'] INJ = coll_modes[cmk]['injuries'] for loc_i in range(len(CFAR)): loc_label = 'LOC{}'.format(loc_i + 1) if loc_label in P_sel.columns: for inj_i in range(inj_lvls): INJ_i = P_sel.loc[mode_IDs, loc_label] * CFAR[loc_i] * \ INJ[inj_i] COL_INJ.loc[mode_IDs, 'INJ-{}'.format(inj_i)] = ( COL_INJ.loc[mode_IDs, 'INJ-{}'.format(inj_i)].add(INJ_i, axis=0).values) return COL_INJ else: return None def _calc_non_collapse_injuries(self): idx = pd.IndexSlice ncID = self._ID_dict['non-collapse'] NC_samples = len(ncID) DV_INJ_dict = dict([(i, pd.DataFrame(np.zeros((NC_samples, len(self._DMG.columns))), columns=self._DMG.columns, index=ncID)) for i in range(self._inj_lvls)]) s_fg_keys = sorted(self._FG_dict.keys()) for fg_id in s_fg_keys: FG = self._FG_dict[fg_id] PG_set = FG._performance_groups DS_list = self._DMG.loc[:, idx[FG._ID, PG_set[0]._ID, :]].columns DS_list = DS_list.levels[2][DS_list.labels[2]].values for pg_i, PG in enumerate(PG_set): PG_ID = PG._ID for d_i, d_tag in enumerate(DS_list): dsg_i = int(d_tag[0]) - 1 ds_i = int(d_tag[-1]) - 1 DS = PG._DSG_set[dsg_i]._DS_set[ds_i] if DS._affected_area > 0.: P_affected = (self._POP.loc[ncID] * DS._affected_area / self._AIM_in['general']['plan_area']) QNT = self._DMG.loc[:, (FG._ID, PG_ID, d_tag)] # estimate injuries for i in range(self._inj_lvls): INJ_samples = DS.unit_injuries(severity_level=i, sample_size=NC_samples) if INJ_samples is not None: INJ_samples.index = ncID P_aff_i = P_affected.loc[:, 'LOC{}'.format(PG._location)] INJ_i = INJ_samples * P_aff_i * QNT DV_INJ_dict[i].loc[:, (FG._ID, PG_ID, d_tag)] = INJ_i # remove the useless columns from DV_INJ for i in range(self._inj_lvls): DV_INJ = DV_INJ_dict[i] DV_INJ_dict[i] = DV_INJ.loc[:, (DV_INJ != 0.0).any(axis=0)] # sort the columns to enable index slicing later for i in range(self._inj_lvls): DV_INJ_dict[i] = DV_INJ_dict[i].sort_index(axis=1, ascending=True) return DV_INJ_dict
import React from "react" import { Link } from "gatsby" import { graphql } from "gatsby" import Layout from "../components/layout" import SEO from "../components/seo" export default ({data}) => { return ( <Layout> <SEO title="Home" /> <h1>Blog</h1> {data.allMarkdownRemark.edges.map(({ node }) => ( <div key={node.id}> <Link to={node.frontmatter.path}>{node.frontmatter.title}</Link> </div> ))} </Layout> )} export const query = graphql` query IndexQuery { allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) { totalCount edges { node { id frontmatter { title date(formatString: "DD MMMM, YYYY") path } } } } } `;
Dagaz.Controller.persistense = "none"; ZRF = { JUMP: 0, IF: 1, FORK: 2, FUNCTION: 3, IN_ZONE: 4, FLAG: 5, SET_FLAG: 6, POS_FLAG: 7, SET_POS_FLAG: 8, ATTR: 9, SET_ATTR: 10, PROMOTE: 11, MODE: 12, ON_BOARD_DIR: 13, ON_BOARD_POS: 14, PARAM: 15, LITERAL: 16, VERIFY: 20 }; Dagaz.Model.BuildDesign = function(design) { design.checkVersion("z2j", "2"); design.checkVersion("animate-captures", "false"); design.checkVersion("smart-moves", "false"); design.checkVersion("show-hints", "false"); design.checkVersion("show-blink", "true"); design.checkVersion("advisor-wait", "5"); design.addDirection("w"); design.addDirection("e"); design.addDirection("s"); design.addDirection("ne"); design.addDirection("n"); design.addDirection("se"); design.addDirection("sw"); design.addDirection("nw"); design.addPlayer("Black", [1, 0, 4, 6, 2, 7, 3, 5]); design.addPlayer("White", [1, 0, 4, 6, 2, 7, 3, 5]); design.addPosition("a8", [0, 1, 8, 0, 0, 9, 0, 0]); design.addPosition("b8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("c8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("d8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("e8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("f8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("g8", [-1, 1, 8, 0, 0, 9, 7, 0]); design.addPosition("h8", [-1, 0, 8, 0, 0, 0, 7, 0]); design.addPosition("a7", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g7", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h7", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a6", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g6", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h6", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a5", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g5", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h5", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a4", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g4", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h4", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a3", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g3", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h3", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a2", [0, 1, 8, -7, -8, 9, 0, 0]); design.addPosition("b2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("c2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("d2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("e2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("f2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("g2", [-1, 1, 8, -7, -8, 9, 7, -9]); design.addPosition("h2", [-1, 0, 8, 0, -8, 0, 7, -9]); design.addPosition("a1", [0, 1, 0, -7, -8, 0, 0, 0]); design.addPosition("b1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("c1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("d1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("e1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("f1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("g1", [-1, 1, 0, -7, -8, 0, 0, -9]); design.addPosition("h1", [-1, 0, 0, 0, -8, 0, 0, -9]); design.addPosition("X1", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X2", [0, 0, 0, 0, 0, 0, 0, 0]); design.addPosition("X3", [0, 0, 0, 0, 0, 0, 0, 0]); design.addZone("promotion", 2, [56, 58, 60, 62]); design.addZone("promotion", 1, [1, 3, 5, 7]); design.addCommand(0, ZRF.FUNCTION, 24); // from design.addCommand(0, ZRF.PARAM, 0); // $1 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 2); // enemy? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.FUNCTION, 26); // capture design.addCommand(0, ZRF.PARAM, 1); // $2 design.addCommand(0, ZRF.FUNCTION, 22); // navigate design.addCommand(0, ZRF.FUNCTION, 1); // empty? design.addCommand(0, ZRF.FUNCTION, 20); // verify design.addCommand(0, ZRF.IN_ZONE, 0); // promotion design.addCommand(0, ZRF.FUNCTION, 0); // not design.addCommand(0, ZRF.IF, 4); design.addCommand(0, ZRF.PROMOTE, 1); // King design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.JUMP, 3); design.addCommand(0, ZRF.MODE, 0); // jump-type design.addCommand(0, ZRF.FUNCTION, 25); // to design.addCommand(0, ZRF.FUNCTION, 28); // end design.addCommand(1, ZRF.FUNCTION, 24); // from design.addCommand(1, ZRF.PARAM, 0); // $1 design.addCommand(1, ZRF.FUNCTION, 22); // navigate design.addCommand(1, ZRF.FUNCTION, 1); // empty? design.addCommand(1, ZRF.FUNCTION, 20); // verify design.addCommand(1, ZRF.IN_ZONE, 0); // promotion design.addCommand(1, ZRF.FUNCTION, 0); // not design.addCommand(1, ZRF.IF, 4); design.addCommand(1, ZRF.PROMOTE, 1); // King design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.JUMP, 2); design.addCommand(1, ZRF.FUNCTION, 25); // to design.addCommand(1, ZRF.FUNCTION, 28); // end design.addCommand(2, ZRF.FUNCTION, 24); // from design.addCommand(2, ZRF.PARAM, 0); // $1 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 2); // enemy? design.addCommand(2, ZRF.FUNCTION, 20); // verify design.addCommand(2, ZRF.FUNCTION, 26); // capture design.addCommand(2, ZRF.PARAM, 1); // $2 design.addCommand(2, ZRF.FUNCTION, 22); // navigate design.addCommand(2, ZRF.FUNCTION, 1); // empty? design.addCommand(2, ZRF.FUNCTION, 20); // verify design.addCommand(2, ZRF.MODE, 0); // jump-type design.addCommand(2, ZRF.FUNCTION, 25); // to design.addCommand(2, ZRF.FUNCTION, 28); // end design.addCommand(3, ZRF.FUNCTION, 24); // from design.addCommand(3, ZRF.PARAM, 0); // $1 design.addCommand(3, ZRF.FUNCTION, 22); // navigate design.addCommand(3, ZRF.FUNCTION, 1); // empty? design.addCommand(3, ZRF.FUNCTION, 20); // verify design.addCommand(3, ZRF.FUNCTION, 25); // to design.addCommand(3, ZRF.FUNCTION, 28); // end design.addCommand(4, ZRF.FUNCTION, 24); // from design.addCommand(4, ZRF.PARAM, 0); // $1 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.FUNCTION, 1); // empty? design.addCommand(4, ZRF.FUNCTION, 0); // not design.addCommand(4, ZRF.IF, 4); design.addCommand(4, ZRF.PARAM, 1); // $2 design.addCommand(4, ZRF.FUNCTION, 22); // navigate design.addCommand(4, ZRF.JUMP, -5); design.addCommand(4, ZRF.FUNCTION, 2); // enemy? design.addCommand(4, ZRF.FUNCTION, 20); // verify design.addCommand(4, ZRF.FUNCTION, 25); // to design.addCommand(4, ZRF.FUNCTION, 28); // end design.addCommand(5, ZRF.FUNCTION, 24); // from design.addCommand(5, ZRF.PARAM, 0); // $1 design.addCommand(5, ZRF.FUNCTION, 22); // navigate design.addCommand(5, ZRF.FUNCTION, 1); // empty? design.addCommand(5, ZRF.FUNCTION, 0); // not design.addCommand(5, ZRF.IF, 7); design.addCommand(5, ZRF.FORK, 3); design.addCommand(5, ZRF.FUNCTION, 25); // to design.addCommand(5, ZRF.FUNCTION, 28); // end design.addCommand(5, ZRF.PARAM, 1); // $2 design.addCommand(5, ZRF.FUNCTION, 22); // navigate design.addCommand(5, ZRF.JUMP, -8); design.addCommand(5, ZRF.FUNCTION, 28); // end design.addCommand(6, ZRF.FUNCTION, 24); // from design.addCommand(6, ZRF.PARAM, 0); // $1 design.addCommand(6, ZRF.FUNCTION, 22); // navigate design.addCommand(6, ZRF.PARAM, 1); // $2 design.addCommand(6, ZRF.FUNCTION, 22); // navigate design.addCommand(6, ZRF.PARAM, 2); // $3 design.addCommand(6, ZRF.FUNCTION, 22); // navigate design.addCommand(6, ZRF.FUNCTION, 2); // enemy? design.addCommand(6, ZRF.FUNCTION, 20); // verify design.addCommand(6, ZRF.FUNCTION, 25); // to design.addCommand(6, ZRF.FUNCTION, 28); // end design.addCommand(7, ZRF.FUNCTION, 24); // from design.addCommand(7, ZRF.PARAM, 0); // $1 design.addCommand(7, ZRF.FUNCTION, 22); // navigate design.addCommand(7, ZRF.PARAM, 1); // $2 design.addCommand(7, ZRF.FUNCTION, 22); // navigate design.addCommand(7, ZRF.PARAM, 2); // $3 design.addCommand(7, ZRF.FUNCTION, 22); // navigate design.addCommand(7, ZRF.FUNCTION, 1); // empty? design.addCommand(7, ZRF.FUNCTION, 20); // verify design.addCommand(7, ZRF.FUNCTION, 25); // to design.addCommand(7, ZRF.FUNCTION, 28); // end // design.addPriority(0); // jump-type // design.addPriority(1); // normal-type design.addPiece("Man", 0, 1); design.addMove(0, 0, [7, 7], 0); design.addMove(0, 0, [3, 3], 0); design.addMove(0, 1, [7], 1); design.addMove(0, 1, [3], 1); design.addPiece("King", 1, 100); design.addMove(1, 2, [7, 7], 0); design.addMove(1, 2, [3, 3], 0); design.addMove(1, 2, [6, 6], 0); design.addMove(1, 2, [5, 5], 0); design.addMove(1, 3, [7], 1); design.addMove(1, 3, [3], 1); design.addMove(1, 3, [6], 1); design.addMove(1, 3, [5], 1); design.addPiece("Bishop", 2, 15); design.addMove(2, 4, [7, 7], 0); design.addMove(2, 4, [3, 3], 0); design.addMove(2, 4, [6, 6], 0); design.addMove(2, 4, [5, 5], 0); design.addMove(2, 5, [7, 7], 1); design.addMove(2, 5, [3, 3], 1); design.addMove(2, 5, [6, 6], 1); design.addMove(2, 5, [5, 5], 1); design.addPiece("Camel", 3, 20); design.addMove(3, 6, [4, 4, 7], 0); design.addMove(3, 6, [4, 4, 3], 0); design.addMove(3, 6, [2, 2, 6], 0); design.addMove(3, 6, [2, 2, 5], 0); design.addMove(3, 6, [0, 0, 6], 0); design.addMove(3, 6, [0, 0, 7], 0); design.addMove(3, 6, [1, 1, 5], 0); design.addMove(3, 6, [1, 1, 3], 0); design.addMove(3, 7, [4, 4, 7], 1); design.addMove(3, 7, [4, 4, 3], 1); design.addMove(3, 7, [2, 2, 6], 1); design.addMove(3, 7, [2, 2, 5], 1); design.addMove(3, 7, [0, 0, 6], 1); design.addMove(3, 7, [0, 0, 7], 1); design.addMove(3, 7, [1, 1, 5], 1); design.addMove(3, 7, [1, 1, 3], 1); design.setup("Black", "Man", 40); design.setup("Black", "Man", 49); design.setup("Black", "Man", 42); design.setup("Black", "Man", 51); design.setup("Black", "Man", 44); design.setup("Black", "Man", 53); design.setup("Black", "Man", 46); design.setup("Black", "Man", 55); design.setup("Black", "Bishop", 56); design.setup("Black", "King", 58); design.setup("Black", "King", 60); design.setup("Black", "Camel", 62); design.setup("White", "Man", 8); design.setup("White", "Man", 17); design.setup("White", "Man", 10); design.setup("White", "Man", 19); design.setup("White", "Man", 12); design.setup("White", "Man", 21); design.setup("White", "Man", 14); design.setup("White", "Man", 23); design.setup("White", "Bishop", 7); design.setup("White", "King", 3); design.setup("White", "King", 5); design.setup("White", "Camel", 1); } Dagaz.View.configure = function(view) { view.defBoard("Board"); view.defPiece("WhiteMan", "White Man"); view.defPiece("BlackMan", "Black Man"); view.defPiece("WhiteKing", "White King"); view.defPiece("BlackKing", "Black King"); view.defPiece("WhiteBishop", "White Bishop"); view.defPiece("BlackBishop", "Black Bishop"); view.defPiece("WhiteCamel", "White Camel"); view.defPiece("BlackCamel", "Black Camel"); view.defPosition("a8", 352, 352, 50, 50); view.defPosition("b8", 302, 352, 50, 50); view.defPosition("c8", 252, 352, 50, 50); view.defPosition("d8", 202, 352, 50, 50); view.defPosition("e8", 152, 352, 50, 50); view.defPosition("f8", 102, 352, 50, 50); view.defPosition("g8", 52, 352, 50, 50); view.defPosition("h8", 2, 352, 50, 50); view.defPosition("a7", 352, 302, 50, 50); view.defPosition("b7", 302, 302, 50, 50); view.defPosition("c7", 252, 302, 50, 50); view.defPosition("d7", 202, 302, 50, 50); view.defPosition("e7", 152, 302, 50, 50); view.defPosition("f7", 102, 302, 50, 50); view.defPosition("g7", 52, 302, 50, 50); view.defPosition("h7", 2, 302, 50, 50); view.defPosition("a6", 352, 252, 50, 50); view.defPosition("b6", 302, 252, 50, 50); view.defPosition("c6", 252, 252, 50, 50); view.defPosition("d6", 202, 252, 50, 50); view.defPosition("e6", 152, 252, 50, 50); view.defPosition("f6", 102, 252, 50, 50); view.defPosition("g6", 52, 252, 50, 50); view.defPosition("h6", 2, 252, 50, 50); view.defPosition("a5", 352, 202, 50, 50); view.defPosition("b5", 302, 202, 50, 50); view.defPosition("c5", 252, 202, 50, 50); view.defPosition("d5", 202, 202, 50, 50); view.defPosition("e5", 152, 202, 50, 50); view.defPosition("f5", 102, 202, 50, 50); view.defPosition("g5", 52, 202, 50, 50); view.defPosition("h5", 2, 202, 50, 50); view.defPosition("a4", 352, 152, 50, 50); view.defPosition("b4", 302, 152, 50, 50); view.defPosition("c4", 252, 152, 50, 50); view.defPosition("d4", 202, 152, 50, 50); view.defPosition("e4", 152, 152, 50, 50); view.defPosition("f4", 102, 152, 50, 50); view.defPosition("g4", 52, 152, 50, 50); view.defPosition("h4", 2, 152, 50, 50); view.defPosition("a3", 352, 102, 50, 50); view.defPosition("b3", 302, 102, 50, 50); view.defPosition("c3", 252, 102, 50, 50); view.defPosition("d3", 202, 102, 50, 50); view.defPosition("e3", 152, 102, 50, 50); view.defPosition("f3", 102, 102, 50, 50); view.defPosition("g3", 52, 102, 50, 50); view.defPosition("h3", 2, 102, 50, 50); view.defPosition("a2", 352, 52, 50, 50); view.defPosition("b2", 302, 52, 50, 50); view.defPosition("c2", 252, 52, 50, 50); view.defPosition("d2", 202, 52, 50, 50); view.defPosition("e2", 152, 52, 50, 50); view.defPosition("f2", 102, 52, 50, 50); view.defPosition("g2", 52, 52, 50, 50); view.defPosition("h2", 2, 52, 50, 50); view.defPosition("a1", 352, 2, 50, 50); view.defPosition("b1", 302, 2, 50, 50); view.defPosition("c1", 252, 2, 50, 50); view.defPosition("d1", 202, 2, 50, 50); view.defPosition("e1", 152, 2, 50, 50); view.defPosition("f1", 102, 2, 50, 50); view.defPosition("g1", 52, 2, 50, 50); view.defPosition("h1", 2, 2, 50, 50); view.defPopup("Promote", 114, 70); view.defPopupPosition("X1", 10, 7, 50, 50); view.defPopupPosition("X2", 62, 7, 50, 50); view.defPopupPosition("X3", 115, 7, 50, 50); }
(function(d){d['tt']=Object.assign(d['tt']||{},{a:"Image toolbar",b:"Cannot upload file:",c:"Table toolbar",d:"Subscript",e:"Калын",f:"Underline",g:"Strikethrough",h:"Block quote",i:"Superscript",j:"Choose heading",k:"Heading",l:"Increase indent",m:"Decrease indent",n:"Full size image",o:"Side image",p:"Left aligned image",q:"Centered image",r:"Right aligned image",s:"Enter image caption",t:"Insert image",u:"Insert image or file",v:"Upload failed",w:"Link",x:"media widget",y:"Numbered List",z:"Bulleted List",aa:"Insert media",ab:"The URL must not be empty.",ac:"This media URL is not supported.",ad:"Insert table",ae:"Header column",af:"Insert column left",ag:"Insert column right",ah:"Delete column",ai:"Column",aj:"Header row",ak:"Insert row below",al:"Insert row above",am:"Delete row",an:"Row",ao:"Merge cell up",ap:"Merge cell right",aq:"Merge cell down",ar:"Merge cell left",as:"Split cell vertically",at:"Split cell horizontally",au:"Merge cells",av:"Widget toolbar",aw:"Upload in progress",ax:"Align left",ay:"Align right",az:"Align center",ba:"Justify",bb:"Text alignment",bc:"Text alignment toolbar",bd:"image widget",be:"Horizontal line",bf:"Italic",bg:"Could not obtain resized image URL.",bh:"Selecting resized image failed",bi:"Could not insert image at the current position.",bj:"Inserting image failed",bk:"Сакла",bl:"Cancel",bm:"Paste the media URL in the input.",bn:"Tip: Paste the URL into the content to embed faster.",bo:"Media URL",bp:"Dropdown toolbar",bq:"Rich Text Editor",br:"Font Size",bs:"Default",bt:"Tiny",bu:"Small",bv:"Big",bw:"Huge",bx:"Font Color",by:"Font Family",bz:"Font Background Color",ca:"Change image text alternative",cb:"Remove color",cc:"Document colors",cd:"Black",ce:"Dim grey",cf:"Grey",cg:"Light grey",ch:"White",ci:"Red",cj:"Orange",ck:"Yellow",cl:"Light green",cm:"Green",cn:"Aquamarine",co:"Turquoise",cp:"Light blue",cq:"Blue",cr:"Purple",cs:"%0 of %1",ct:"Previous",cu:"Next",cv:"Text alternative",cw:"Editor toolbar",cx:"Show more items",cy:"Undo",cz:"Кабатла",da:"Open in a new tab",db:"Downloadable",dc:"Unlink",dd:"Edit link",de:"Open link in new tab",df:"This link has no URL",dg:"Link URL",dh:"Paragraph",di:"Heading 1",dj:"Heading 2",dk:"Heading 3",dl:"Heading 4",dm:"Heading 5",dn:"Heading 6",do:"Rich Text Editor, %0"})})(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
const { Model, DataTypes } = require('sequelize'); const sequelize = require('../config/connection'); class PaymentMethod extends Model {} PaymentMethod.init( { id: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV4, allowNull: false, primaryKey: true, }, stripe_customer_id: { type: DataTypes.STRING, allowNull: false, }, stripe_payment_method_id: { type: DataTypes.STRING, allowNull: false, }, user_id: { type: DataTypes.UUID, allowNull: false, references: { model: 'user', key: 'id', }, }, }, { sequelize, timestamps: true, freezeTableName: true, underscored: true, modelName: 'paymentMethod', } ); module.exports = PaymentMethod;
import client from 'shared/client'; import { NOVALUE, ChannelListTypes } from 'shared/constants'; import { Channel, SavedSearch } from 'shared/data/resources'; export function fetchResourceSearchResults(context, params) { params = { ...params }; delete params['last']; params.page_size = params.page_size || 25; params.channel_list = params.channel_list || ChannelListTypes.PUBLIC; return client.get(window.Urls.search_list(), { params }).then(response => { context.commit('contentNode/ADD_CONTENTNODES', response.data.results, { root: true }); return response.data; }); } export function loadChannels(context, params) { // Used for search channel filter dropdown params.page_size = 25; return Channel.requestCollection({ deleted: false, ...params }).then(channelPage => { return channelPage; }); } /* SAVED SEARCH ACTIONS */ export function loadSavedSearches({ commit }) { return SavedSearch.where().then(searches => { commit('SET_SAVEDSEARCHES', searches); return searches; }); } export function createSearch({ commit, rootState }, params) { const data = { params, name: params.keywords, saved_by: rootState.session.currentUser.id, created: new Date(), }; return SavedSearch.put(data).then(id => { commit('UPDATE_SAVEDSEARCH', { id, ...data, }); return id; }); } export function updateSearch({ commit }, { id, name = NOVALUE } = {}) { const searchData = {}; if (!id) { throw ReferenceError('id must be defined to update a saved search'); } if (name !== NOVALUE) { searchData.name = name; } commit('UPDATE_SAVEDSEARCH', { id, ...searchData }); return SavedSearch.update(id, searchData); } export function deleteSearch({ commit }, searchId) { return SavedSearch.delete(searchId).then(() => { commit('REMOVE_SAVEDSEARCH', searchId); return searchId; }); }
'use strict'; /** * The ozp toolbar component shown in the Webtop. * * @module ozpWebtop.ozpToolbar * @requires ozp.common.windowSizeWatcher * @requires ozpWebtop.models */ angular.module('ozpWebtop.ozpToolbar', [ 'ozp.common.windowSizeWatcher', 'ozpWebtop.models', 'ozpWebtop.filters', 'ozpWebtop.services.ozpInterface']); angular.module( 'ozpWebtop.ozpToolbar') /** * Controller for ozp toolbar located at the top of Webtop * * Includes: * - menu with links to other OZP resources * - notifications (TODO) * - username button with dropdown to access user preferences, help, and logout * * ngtype: controller * * @class OzpToolbarCtrl * @constructor * @param $scope ng $scope * @param $rootScope ng $rootScope * @param windowSizeWatcher notify when window size changes * @param deviceSizeChangedEvent event name * @param fullScreenModeToggleEvent event name * @param ozpInterface module for backend communication * @namespace ozpToolbar * */ .controller('OzpToolbarCtrl', function($scope, $rootScope, $window, $log, $modal, models, windowSizeWatcher, deviceSizeChangedEvent, tooltipDelay, fullScreenModeToggleEvent, ozpInterface, notificationReceivedEvent) { // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // $scope properties // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * @property toolTipDelay length of time to delay showing tooltips on hover * @type number */ $scope.toolTipDelay = tooltipDelay; /** * @property usernameLength Max length of username, based on * current screen size * @type {Number} */ $scope.usernameLength = 0; /** * @property fullScreenMode Flag indicating if toolbar should be hidden * @type {boolean} */ $scope.fullScreenMode = false; /** * @property messages Messages that have not been dismissed * type {array} */ $scope.messages = []; /** * @property thereAreUnexpiredNotifications Whether or not there are unexpired * notifications, used to change class in template to notify use * type {boolean} */ $rootScope.$on(notificationReceivedEvent, function(event, data){ //check to see if there are any notifications $scope.messages = data; $scope.messageCount = $scope.messages.length; $scope.thereAreUnexpiredNotifications = true; //update notification tooltip if($scope.messages.length === 0){ // no messages, switch bell icon in template $scope.thereAreUnexpiredNotifications = false; }else if($scope.messageCount === 1){ $scope.notificationTooltip = $scope.messageCount + ' new notification.'; } else { $scope.notificationTooltip = $scope.messageCount + ' new notifications.'; } }); $scope.dismissNotification = function(a){ for(var b in $scope.messages){ if($scope.messages[b].id === a.id){ //update the backend so other apps know message has been dismissed models.dismissNotification(a); //delete local message from scope $scope.messages.splice(b, 1); } } if($scope.messageCount > 0){ $scope.messageCount = $scope.messageCount - 1; $scope.notificationTooltip = $scope.messageCount + ' new notifications.'; } if($scope.messages.length === 0){ // no messages, switch bell icon in template $scope.thereAreUnexpiredNotifications = false; } }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // initialization // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // register for notifications when window size changes windowSizeWatcher.run(); $scope.$on(deviceSizeChangedEvent, function(event, value) { handleDeviceSizeChange(value); }); $scope.$on(fullScreenModeToggleEvent, function(event, data) { $scope.fullScreenMode = data.fullScreenMode; }); $scope.hudUrl = $window.OzoneConfig.HUD_URL; $scope.centerUrl = $window.OzoneConfig.CENTER_URL; $scope.webtopUrl = $window.OzoneConfig.WEBTOP_URL; $scope.metricsUrl = $window.OzoneConfig.METRICS_URL; $scope.developerResourcesUrl = $window.OzoneConfig.DEVELOPER_RESOURCES_URL; $scope.feedbackAddress = $window.OzoneConfig.FEEDBACK_ADDRESS; $scope.helpdeskAddress = $window.OzoneConfig.HELPDESK_ADDRESS; $scope.feedbackTarget = '_blank'; $scope.helpdeskTarget = '_blank'; if($scope.feedbackAddress.substring(0,7)=== 'mailto:'){ $scope.feedbackTarget = '_self'; } if($scope.helpdeskAddress.substring(0,7)=== 'mailto:'){ $scope.helpdeskTarget = '_self'; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // methods // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /** * Handler invoked when window size changes across device size boundaries * as defined by Bootstrap * * @method handleDeviceSizeChange * @param value value.deviceSize is one of 'xs', 'sm', 'md', or 'lg' */ function handleDeviceSizeChange(value) { if (value.deviceSize === 'sm') { $scope.usernameLength = 9; } else if (value.deviceSize === 'md') { $scope.usernameLength = 12; } else if (value.deviceSize === 'lg') { $scope.usernameLength = 12; } } /** * @method openHelpModal * @param board the changed board object * @returns {*} */ $scope.openHelpModal = function(board) { $scope.board = board; var modalInstance = $modal.open({ templateUrl: 'userInterface/helpModal/helpModal.tpl.html', controller: 'helpModalInstanceCtrl', windowClass: 'app-modal-window-large', scope: $scope, resolve: { dashboard: function() { // return $scope.board; return $scope.board; } } }); modalInstance.result.then(function () { }); }; /** * @method openProfileModal * @param board the changed board object * @returns {*} */ $scope.openProfileModal = function(board) { $scope.board = board; var modalInstance = $modal.open({ templateUrl: 'userInterface/profileModal/profileModal.tpl.html', controller: 'profileModalInstanceCtrl', windowClass: 'app-modal-window', scope: $scope, resolve: { dashboard: function() { // return $scope.board; return $scope.board; } } }); modalInstance.result.then(function () { }); }; /** * @method openContactModal * @param board the changed board object * @returns {*} */ $scope.openContactModal = function(board) { $scope.board = board; var modalInstance = $modal.open({ templateUrl: 'userInterface/contactModal/contactModal.tpl.html', controller: 'contactModalInstanceCtrl', windowClass: 'app-modal-window', scope: $scope, resolve: { dashboard: function() { // return $scope.board; return $scope.board; } } }); modalInstance.result.then(function () { }); }; /** * @property isAdmin indicates if the user is an admin * @property isOrgSteward indicates if the user is an org steward */ ozpInterface.getProfile().then(function(d){ var userRole=d.highestRole; if(userRole === 'ADMIN' || userRole === 'APPS_MALL_STEWARD'){ $scope.isAdmin = true; }else{ $scope.isAdmin = false; } if(userRole === 'ORG_STEWARD'){ $scope.isOrgSteward = true; }else{ $scope.isOrgSteward = false; } }); } );
define(["exports", "./node_modules/@polymer/polymer/polymer-legacy.js", "./node_modules/@lrnwebcomponents/simple-timer/simple-timer.js", "./node_modules/@lrnwebcomponents/simple-modal/simple-modal.js", "./node_modules/@lrnwebcomponents/to-do/to-do.js", "./node_modules/@polymer/paper-card/paper-card.js", "./node_modules/@polymer/paper-button/paper-button.js"], function (_exports, _polymerLegacy, _simpleTimer, _simpleModal, _toDo, _paperCard, _paperButton) { "use strict"; Object.defineProperty(_exports, "__esModule", { value: true }); _exports.SillyHaxGame = void 0; function _templateObject_d1cce2c0c3a011e99204fd28bf05b7e9() { var data = babelHelpers.taggedTemplateLiteral(["\n <style>\n :host {\n display: block;\n }\n </style>\n <paper-card heading=\"[[haxText]]\" elevation=\"1\">\n <simple-timer\n id=\"timer\"\n start-time=\"60\"\n count-up=\"\"\n hidden=\"\"\n current-time=\"{{timer}}\"\n ></simple-timer>\n <div class=\"card-content\">\n <to-do\n items=\"{{tasks}}\"\n hide-form=\"\"\n id=\"todo\"\n name=\"Hax Challenge\"\n ></to-do>\n </div>\n <div class=\"card-actions\">\n <paper-button id=\"play\" raised=\"\" on-tap=\"_playButton\"\n >Play</paper-button\n >\n <paper-button raised=\"\" on-tap=\"_resetTimer\">Reset</paper-button>\n </div>\n </paper-card>\n "]); _templateObject_d1cce2c0c3a011e99204fd28bf05b7e9 = function _templateObject_d1cce2c0c3a011e99204fd28bf05b7e9() { return data; }; return data; } /** `silly-hax-game` An example web component of gamifying HAX to make it more fun and challenging. * @demo demo/index.html */ var SillyHaxGame = (0, _polymerLegacy.Polymer)({ _template: (0, _polymerLegacy.html)(_templateObject_d1cce2c0c3a011e99204fd28bf05b7e9()), is: "silly-hax-game", properties: { /** * tasks to accomplish */ tasks: { type: Array, value: [] }, /** * haxText */ haxText: { type: String, computed: "_haxTextValue(timer)" }, /** * __score board */ __score: { type: Array, value: [] }, /** * tweet */ tweet: { type: String }, /** * Timer as updated via downstream */ timer: { type: Number }, /** * Playing the game or not. */ playing: { type: Boolean, value: !1, observer: "_playGame", reflectToAttribute: !0 } }, /** * Play button */ _playButton: function _playButton(e) { if (!this.playing) { this.playing = !0; this.$.timer.start(); } }, /** * _playGame */ _playGame: function _playGame(newValue, oldValue) { if (newValue) { this.__started = !0; this.set("tasks", []); this.push("tasks", { value: !1, label: "Start to edit with HAX", disabled: !0, id: "play" }, { value: !1, label: "Embed a video by Searching for it", disabled: !0, id: "youtube" }, { value: !1, label: "Turn a NASA image into a meme", disabled: !0, id: "nasa" }, { value: !1, label: "Saved content!!!", disabled: !0, id: "saved" }); } }, /** * Reset the timer to play again */ _resetTimer: function _resetTimer(e) { this.$.timer.pause(); this.playing = !1; this.timer = 0; this.set("tasks", []); }, _haxTextValue: function _haxTextValue(time) { if (babelHelpers.typeof(time) === babelHelpers.typeof(void 0) || 60 == time) { return "Take the HAX challenge"; } else { return time.toFixed(2); } }, /** * Attached to the DOM, now fire. */ attached: function attached() { document.body.addEventListener("hax-body-tag-added", this._verifyAction.bind(this)); document.body.addEventListener("hax-store-property-updated", this._propertyUpdated.bind(this)); }, /** * Property updated in the hax store. */ _propertyUpdated: function _propertyUpdated(e) { switch (e.detail.property) { case "editMode": if (this.playing && this.__started && e.detail.value && babelHelpers.typeof(this.tasks[0].label) !== babelHelpers.typeof(void 0)) { this.set("tasks.0.value", !0); this.set("tasks.0.label", this.tasks[0].label + " - " + this.timer.toFixed(2) + " seconds"); } else if (!1 === e.detail.value && this.__started && this.playing) { this.set("tasks." + (parseInt(this.tasks.length) - 1) + ".value", !0); this.set("tasks." + (parseInt(this.tasks.length) - 1) + ".label", this.tasks[parseInt(this.tasks.length) - 1].label + " - " + this.timer.toFixed(2) + " seconds"); this.$.timer.pause(); this._verifyWin(); } break; } }, /** * Verify if they won! */ _verifyWin: function _verifyWin() { var win = !0, winning = 0; this.set("__score", this.tasks); for (var i in this.tasks) { if (!this.tasks[i].value) { win = !1; } else { winning++; } } if (0 === this.timer) { win = !1; this.push("__score", { value: !1, label: "You ran out of time :(", disabled: !0, id: "time" }); } else if (!win) { this.push("__score", { value: !1, label: "You didn't complete everything. CHEATER!", disabled: !0, id: "cheater" }); } else { this.push("__score", { value: !0, label: "You did it!!! <(:) Much Success!", disabled: !0, id: "time" }); winning++; } if (!win) { this.__successText = ":( You have much sadness by only completing " + winning + " of the available " + this.tasks.length + " challenges. If you experienced confusion when using the interface for certain tasks please let us know! We want everyone to be able to master HAX."; this.tweet = "http://twitter.com/home?status=" + encodeURIComponent("I took the #HaxtheWeb Challenge and finished " + winning + " challenges! Take the challenge at http://haxtheweb.org/ !"); } else { this.__successText = "YOU ARE A HAX MASTER! YOU BEAT ALL " + this.tasks.length + " CHALLENGES. AM I USING ENOUGH CAPSLOCK!? YOU BET I AM! TWEET YOUR SUCCESS NOW!"; this.tweet = "http://twitter.com/home?status=" + encodeURIComponent("I are winning! I beat the #HaxtheWeb Challenge in " + this.timer.toFixed(2) + " seconds. Now I drink more coffee and code less! Take the challenge at http://haxtheweb.org/ !"); } var c = document.createElement("div"); c.innerHTML = "<p>".concat(this.__successText, "\n <a href=\"https://github.com/elmsln/lrnwebcomponents/issues/new\" target=\"_blank\" style=\"text-decoration: none;text-transform: none;\"><paper-button raised=\"\">Give us feedback to improve</paper-button></a>\n <a href=\"").concat(this.tweet, "\" target=\"_blank\" style=\"text-decoration: none;text-transform: none;\"><paper-button raised=\"\">Tweet your score</paper-button></a>\n </p>"); var todo = document.createElement("to-do"); todo.setAttribute("hide-form", "hide-form"); todo.setAttribute("name", "Report card"); todo.setAttribute("items", JSON.stringify(this.__score, null, 2)); c.appendChild(todo); var evt = new CustomEvent("simple-modal-show", { bubbles: !0, cancelable: !0, detail: { title: "HAX Challenge score", elements: { content: c }, invokedBy: this.$.play, clone: !0 } }); this.dispatchEvent(evt); }, /** * Verify that different tasks have been completed. */ _verifyAction: function _verifyAction(e) { if (this.playing && this.__started) { if ("VIDEO-PLAYER" === e.detail.node.tagName) { this.set("tasks.1.value", !0); this.set("tasks.1.label", this.tasks[1].label + " - " + this.timer.toFixed(2) + " seconds"); } else if ("MEME-MAKER" === e.detail.node.tagName) { this.set("tasks.2.value", !0); this.set("tasks.2.label", this.tasks[2].label + " - " + this.timer.toFixed(2) + " seconds"); } } } }); _exports.SillyHaxGame = SillyHaxGame; });
const path = require('path'); const { createFilePath } = require('gatsby-source-filesystem'); exports.onCreateNode = ({ node, getNode, actions }) => { const { createNodeField } = actions; if (node.internal.type === 'JavascriptFrontmatter') { const slug = createFilePath({ node, getNode, basePath: 'pages' }); createNodeField({ node, name: 'slug', value: slug, }); createNodeField({ node, name: 'domain', value: getDomain(slug), }); createNodeField({ node, name: 'underConstruction', value: Boolean(node.frontmatter.underConstruction), }); } }; exports.createPages = ({ graphql, actions }) => { const { createPage } = actions; return new Promise((resolve, reject) => { graphql(` { allJavascriptFrontmatter { edges { node { fileAbsolutePath fields { slug underConstruction } frontmatter { layout } } } } } `).then(result => { result.data.allJavascriptFrontmatter.edges .filter(({ node }) => node.fileAbsolutePath.match(/\/pages\//)) .forEach(({ node }) => { createPage({ path: node.fields.slug, component: path.resolve(`./src/templates/${node.fields.underConstruction ? "under-construction" : node.frontmatter.layout}.tsx`), context: { slug: node.fields.slug, } }); }); resolve(); }) }); } function getDomain(slug) { const domains = [ { name: 'plastics', pattern: /^\/plastics\// }, { name: 'energy', pattern: /^\/energy\// }, { name: 'engineering', pattern: /^\/engineering\// }, { name: 'metalPackaging', pattern: /^\/metal-packaging\// }, { name: 'group', pattern: '/' }, ]; return domains.find(d => slug.match(d.pattern)).name; } function getLayout(slug) { const layouts = [ { layout: '/app-plastics/', pattern: /^\/plastics\// }, { layout: '/app-energy/', pattern: /^\/energy\// }, { layout: '/app-engineering/', pattern: /^\/engineering\// }, { layout: '/app-metal-packaging/', pattern: /^\/metal-packaging\// }, { layout: '/app/', pattern: '/' }, ]; return layouts.find(l => slug.match(l.pattern)).layout; }
// Copyright (C) 2015 André Bargull. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-function-definitions-static-semantics-early-errors description: > A SyntaxError is thrown if a function contains a non-simple parameter list and a UseStrict directive. info: > Static Semantics: Early Errors It is a Syntax Error if ContainsUseStrict of FunctionBody is true and IsSimpleParameterList of FormalParameters is false. negative: phase: early type: SyntaxError ---*/ throw "Test262: This statement should not be evaluated."; var f = function(a = 0) { "use strict"; }
import inspect import os import jug.task from .task_reset import task_reset_at_exit, task_reset from .utils import simple_execute _jugdir = os.path.abspath(inspect.getfile(inspect.currentframe())) _jugdir = os.path.join(os.path.dirname(_jugdir), 'jugfiles') Task = jug.task.Task def add1(x): return x + 1 def add2(x): return x + 2 def _assert_tsorted(tasks): from itertools import chain for i,ti in enumerate(tasks): for j,tj in enumerate(tasks[i+1:]): for dep in chain(ti.args, ti.kwargs.values()): if type(dep) is list: assert tj not in dep else: assert tj is not dep @task_reset def test_topological_sort(): bases = [jug.task.Task(add1,i) for i in range(10)] derived = [jug.task.Task(add1,t) for t in bases] derived2 = [jug.task.Task(add1,t) for t in derived] derived3 = [jug.task.Task(add1,t) for t in derived] alltasks = bases + derived jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks.reverse() jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks = bases + derived alltasks.reverse() jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks = derived + bases jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks = derived + bases + derived2 jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) + len(derived2) _assert_tsorted(alltasks) alltasks = derived + bases + derived2 + derived3 jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) + len(derived2) + len(derived3) _assert_tsorted(alltasks) @task_reset def test_topological_sort_kwargs(): def add2(x): return x + 2 def sumlst(lst,param): return sum(lst) bases = [jug.task.Task(add2,x=i) for i in range(10)] derived = [jug.task.Task(sumlst,lst=bases,param=p) for p in range(4)] alltasks = bases + derived jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks.reverse() jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks = bases + derived alltasks.reverse() jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) alltasks = derived + bases jug.task.topological_sort(alltasks) assert len(alltasks) == len(bases) + len(derived) _assert_tsorted(alltasks) def data(): return list(range(20)) def mult(r,f): return [f*rr for rr in r] def reduce(r): return sum(r) @task_reset def test_topological_sort_canrun(): Task = jug.task.Task input = Task(data) for f in range(80): Task(reduce, Task(mult,input,f)) alltasks = jug.task.alltasks jug.task.topological_sort(alltasks) assert len(alltasks) == len(set(t.hash() for t in alltasks)) for t in alltasks: assert t.can_run() t.run() @task_reset def test_load_after_run(): T = jug.task.Task(add1,1) T.run() assert T.can_load() @task_reset def test_hash_same_func(): T0 = jug.task.Task(add1,0) T1 = jug.task.Task(add1,1) assert T0.hash() != T1.hash() @task_reset def test_hash_different_func(): T0 = jug.task.Task(add1,0) T1 = jug.task.Task(add2,0) assert T0.hash() != T1.hash() @task_reset def test_taskgenerator(): @jug.task.TaskGenerator def double(x): return 2*x T=double(2) assert type(T) == jug.task.Task @task_reset def test_unload(): T0 = jug.task.Task(add1,0) assert not hasattr(T0, '_result') assert T0.can_run() T0.run() assert hasattr(T0, '_result') assert T0.result == 1 T0.unload() assert T0.result == 1 @task_reset def test_unload_recursive(): T0 = jug.task.Task(add1,0) T1 = jug.task.Task(add1,T0) T2 = jug.task.Task(add1,T1) assert not hasattr(T0, '_result') T0.run() T1.run() T2.run() assert hasattr(T0, '_result') T2.unload_recursive() assert not hasattr(T0, '_result') def identity(x): return x @task_reset def test_cachedfunction(): assert jug.task.CachedFunction(identity,123) == 123 assert jug.task.CachedFunction(identity,'mixture') == 'mixture' @task_reset def test_npyload(): import numpy as np A = np.arange(23) assert np.all(jug.task.CachedFunction(identity,A) == A) @jug.task.TaskGenerator def double(x): return 2 * x @task_reset def test_value(): two = double(1) four = double(two) eight = double(four) two.run() four.run() eight.run() assert jug.task.value(eight) == 8 @task_reset def test_dict_sort_run(): tasks = [double(1), double(2), Task(identity,2) ] tasks += [Task(identity,{ 'one' : tasks[2], 'two' : tasks[0], 'three' : { 1 : tasks[1], 0 : tasks[0] }})] jug.task.topological_sort(tasks) for t in tasks: assert t.can_run() t.run() assert tasks[-1].result == { 'one' : 2, 'two' : 2, 'three' : {1 : 4, 0: 2}} @task_reset def test_unload_recursive_result_property(): two = double(1) four = double(two) two.run() four.run() four.unload_recursive () assert not hasattr(four, '_result') assert not hasattr(two, '_result') # Crashed in version 0.7.3 @task_reset def test_unload_wnoresult(): t = Task(add2, 3) t.unload() @task_reset def test_starts_unloaded(): t = Task(add2, 3) assert not t.is_loaded() @task_reset def test__str__repr__(): t = Task(add2, 3) assert str(t).find('add2') >= 0 assert repr(t).find('add2') >= 0 assert repr(t).find('3') >= 0 def add_tuple(a_b): a,b = a_b return a + b @task_reset def test_unload_recursive_tuple(): T0 = jug.task.Task(add1,0) T1 = jug.task.Task(add1,T0) T2 = jug.task.Task(add_tuple,(T0,T1)) T3 = jug.task.Task(add1, T2) assert not hasattr(T0, '_result') T0.run() T1.run() T2.run() T3.run() assert hasattr(T0, '_result') T3.unload_recursive() assert not hasattr(T0, '_result') @task_reset def test_builtin_function(): import numpy as np jugfile = os.path.join(_jugdir, 'builtin_function.py') store, space = jug.jug.init(jugfile, 'dict_store') simple_execute() a8 = jug.task.value(space['a8']) assert np.all(a8 == np.arange(8))
""" Django settings for Jagrati project. Generated by 'django-admin startproject' using Django 2.2.6. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os from decouple import config # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'imagekit', 'django_cleanup.apps.CleanupConfig', 'rest_framework', 'rest_framework.authtoken', 'social_django', 'django_extensions', 'home', 'accounts', 'apps.students', 'apps.volunteers', 'apps.feedbacks', 'apps.events', 'apps.misc', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework.authentication.TokenAuthentication', ], 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAuthenticated', ], } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'Jagrati.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/', os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', # for accessing models from templates... Or Use Inclusion Tags 'home.context_processors.database_context', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'Jagrati.wsgi.application' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.google.GoogleOAuth2' ] # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Kolkata' USE_I18N = True USE_L10N = False # Is false in AlumniConnect USE_TZ = True DATE_FORMAT = 'Y-m-d' LOGIN_REDIRECT_URL = '/' AUTH_USER_MODEL = 'accounts.User' # DJANGO_EXTENSIONS settings SHELL_PLUS_PRINT_SQL = True # GOOGLE_OAUTH settings SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = config("SOCIAL_AUTH_GOOGLE_OAUTH2_KEY") SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = config("SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET") CORS_ORIGIN_ALLOW_ALL = True
//begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery //begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery begin jquery /*! jQuery v1.12.4 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=a.document,e=c.slice,f=c.concat,g=c.push,h=c.indexOf,i={},j=i.toString,k=i.hasOwnProperty,l={},m="1.12.4",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return e.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:e.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a){return n.each(this,a)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(e.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:g,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){var b=a&&a.toString();return!n.isArray(a)&&b-parseFloat(b)+1>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!k.call(a,"constructor")&&!k.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(!l.ownFirst)for(b in a)return k.call(a,b);for(b in a);return void 0===b||k.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?i[j.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(s(a)){for(c=a.length;c>d;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):g.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(h)return h.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,g=0,h=[];if(s(a))for(d=a.length;d>g;g++)e=b(a[g],g,c),null!=e&&h.push(e);else for(g in a)e=b(a[g],g,c),null!=e&&h.push(e);return f.apply([],h)},guid:1,proxy:function(a,b){var c,d,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=e.call(arguments,2),d=function(){return a.apply(b||this,c.concat(e.call(arguments)))},d.guid=a.guid=a.guid||n.guid++,d):void 0},now:function(){return+new Date},support:l}),"function"==typeof Symbol&&(n.fn[Symbol.iterator]=c[Symbol.iterator]),n.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){i["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=!!a&&"length"in a&&a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ga(),z=ga(),A=ga(),B=function(a,b){return a===b&&(l=!0),0},C=1<<31,D={}.hasOwnProperty,E=[],F=E.pop,G=E.push,H=E.push,I=E.slice,J=function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},K="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",L="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",N="\\["+L+"*("+M+")(?:"+L+"*([*^$|!~]?=)"+L+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+M+"))|)"+L+"*\\]",O=":("+M+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+N+")*)|.*)\\)|)",P=new RegExp(L+"+","g"),Q=new RegExp("^"+L+"+|((?:^|[^\\\\])(?:\\\\.)*)"+L+"+$","g"),R=new RegExp("^"+L+"*,"+L+"*"),S=new RegExp("^"+L+"*([>+~]|"+L+")"+L+"*"),T=new RegExp("="+L+"*([^\\]'\"]*?)"+L+"*\\]","g"),U=new RegExp(O),V=new RegExp("^"+M+"$"),W={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),TAG:new RegExp("^("+M+"|[*])"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+L+"*(even|odd|(([+-]|)(\\d*)n|)"+L+"*(?:([+-]|)"+L+"*(\\d+)|))"+L+"*\\)|)","i"),bool:new RegExp("^(?:"+K+")$","i"),needsContext:new RegExp("^"+L+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+L+"*((?:-\\d)?\\d*)"+L+"*\\)|)(?=[^-]|$)","i")},X=/^(?:input|select|textarea|button)$/i,Y=/^h\d$/i,Z=/^[^{]+\{\s*\[native \w/,$=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,_=/[+~]/,aa=/'|\\/g,ba=new RegExp("\\\\([\\da-f]{1,6}"+L+"?|("+L+")|.)","ig"),ca=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},da=function(){m()};try{H.apply(E=I.call(v.childNodes),v.childNodes),E[v.childNodes.length].nodeType}catch(ea){H={apply:E.length?function(a,b){G.apply(a,I.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fa(a,b,d,e){var f,h,j,k,l,o,r,s,w=b&&b.ownerDocument,x=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==x&&9!==x&&11!==x)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==x&&(o=$.exec(a)))if(f=o[1]){if(9===x){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(w&&(j=w.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(o[2])return H.apply(d,b.getElementsByTagName(a)),d;if((f=o[3])&&c.getElementsByClassName&&b.getElementsByClassName)return H.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==x)w=b,s=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(aa,"\\$&"):b.setAttribute("id",k=u),r=g(a),h=r.length,l=V.test(k)?"#"+k:"[id='"+k+"']";while(h--)r[h]=l+" "+qa(r[h]);s=r.join(","),w=_.test(a)&&oa(b.parentNode)||b}if(s)try{return H.apply(d,w.querySelectorAll(s)),d}catch(y){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(Q,"$1"),b,d,e)}function ga(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ha(a){return a[u]=!0,a}function ia(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ja(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function ka(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||C)-(~a.sourceIndex||C);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function la(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function na(a){return ha(function(b){return b=+b,ha(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function oa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=fa.support={},f=fa.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fa.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ia(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ia(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Z.test(n.getElementsByClassName),c.getById=ia(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ba,ca);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return"undefined"!=typeof b.getElementsByClassName&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=Z.test(n.querySelectorAll))&&(ia(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ia(function(a){var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Z.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ia(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",O)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Z.test(o.compareDocumentPosition),t=b||Z.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return ka(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?ka(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},fa.matches=function(a,b){return fa(a,null,null,b)},fa.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(T,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fa(b,n,null,[a]).length>0},fa.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fa.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fa.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fa.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fa.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fa.selectors={cacheLength:50,createPseudo:ha,match:W,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ba,ca),a[3]=(a[3]||a[4]||a[5]||"").replace(ba,ca),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fa.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fa.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return W.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&U.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ba,ca).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fa.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(P," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fa.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ha(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ha(function(a){var b=[],c=[],d=h(a.replace(Q,"$1"));return d[u]?ha(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ha(function(a){return function(b){return fa(a,b).length>0}}),contains:ha(function(a){return a=a.replace(ba,ca),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ha(function(a){return V.test(a||"")||fa.error("unsupported lang: "+a),a=a.replace(ba,ca).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Y.test(a.nodeName)},input:function(a){return X.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:na(function(){return[0]}),last:na(function(a,b){return[b-1]}),eq:na(function(a,b,c){return[0>c?c+b:c]}),even:na(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:na(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:na(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:na(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=la(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=ma(b);function pa(){}pa.prototype=d.filters=d.pseudos,d.setFilters=new pa,g=fa.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=R.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=S.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(Q," ")}),h=h.slice(c.length));for(g in d.filter)!(e=W[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?fa.error(a):z(a,i).slice(0)};function qa(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function ra(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(j=b[u]||(b[u]={}),i=j[b.uniqueID]||(j[b.uniqueID]={}),(h=i[d])&&h[0]===w&&h[1]===f)return k[2]=h[2];if(i[d]=k,k[2]=a(b,c,g))return!0}}}function sa(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ta(a,b,c){for(var d=0,e=b.length;e>d;d++)fa(a,b[d],c);return c}function ua(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function va(a,b,c,d,e,f){return d&&!d[u]&&(d=va(d)),e&&!e[u]&&(e=va(e,f)),ha(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ta(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ua(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ua(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ua(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function wa(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ra(function(a){return a===b},h,!0),l=ra(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[ra(sa(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return va(i>1&&sa(m),i>1&&qa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(Q,"$1"),c,e>i&&wa(a.slice(i,e)),f>e&&wa(a=a.slice(e)),f>e&&qa(a))}m.push(c)}return sa(m)}function xa(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=F.call(i));u=ua(u)}H.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&fa.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ha(f):f}return h=fa.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wa(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xa(e,d)),f.selector=a}return f},i=fa.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(ba,ca),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=W.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(ba,ca),_.test(j[0].type)&&oa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qa(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||_.test(a)&&oa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ia(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ia(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ja("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ia(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ja("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ia(function(a){return null==a.getAttribute("disabled")})||ja(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fa}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.uniqueSort=n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},v=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},w=n.expr.match.needsContext,x=/^<([\w-]+)\s*\/?>(?:<\/\1>|)$/,y=/^.[^:#\[\.,]*$/;function z(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(y.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>-1!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(z(this,a||[],!1))},not:function(a){return this.pushStack(z(this,a||[],!0))},is:function(a){return!!z(this,"string"==typeof a&&w.test(a)?n(a):a||[],!1).length}});var A,B=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=n.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||A,"string"==typeof a){if(e="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:B.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),x.test(e[1])&&n.isPlainObject(b))for(e in b)n.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}if(f=d.getElementById(e[2]),f&&f.parentNode){if(f.id!==e[2])return A.find(a);this.length=1,this[0]=f}return this.context=d,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof c.ready?c.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};C.prototype=n.fn,A=n(d);var D=/^(?:parents|prev(?:Until|All))/,E={children:!0,contents:!0,next:!0,prev:!0};n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=w.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.uniqueSort(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function F(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return u(a,"parentNode")},parentsUntil:function(a,b,c){return u(a,"parentNode",c)},next:function(a){return F(a,"nextSibling")},prev:function(a){return F(a,"previousSibling")},nextAll:function(a){return u(a,"nextSibling")},prevAll:function(a){return u(a,"previousSibling")},nextUntil:function(a,b,c){return u(a,"nextSibling",c)},prevUntil:function(a,b,c){return u(a,"previousSibling",c)},siblings:function(a){return v((a.parentNode||{}).firstChild,a)},children:function(a){return v(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(E[a]||(e=n.uniqueSort(e)),D.test(a)&&(e=e.reverse())),this.pushStack(e)}});var G=/\S+/g;function H(a){var b={};return n.each(a.match(G)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?H(a):n.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){n.each(b,function(b,c){n.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==n.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return n.each(arguments,function(a,b){var c;while((c=n.inArray(b,f,c))>-1)f.splice(c,1),h>=c&&h--}),this},has:function(a){return a?n.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=!0,c||j.disable(),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().progress(c.notify).done(c.resolve).fail(c.reject):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=e.call(arguments),d=c.length,f=1!==d||a&&n.isFunction(a.promise)?d:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(d){b[a]=this,c[a]=arguments.length>1?e.call(arguments):d,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(d>1)for(i=new Array(d),j=new Array(d),k=new Array(d);d>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().progress(h(b,j,i)).done(h(b,k,c)).fail(g.reject):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(d,[n]),n.fn.triggerHandler&&(n(d).triggerHandler("ready"),n(d).off("ready"))))}});function J(){d.addEventListener?(d.removeEventListener("DOMContentLoaded",K),a.removeEventListener("load",K)):(d.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(d.addEventListener||"load"===a.event.type||"complete"===d.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll)a.setTimeout(n.ready);else if(d.addEventListener)d.addEventListener("DOMContentLoaded",K),a.addEventListener("load",K);else{d.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&d.documentElement}catch(e){}c&&c.doScroll&&!function f(){if(!n.isReady){try{c.doScroll("left")}catch(b){return a.setTimeout(f,50)}J(),n.ready()}}()}return I.promise(b)},n.ready.promise();var L;for(L in n(l))break;l.ownFirst="0"===L,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c,e;c=d.getElementsByTagName("body")[0],c&&c.style&&(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",l.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(e))}),function(){var a=d.createElement("div");l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}a=null}();var M=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b},N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0; }return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(M(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),"object"!=typeof b&&"function"!=typeof b||(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f}}function S(a,b,c){if(M(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=void 0)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}}),function(){var a;l.shrinkWrapBlocks=function(){if(null!=a)return a;a=!1;var b,c,e;return c=d.getElementsByTagName("body")[0],c&&c.style?(b=d.createElement("div"),e=d.createElement("div"),e.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(e).appendChild(b),"undefined"!=typeof b.style.zoom&&(b.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",b.appendChild(d.createElement("div")).style.width="5px",a=3!==b.offsetWidth),c.removeChild(e),a):void 0}}();var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),V=["Top","Right","Bottom","Left"],W=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)};function X(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return n.css(a,b,"")},i=h(),j=c&&c[3]||(n.cssNumber[b]?"":"px"),k=(n.cssNumber[b]||"px"!==j&&+i)&&U.exec(n.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,n.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var Y=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)Y(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},Z=/^(?:checkbox|radio)$/i,$=/<([\w:-]+)/,_=/^$|\/(?:java|ecma)script/i,aa=/^\s+/,ba="abbr|article|aside|audio|bdi|canvas|data|datalist|details|dialog|figcaption|figure|footer|header|hgroup|main|mark|meter|nav|output|picture|progress|section|summary|template|time|video";function ca(a){var b=ba.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}!function(){var a=d.createElement("div"),b=d.createDocumentFragment(),c=d.createElement("input");a.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",l.leadingWhitespace=3===a.firstChild.nodeType,l.tbody=!a.getElementsByTagName("tbody").length,l.htmlSerialize=!!a.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==d.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,b.appendChild(c),l.appendChecked=c.checked,a.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!a.cloneNode(!0).lastChild.defaultValue,b.appendChild(a),c=d.createElement("input"),c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),a.appendChild(c),l.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!!a.addEventListener,a[n.expando]=1,l.attributes=!a.getAttribute(n.expando)}();var da={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]};da.optgroup=da.option,da.tbody=da.tfoot=da.colgroup=da.caption=da.thead,da.th=da.td;function ea(a,b){var c,d,e=0,f="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,ea(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function fa(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}var ga=/<|&#?\w+;/,ha=/<tbody/i;function ia(a){Z.test(a.type)&&(a.defaultChecked=a.checked)}function ja(a,b,c,d,e){for(var f,g,h,i,j,k,m,o=a.length,p=ca(b),q=[],r=0;o>r;r++)if(g=a[r],g||0===g)if("object"===n.type(g))n.merge(q,g.nodeType?[g]:g);else if(ga.test(g)){i=i||p.appendChild(b.createElement("div")),j=($.exec(g)||["",""])[1].toLowerCase(),m=da[j]||da._default,i.innerHTML=m[1]+n.htmlPrefilter(g)+m[2],f=m[0];while(f--)i=i.lastChild;if(!l.leadingWhitespace&&aa.test(g)&&q.push(b.createTextNode(aa.exec(g)[0])),!l.tbody){g="table"!==j||ha.test(g)?"<table>"!==m[1]||ha.test(g)?0:i:i.firstChild,f=g&&g.childNodes.length;while(f--)n.nodeName(k=g.childNodes[f],"tbody")&&!k.childNodes.length&&g.removeChild(k)}n.merge(q,i.childNodes),i.textContent="";while(i.firstChild)i.removeChild(i.firstChild);i=p.lastChild}else q.push(b.createTextNode(g));i&&p.removeChild(i),l.appendChecked||n.grep(ea(q,"input"),ia),r=0;while(g=q[r++])if(d&&n.inArray(g,d)>-1)e&&e.push(g);else if(h=n.contains(g.ownerDocument,g),i=ea(p.appendChild(g),"script"),h&&fa(i),c){f=0;while(g=i[f++])_.test(g.type||"")&&c.push(g)}return i=null,p}!function(){var b,c,e=d.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b]=c in a)||(e.setAttribute(c,"t"),l[b]=e.attributes[c].expando===!1);e=null}();var ka=/^(?:input|select|textarea)$/i,la=/^key/,ma=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,na=/^(?:focusinfocus|focusoutblur)$/,oa=/^([^.]*)(?:\.(.+)|)/;function pa(){return!0}function qa(){return!1}function ra(){try{return d.activeElement}catch(a){}}function sa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)sa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=qa;else if(!e)return a;return 1===f&&(g=e,e=function(a){return n().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=n.guid++)),a.each(function(){n.event.add(this,b,e,d,c)})}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return"undefined"==typeof n||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(G)||[""],h=b.length;while(h--)f=oa.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(G)||[""],j=b.length;while(j--)if(h=oa.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,e,f){var g,h,i,j,l,m,o,p=[e||d],q=k.call(b,"type")?b.type:b,r=k.call(b,"namespace")?b.namespace.split("."):[];if(i=m=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!na.test(q+n.event.triggered)&&(q.indexOf(".")>-1&&(r=q.split("."),q=r.shift(),r.sort()),h=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=r.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:n.makeArray(c,[b]),l=n.event.special[q]||{},f||!l.trigger||l.trigger.apply(e,c)!==!1)){if(!f&&!l.noBubble&&!n.isWindow(e)){for(j=l.delegateType||q,na.test(j+q)||(i=i.parentNode);i;i=i.parentNode)p.push(i),m=i;m===(e.ownerDocument||d)&&p.push(m.defaultView||m.parentWindow||a)}o=0;while((i=p[o++])&&!b.isPropagationStopped())b.type=o>1?j:l.bindType||q,g=(n._data(i,"events")||{})[b.type]&&n._data(i,"handle"),g&&g.apply(i,c),g=h&&i[h],g&&g.apply&&M(i)&&(b.result=g.apply(i,c),b.result===!1&&b.preventDefault());if(b.type=q,!f&&!b.isDefaultPrevented()&&(!l._default||l._default.apply(p.pop(),c)===!1)&&M(e)&&h&&e[q]&&!n.isWindow(e)){m=e[h],m&&(e[h]=null),n.event.triggered=q;try{e[q]()}catch(s){}n.event.triggered=void 0,m&&(e[h]=m)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,d,f,g,h=[],i=e.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())a.rnamespace&&!a.rnamespace.test(g.namespace)||(a.handleObj=g,a.data=g.data,d=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==d&&(a.result=d)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>-1:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,e,f=a.type,g=a,h=this.fixHooks[f];h||(this.fixHooks[f]=h=ma.test(f)?this.mouseHooks:la.test(f)?this.keyHooks:{}),e=h.props?this.props.concat(h.props):this.props,a=new n.Event(g),b=e.length;while(b--)c=e[b],a[c]=g[c];return a.target||(a.target=g.srcElement||d),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,h.filter?h.filter(a,g):a},props:"altKey bubbles cancelable ctrlKey currentTarget detail eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,e,f,g=b.button,h=b.fromElement;return null==a.pageX&&null!=b.clientX&&(e=a.target.ownerDocument||d,f=e.documentElement,c=e.body,a.pageX=b.clientX+(f&&f.scrollLeft||c&&c.scrollLeft||0)-(f&&f.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(f&&f.scrollTop||c&&c.scrollTop||0)-(f&&f.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&h&&(a.relatedTarget=h===a.target?b.toElement:h),a.which||void 0===g||(a.which=1&g?1:2&g?3:4&g?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==ra()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===ra()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c){var d=n.extend(new n.Event,c,{type:a,isSimulated:!0});n.event.trigger(d,null,b),d.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=d.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)}:function(a,b,c){var d="on"+b;a.detachEvent&&("undefined"==typeof a[d]&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?pa:qa):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={constructor:n.Event,isDefaultPrevented:qa,isPropagationStopped:qa,isImmediatePropagationStopped:qa,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=pa,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=pa,a&&!this.isSimulated&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=pa,a&&a.stopImmediatePropagation&&a.stopImmediatePropagation(),this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||n.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submit||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?n.prop(b,"form"):void 0;c&&!n._data(c,"submit")&&(n.event.add(c,"submit._submit",function(a){a._submitBubble=!0}),n._data(c,"submit",!0))})},postDispatch:function(a){a._submitBubble&&(delete a._submitBubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.change||(n.event.special.change={setup:function(){return ka.test(this.nodeName)?("checkbox"!==this.type&&"radio"!==this.type||(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._justChanged=!0)}),n.event.add(this,"click._change",function(a){this._justChanged&&!a.isTrigger&&(this._justChanged=!1),n.event.simulate("change",this,a)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;ka.test(b.nodeName)&&!n._data(b,"change")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a)}),n._data(b,"change",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!ka.test(this.nodeName)}}),l.focusin||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a))};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d){return sa(this,a,b,c,d)},one:function(a,b,c,d){return sa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=qa),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});var ta=/ jQuery\d+="(?:null|\d+)"/g,ua=new RegExp("<(?:"+ba+")[\\s/>]","i"),va=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi,wa=/<script|<style|<link/i,xa=/checked\s*(?:[^=]|=\s*.checked.)/i,ya=/^true\/(.*)/,za=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Aa=ca(d),Ba=Aa.appendChild(d.createElement("div"));function Ca(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function Da(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function Ea(a){var b=ya.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Ga(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(Da(b).text=a.text,Ea(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&Z.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}}function Ha(a,b,c,d){b=f.apply([],b);var e,g,h,i,j,k,m=0,o=a.length,p=o-1,q=b[0],r=n.isFunction(q);if(r||o>1&&"string"==typeof q&&!l.checkClone&&xa.test(q))return a.each(function(e){var f=a.eq(e);r&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(o&&(k=ja(b,a[0].ownerDocument,!1,a,d),e=k.firstChild,1===k.childNodes.length&&(k=e),e||d)){for(i=n.map(ea(k,"script"),Da),h=i.length;o>m;m++)g=k,m!==p&&(g=n.clone(g,!0,!0),h&&n.merge(i,ea(g,"script"))),c.call(a[m],g,m);if(h)for(j=i[i.length-1].ownerDocument,n.map(i,Ea),m=0;h>m;m++)g=i[m],_.test(g.type||"")&&!n._data(g,"globalEval")&&n.contains(j,g)&&(g.src?n._evalUrl&&n._evalUrl(g.src):n.globalEval((g.text||g.textContent||g.innerHTML||"").replace(za,"")));k=e=null}return a}function Ia(a,b,c){for(var d,e=b?n.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||n.cleanData(ea(d)),d.parentNode&&(c&&n.contains(d.ownerDocument,d)&&fa(ea(d,"script")),d.parentNode.removeChild(d));return a}n.extend({htmlPrefilter:function(a){return a.replace(va,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!ua.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(Ba.innerHTML=a.outerHTML,Ba.removeChild(f=Ba.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=ea(f),h=ea(a),g=0;null!=(e=h[g]);++g)d[g]&&Ga(e,d[g]);if(b)if(c)for(h=h||ea(a),d=d||ea(f),g=0;null!=(e=h[g]);g++)Fa(e,d[g]);else Fa(a,f);return d=ea(f,"script"),d.length>0&&fa(d,!i&&ea(a,"script")),d=h=e=null,f},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.attributes,m=n.event.special;null!=(d=a[h]);h++)if((b||M(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k||"undefined"==typeof d.removeAttribute?d[i]=void 0:d.removeAttribute(i),c.push(f))}}}),n.fn.extend({domManip:Ha,detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return Y(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||d).createTextNode(a))},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(ea(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return Y(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(ta,""):void 0;if("string"==typeof a&&!wa.test(a)&&(l.htmlSerialize||!ua.test(a))&&(l.leadingWhitespace||!aa.test(a))&&!da[($.exec(a)||["",""])[1].toLowerCase()]){a=n.htmlPrefilter(a);try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ea(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;n.inArray(this,a)<0&&(n.cleanData(ea(this)),c&&c.replaceChild(b,this))},a)}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],f=n(a),h=f.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(f[d])[b](c),g.apply(e,c.get());return this.pushStack(e)}});var Ja,Ka={HTML:"block",BODY:"block"};function La(a,b){var c=n(b.createElement(a)).appendTo(b.body),d=n.css(c[0],"display");return c.detach(),d}function Ma(a){var b=d,c=Ka[a];return c||(c=La(a,b),"none"!==c&&c||(Ja=(Ja||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Ja[0].contentWindow||Ja[0].contentDocument).document,b.write(),b.close(),c=La(a,b),Ja.detach()),Ka[a]=c),c}var Na=/^margin/,Oa=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Pa=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e},Qa=d.documentElement;!function(){var b,c,e,f,g,h,i=d.createElement("div"),j=d.createElement("div");if(j.style){j.style.cssText="float:left;opacity:.5",l.opacity="0.5"===j.style.opacity,l.cssFloat=!!j.style.cssFloat,j.style.backgroundClip="content-box",j.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===j.style.backgroundClip,i=d.createElement("div"),i.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",j.innerHTML="",i.appendChild(j),l.boxSizing=""===j.style.boxSizing||""===j.style.MozBoxSizing||""===j.style.WebkitBoxSizing,n.extend(l,{reliableHiddenOffsets:function(){return null==b&&k(),f},boxSizingReliable:function(){return null==b&&k(),e},pixelMarginRight:function(){return null==b&&k(),c},pixelPosition:function(){return null==b&&k(),b},reliableMarginRight:function(){return null==b&&k(),g},reliableMarginLeft:function(){return null==b&&k(),h}});function k(){var k,l,m=d.documentElement;m.appendChild(i),j.style.cssText="-webkit-box-sizing:border-box;box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",b=e=h=!1,c=g=!0,a.getComputedStyle&&(l=a.getComputedStyle(j),b="1%"!==(l||{}).top,h="2px"===(l||{}).marginLeft,e="4px"===(l||{width:"4px"}).width,j.style.marginRight="50%",c="4px"===(l||{marginRight:"4px"}).marginRight,k=j.appendChild(d.createElement("div")),k.style.cssText=j.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",k.style.marginRight=k.style.width="0",j.style.width="1px",g=!parseFloat((a.getComputedStyle(k)||{}).marginRight),j.removeChild(k)),j.style.display="none",f=0===j.getClientRects().length,f&&(j.style.display="",j.innerHTML="<table><tr><td></td><td>t</td></tr></table>",j.childNodes[0].style.borderCollapse="separate",k=j.getElementsByTagName("td"),k[0].style.cssText="margin:0;border:0;padding:0;display:none",f=0===k[0].offsetHeight,f&&(k[0].style.display="",k[1].style.display="none",f=0===k[0].offsetHeight)),m.removeChild(i)}}}();var Ra,Sa,Ta=/^(top|right|bottom|left)$/;a.getComputedStyle?(Ra=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c.getPropertyValue(b)||c[b]:void 0,""!==g&&void 0!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),c&&!l.pixelMarginRight()&&Oa.test(g)&&Na.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f),void 0===g?g:g+""}):Qa.currentStyle&&(Ra=function(a){return a.currentStyle},Sa=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Ra(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Oa.test(g)&&!Ta.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Ua(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Va=/alpha\([^)]*\)/i,Wa=/opacity\s*=\s*([^)]*)/i,Xa=/^(none|table(?!-c[ea]).+)/,Ya=new RegExp("^("+T+")(.*)$","i"),Za={position:"absolute",visibility:"hidden",display:"block"},$a={letterSpacing:"0",fontWeight:"400"},_a=["Webkit","O","Moz","ms"],ab=d.createElement("div").style;function bb(a){if(a in ab)return a;var b=a.charAt(0).toUpperCase()+a.slice(1),c=_a.length;while(c--)if(a=_a[c]+b,a in ab)return a}function cb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&W(d)&&(f[g]=n._data(d,"olddisplay",Ma(d.nodeName)))):(e=W(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function db(a,b,c){var d=Ya.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function eb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+V[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+V[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+V[f]+"Width",!0,e))):(g+=n.css(a,"padding"+V[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+V[f]+"Width",!0,e)));return g}function fb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Ra(a),g=l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Sa(a,b,f),(0>e||null==e)&&(e=a.style[b]),Oa.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+eb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Sa(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=U.exec(c))&&e[1]&&(c=X(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(n.cssNumber[h]?"":"px")),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=bb(h)||h),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Sa(a,b,d)),"normal"===f&&b in $a&&(f=$a[b]),""===c||c?(e=parseFloat(f),c===!0||isFinite(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?Xa.test(n.css(a,"display"))&&0===a.offsetWidth?Pa(a,Za,function(){return fb(a,b,d)}):fb(a,b,d):void 0},set:function(a,c,d){var e=d&&Ra(a);return db(a,c,d?eb(a,b,d,l.boxSizing&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Wa.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Va,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Va.test(f)?f.replace(Va,e):f+" "+e)}}),n.cssHooks.marginRight=Ua(l.reliableMarginRight,function(a,b){return b?Pa(a,{display:"inline-block"},Sa,[a,"marginRight"]):void 0}),n.cssHooks.marginLeft=Ua(l.reliableMarginLeft,function(a,b){return b?(parseFloat(Sa(a,"marginLeft"))||(n.contains(a.ownerDocument,a)?a.getBoundingClientRect().left-Pa(a,{ marginLeft:0},function(){return a.getBoundingClientRect().left}):0))+"px":void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+V[d]+b]=f[d]||f[d-2]||f[0];return e}},Na.test(a)||(n.cssHooks[a+b].set=db)}),n.fn.extend({css:function(a,b){return Y(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Ra(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)},a,b,arguments.length>1)},show:function(){return cb(this,!0)},hide:function(){return cb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){W(this)?n(this).show():n(this).hide()})}});function gb(a,b,c,d,e){return new gb.prototype.init(a,b,c,d,e)}n.Tween=gb,gb.prototype={constructor:gb,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||n.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=gb.propHooks[this.prop];return a&&a.get?a.get(this):gb.propHooks._default.get(this)},run:function(a){var b,c=gb.propHooks[this.prop];return this.options.duration?this.pos=b=n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):gb.propHooks._default.set(this),this}},gb.prototype.init.prototype=gb.prototype,gb.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[n.cssProps[a.prop]]&&!n.cssHooks[a.prop]?a.elem[a.prop]=a.now:n.style(a.elem,a.prop,a.now+a.unit)}}},gb.propHooks.scrollTop=gb.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},n.fx=gb.prototype.init,n.fx.step={};var hb,ib,jb=/^(?:toggle|show|hide)$/,kb=/queueHooks$/;function lb(){return a.setTimeout(function(){hb=void 0}),hb=n.now()}function mb(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=V[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function nb(a,b,c){for(var d,e=(qb.tweeners[b]||[]).concat(qb.tweeners["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function ob(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&W(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k="none"===j?n._data(a,"olddisplay")||Ma(a.nodeName):j,"inline"===k&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==Ma(a.nodeName)?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],jb.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}else j=void 0;if(n.isEmptyObject(o))"inline"===("none"===j?Ma(a.nodeName):j)&&(p.display=j);else{r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=nb(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function pb(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function qb(a,b,c){var d,e,f=0,g=qb.prefilters.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=hb||lb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{},easing:n.easing._default},c),originalProperties:b,originalOptions:c,startTime:hb||lb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(pb(k,j.opts.specialEasing);g>f;f++)if(d=qb.prefilters[f].call(j,a,k,j.opts))return n.isFunction(d.stop)&&(n._queueHooks(j.elem,j.opts.queue).stop=n.proxy(d.stop,d)),d;return n.map(k,nb,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(qb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return X(c.elem,a,U.exec(b),c),c}]},tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.match(G);for(var c,d=0,e=a.length;e>d;d++)c=a[d],qb.tweeners[c]=qb.tweeners[c]||[],qb.tweeners[c].unshift(b)},prefilters:[ob],prefilter:function(a,b){b?qb.prefilters.unshift(a):qb.prefilters.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,null!=d.queue&&d.queue!==!0||(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(W).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=qb(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&kb.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(mb(b,!0),a,d,e)}}),n.each({slideDown:mb("show"),slideUp:mb("hide"),slideToggle:mb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(hb=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),hb=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ib||(ib=a.setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){a.clearInterval(ib),ib=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(b,c){return b=n.fx?n.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a,b=d.createElement("input"),c=d.createElement("div"),e=d.createElement("select"),f=e.appendChild(d.createElement("option"));c=d.createElement("div"),c.setAttribute("className","t"),c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],b.setAttribute("type","checkbox"),c.appendChild(b),a=c.getElementsByTagName("a")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==c.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=f.selected,l.enctype=!!d.createElement("form").enctype,e.disabled=!0,l.optDisabled=!f.disabled,b=d.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value}();var rb=/\r/g,sb=/[\x20\t\r\n\f]+/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(rb,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.trim(n.text(a)).replace(sb," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],(c.selected||i===e)&&(l.optDisabled?!c.disabled:null===c.getAttribute("disabled"))&&(!c.parentNode.disabled||!n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>-1)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>-1:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var tb,ub,vb=n.expr.attrHandle,wb=/^(?:checked|selected)$/i,xb=l.getSetAttribute,yb=l.input;n.fn.extend({attr:function(a,b){return Y(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),e=n.attrHooks[b]||(n.expr.match.bool.test(b)?ub:tb)),void 0!==c?null===c?void n.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=n.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(G);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?yb&&xb||!wb.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(xb?c:d)}}),ub={set:function(a,b,c){return b===!1?n.removeAttr(a,c):yb&&xb||!wb.test(c)?a.setAttribute(!xb&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=vb[b]||n.find.attr;yb&&xb||!wb.test(b)?vb[b]=function(a,b,d){var e,f;return d||(f=vb[b],vb[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,vb[b]=f),e}:vb[b]=function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),yb&&xb||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):tb&&tb.set(a,b,c)}}),xb||(tb={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},vb.id=vb.name=vb.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:tb.set},n.attrHooks.contenteditable={set:function(a,b,c){tb.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var zb=/^(?:input|select|textarea|button|object)$/i,Ab=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return Y(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&n.isXMLDoc(a)||(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):zb.test(a.nodeName)||Ab.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var Bb=/[\t\r\n\f]/g;function Cb(a){return n.attr(a,"class")||""}n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,Cb(this)))});if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,Cb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(G)||[];while(c=this[i++])if(e=Cb(c),d=1===c.nodeType&&(" "+e+" ").replace(Bb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=n.trim(d),e!==h&&n.attr(c,"class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):n.isFunction(a)?this.each(function(c){n(this).toggleClass(a.call(this,c,Cb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=n(this),f=a.match(G)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=Cb(this),b&&n._data(this,"__className__",b),n.attr(this,"class",b||a===!1?"":n._data(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+Cb(c)+" ").replace(Bb," ").indexOf(b)>-1)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Db=a.location,Eb=n.now(),Fb=/\?/,Gb=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(Gb,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new a.DOMParser,c=d.parseFromString(b,"text/xml")):(c=new a.ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var Hb=/#.*$/,Ib=/([?&])_=[^&]*/,Jb=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Kb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Lb=/^(?:GET|HEAD)$/,Mb=/^\/\//,Nb=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ob={},Pb={},Qb="*/".concat("*"),Rb=Db.href,Sb=Nb.exec(Rb.toLowerCase())||[];function Tb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(G)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Ub(a,b,c,d){var e={},f=a===Pb;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Vb(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Wb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Xb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Rb,type:"GET",isLocal:Kb.test(Sb[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Qb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Vb(Vb(a,n.ajaxSettings),b):Vb(n.ajaxSettings,a)},ajaxPrefilter:Tb(Ob),ajaxTransport:Tb(Pb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var d,e,f,g,h,i,j,k,l=n.ajaxSetup({},c),m=l.context||l,o=l.context&&(m.nodeType||m.jquery)?n(m):n.event,p=n.Deferred(),q=n.Callbacks("once memory"),r=l.statusCode||{},s={},t={},u=0,v="canceled",w={readyState:0,getResponseHeader:function(a){var b;if(2===u){if(!k){k={};while(b=Jb.exec(g))k[b[1].toLowerCase()]=b[2]}b=k[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===u?g:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return u||(a=t[c]=t[c]||a,s[a]=b),this},overrideMimeType:function(a){return u||(l.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>u)for(b in a)r[b]=[r[b],a[b]];else w.always(a[w.status]);return this},abort:function(a){var b=a||v;return j&&j.abort(b),y(0,b),this}};if(p.promise(w).complete=q.add,w.success=w.done,w.error=w.fail,l.url=((b||l.url||Rb)+"").replace(Hb,"").replace(Mb,Sb[1]+"//"),l.type=c.method||c.type||l.method||l.type,l.dataTypes=n.trim(l.dataType||"*").toLowerCase().match(G)||[""],null==l.crossDomain&&(d=Nb.exec(l.url.toLowerCase()),l.crossDomain=!(!d||d[1]===Sb[1]&&d[2]===Sb[2]&&(d[3]||("http:"===d[1]?"80":"443"))===(Sb[3]||("http:"===Sb[1]?"80":"443")))),l.data&&l.processData&&"string"!=typeof l.data&&(l.data=n.param(l.data,l.traditional)),Ub(Ob,l,c,w),2===u)return w;i=n.event&&l.global,i&&0===n.active++&&n.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!Lb.test(l.type),f=l.url,l.hasContent||(l.data&&(f=l.url+=(Fb.test(f)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=Ib.test(f)?f.replace(Ib,"$1_="+Eb++):f+(Fb.test(f)?"&":"?")+"_="+Eb++)),l.ifModified&&(n.lastModified[f]&&w.setRequestHeader("If-Modified-Since",n.lastModified[f]),n.etag[f]&&w.setRequestHeader("If-None-Match",n.etag[f])),(l.data&&l.hasContent&&l.contentType!==!1||c.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+("*"!==l.dataTypes[0]?", "+Qb+"; q=0.01":""):l.accepts["*"]);for(e in l.headers)w.setRequestHeader(e,l.headers[e]);if(l.beforeSend&&(l.beforeSend.call(m,w,l)===!1||2===u))return w.abort();v="abort";for(e in{success:1,error:1,complete:1})w[e](l[e]);if(j=Ub(Pb,l,c,w)){if(w.readyState=1,i&&o.trigger("ajaxSend",[w,l]),2===u)return w;l.async&&l.timeout>0&&(h=a.setTimeout(function(){w.abort("timeout")},l.timeout));try{u=1,j.send(s,y)}catch(x){if(!(2>u))throw x;y(-1,x)}}else y(-1,"No Transport");function y(b,c,d,e){var k,s,t,v,x,y=c;2!==u&&(u=2,h&&a.clearTimeout(h),j=void 0,g=e||"",w.readyState=b>0?4:0,k=b>=200&&300>b||304===b,d&&(v=Wb(l,w,d)),v=Xb(l,v,w,k),k?(l.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(n.lastModified[f]=x),x=w.getResponseHeader("etag"),x&&(n.etag[f]=x)),204===b||"HEAD"===l.type?y="nocontent":304===b?y="notmodified":(y=v.state,s=v.data,t=v.error,k=!t)):(t=y,!b&&y||(y="error",0>b&&(b=0))),w.status=b,w.statusText=(c||y)+"",k?p.resolveWith(m,[s,y,w]):p.rejectWith(m,[w,y,t]),w.statusCode(r),r=void 0,i&&o.trigger(k?"ajaxSuccess":"ajaxError",[w,l,k?s:t]),q.fireWith(m,[w,y]),i&&(o.trigger("ajaxComplete",[w,l]),--n.active||n.event.trigger("ajaxStop")))}return w},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax(n.extend({url:a,type:b,dataType:e,data:c,success:d},n.isPlainObject(a)&&a))}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return n.isFunction(a)?this.each(function(b){n(this).wrapInner(a.call(this,b))}):this.each(function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}});function Yb(a){return a.style&&a.style.display||n.css(a,"display")}function Zb(a){if(!n.contains(a.ownerDocument||d,a))return!0;while(a&&1===a.nodeType){if("none"===Yb(a)||"hidden"===a.type)return!0;a=a.parentNode}return!1}n.expr.filters.hidden=function(a){return l.reliableHiddenOffsets()?a.offsetWidth<=0&&a.offsetHeight<=0&&!a.getClientRects().length:Zb(a)},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var $b=/%20/g,_b=/\[\]$/,ac=/\r?\n/g,bc=/^(?:submit|button|image|reset|file)$/i,cc=/^(?:input|select|textarea|keygen)/i;function dc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||_b.test(a)?d(a,e):dc(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)dc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)dc(c,a[c],b,e);return d.join("&").replace($b,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&cc.test(this.nodeName)&&!bc.test(a)&&(this.checked||!Z.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(ac,"\r\n")}}):{name:b.name,value:c.replace(ac,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return this.isLocal?ic():d.documentMode>8?hc():/^(get|post|head|put|delete|options)$/i.test(this.type)&&hc()||ic()}:hc;var ec=0,fc={},gc=n.ajaxSettings.xhr();a.attachEvent&&a.attachEvent("onunload",function(){for(var a in fc)fc[a](void 0,!0)}),l.cors=!!gc&&"withCredentials"in gc,gc=l.ajax=!!gc,gc&&n.ajaxTransport(function(b){if(!b.crossDomain||l.cors){var c;return{send:function(d,e){var f,g=b.xhr(),h=++ec;if(g.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(f in b.xhrFields)g[f]=b.xhrFields[f];b.mimeType&&g.overrideMimeType&&g.overrideMimeType(b.mimeType),b.crossDomain||d["X-Requested-With"]||(d["X-Requested-With"]="XMLHttpRequest");for(f in d)void 0!==d[f]&&g.setRequestHeader(f,d[f]+"");g.send(b.hasContent&&b.data||null),c=function(a,d){var f,i,j;if(c&&(d||4===g.readyState))if(delete fc[h],c=void 0,g.onreadystatechange=n.noop,d)4!==g.readyState&&g.abort();else{j={},f=g.status,"string"==typeof g.responseText&&(j.text=g.responseText);try{i=g.statusText}catch(k){i=""}f||!b.isLocal||b.crossDomain?1223===f&&(f=204):f=j.text?200:404}j&&e(f,i,j,g.getAllResponseHeaders())},b.async?4===g.readyState?a.setTimeout(c):g.onreadystatechange=fc[h]=c:c()},abort:function(){c&&c(void 0,!0)}}}});function hc(){try{return new a.XMLHttpRequest}catch(b){}}function ic(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=d.head||n("head")[0]||d.documentElement;return{send:function(e,f){b=d.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||f(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var jc=[],kc=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=jc.pop()||n.expando+"_"+Eb++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(kc.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&kc.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(kc,"$1"+e):b.jsonp!==!1&&(b.url+=(Fb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?n(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,jc.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||d;var e=x.exec(a),f=!c&&[];return e?[b.createElement(e[1])]:(e=ja([a],b,f),f&&f.length&&n(f).remove(),n.merge([],e.childNodes))};var lc=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&lc)return lc.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=n.trim(a.slice(h,a.length)),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&n.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};function mc(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,n.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?("undefined"!=typeof e.getBoundingClientRect&&(d=e.getBoundingClientRect()),c=mc(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||Qa})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return Y(this,function(a,d,e){var f=mc(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Ua(l.pixelPosition,function(a,c){return c?(c=Sa(a,b),Oa.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({ padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return Y(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var nc=a.jQuery,oc=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=oc),b&&a.jQuery===n&&(a.jQuery=nc),n},b||(a.jQuery=a.$=n),n}); //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery end jquery //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js //begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js begin bootstrap js /*! * Bootstrap v4.0.0-alpha.5 (https://getbootstrap.com) * Copyright 2011-2016 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors) * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>=4)throw new Error("Bootstrap's JavaScript requires at least jQuery v1.9.1 but less than v4.0.0")}(jQuery),+function(){function a(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function b(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function c(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}var d="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},e=function(){function a(a,b){for(var c=0;c<b.length;c++){var d=b[c];d.enumerable=d.enumerable||!1,d.configurable=!0,"value"in d&&(d.writable=!0),Object.defineProperty(a,d.key,d)}}return function(b,c,d){return c&&a(b.prototype,c),d&&a(b,d),b}}(),f=function(a){function b(a){return{}.toString.call(a).match(/\s([a-zA-Z]+)/)[1].toLowerCase()}function c(a){return(a[0]||a).nodeType}function d(){return{bindType:h.end,delegateType:h.end,handle:function(b){if(a(b.target).is(this))return b.handleObj.handler.apply(this,arguments)}}}function e(){if(window.QUnit)return!1;var a=document.createElement("bootstrap");for(var b in j)if(void 0!==a.style[b])return{end:j[b]};return!1}function f(b){var c=this,d=!1;return a(this).one(k.TRANSITION_END,function(){d=!0}),setTimeout(function(){d||k.triggerTransitionEnd(c)},b),this}function g(){h=e(),a.fn.emulateTransitionEnd=f,k.supportsTransitionEnd()&&(a.event.special[k.TRANSITION_END]=d())}var h=!1,i=1e6,j={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"},k={TRANSITION_END:"bsTransitionEnd",getUID:function(a){do a+=~~(Math.random()*i);while(document.getElementById(a));return a},getSelectorFromElement:function(a){var b=a.getAttribute("data-target");return b||(b=a.getAttribute("href")||"",b=/^#[a-z]/i.test(b)?b:null),b},reflow:function(a){new Function("bs","return bs")(a.offsetHeight)},triggerTransitionEnd:function(b){a(b).trigger(h.end)},supportsTransitionEnd:function(){return Boolean(h)},typeCheckConfig:function(a,d,e){for(var f in e)if(e.hasOwnProperty(f)){var g=e[f],h=d[f],i=void 0;if(i=h&&c(h)?"element":b(h),!new RegExp(g).test(i))throw new Error(a.toUpperCase()+": "+('Option "'+f+'" provided type "'+i+'" ')+('but expected type "'+g+'".'))}}};return g(),k}(jQuery),g=(function(a){var b="alert",d="4.0.0-alpha.5",g="bs.alert",h="."+g,i=".data-api",j=a.fn[b],k=150,l={DISMISS:'[data-dismiss="alert"]'},m={CLOSE:"close"+h,CLOSED:"closed"+h,CLICK_DATA_API:"click"+h+i},n={ALERT:"alert",FADE:"fade",IN:"in"},o=function(){function b(a){c(this,b),this._element=a}return b.prototype.close=function(a){a=a||this._element;var b=this._getRootElement(a),c=this._triggerCloseEvent(b);c.isDefaultPrevented()||this._removeElement(b)},b.prototype.dispose=function(){a.removeData(this._element,g),this._element=null},b.prototype._getRootElement=function(b){var c=f.getSelectorFromElement(b),d=!1;return c&&(d=a(c)[0]),d||(d=a(b).closest("."+n.ALERT)[0]),d},b.prototype._triggerCloseEvent=function(b){var c=a.Event(m.CLOSE);return a(b).trigger(c),c},b.prototype._removeElement=function(b){return a(b).removeClass(n.IN),f.supportsTransitionEnd()&&a(b).hasClass(n.FADE)?void a(b).one(f.TRANSITION_END,a.proxy(this._destroyElement,this,b)).emulateTransitionEnd(k):void this._destroyElement(b)},b.prototype._destroyElement=function(b){a(b).detach().trigger(m.CLOSED).remove()},b._jQueryInterface=function(c){return this.each(function(){var d=a(this),e=d.data(g);e||(e=new b(this),d.data(g,e)),"close"===c&&e[c](this)})},b._handleDismiss=function(a){return function(b){b&&b.preventDefault(),a.close(this)}},e(b,null,[{key:"VERSION",get:function(){return d}}]),b}();return a(document).on(m.CLICK_DATA_API,l.DISMISS,o._handleDismiss(new o)),a.fn[b]=o._jQueryInterface,a.fn[b].Constructor=o,a.fn[b].noConflict=function(){return a.fn[b]=j,o._jQueryInterface},o}(jQuery),function(a){var b="button",d="4.0.0-alpha.5",f="bs.button",g="."+f,h=".data-api",i=a.fn[b],j={ACTIVE:"active",BUTTON:"btn",FOCUS:"focus"},k={DATA_TOGGLE_CARROT:'[data-toggle^="button"]',DATA_TOGGLE:'[data-toggle="buttons"]',INPUT:"input",ACTIVE:".active",BUTTON:".btn"},l={CLICK_DATA_API:"click"+g+h,FOCUS_BLUR_DATA_API:"focus"+g+h+" "+("blur"+g+h)},m=function(){function b(a){c(this,b),this._element=a}return b.prototype.toggle=function(){var b=!0,c=a(this._element).closest(k.DATA_TOGGLE)[0];if(c){var d=a(this._element).find(k.INPUT)[0];if(d){if("radio"===d.type)if(d.checked&&a(this._element).hasClass(j.ACTIVE))b=!1;else{var e=a(c).find(k.ACTIVE)[0];e&&a(e).removeClass(j.ACTIVE)}b&&(d.checked=!a(this._element).hasClass(j.ACTIVE),a(this._element).trigger("change")),d.focus()}}else this._element.setAttribute("aria-pressed",!a(this._element).hasClass(j.ACTIVE));b&&a(this._element).toggleClass(j.ACTIVE)},b.prototype.dispose=function(){a.removeData(this._element,f),this._element=null},b._jQueryInterface=function(c){return this.each(function(){var d=a(this).data(f);d||(d=new b(this),a(this).data(f,d)),"toggle"===c&&d[c]()})},e(b,null,[{key:"VERSION",get:function(){return d}}]),b}();return a(document).on(l.CLICK_DATA_API,k.DATA_TOGGLE_CARROT,function(b){b.preventDefault();var c=b.target;a(c).hasClass(j.BUTTON)||(c=a(c).closest(k.BUTTON)),m._jQueryInterface.call(a(c),"toggle")}).on(l.FOCUS_BLUR_DATA_API,k.DATA_TOGGLE_CARROT,function(b){var c=a(b.target).closest(k.BUTTON)[0];a(c).toggleClass(j.FOCUS,/^focus(in)?$/.test(b.type))}),a.fn[b]=m._jQueryInterface,a.fn[b].Constructor=m,a.fn[b].noConflict=function(){return a.fn[b]=i,m._jQueryInterface},m}(jQuery),function(a){var b="carousel",g="4.0.0-alpha.5",h="bs.carousel",i="."+h,j=".data-api",k=a.fn[b],l=600,m=37,n=39,o={interval:5e3,keyboard:!0,slide:!1,pause:"hover",wrap:!0},p={interval:"(number|boolean)",keyboard:"boolean",slide:"(boolean|string)",pause:"(string|boolean)",wrap:"boolean"},q={NEXT:"next",PREVIOUS:"prev"},r={SLIDE:"slide"+i,SLID:"slid"+i,KEYDOWN:"keydown"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i,LOAD_DATA_API:"load"+i+j,CLICK_DATA_API:"click"+i+j},s={CAROUSEL:"carousel",ACTIVE:"active",SLIDE:"slide",RIGHT:"right",LEFT:"left",ITEM:"carousel-item"},t={ACTIVE:".active",ACTIVE_ITEM:".active.carousel-item",ITEM:".carousel-item",NEXT_PREV:".next, .prev",INDICATORS:".carousel-indicators",DATA_SLIDE:"[data-slide], [data-slide-to]",DATA_RIDE:'[data-ride="carousel"]'},u=function(){function j(b,d){c(this,j),this._items=null,this._interval=null,this._activeElement=null,this._isPaused=!1,this._isSliding=!1,this._config=this._getConfig(d),this._element=a(b)[0],this._indicatorsElement=a(this._element).find(t.INDICATORS)[0],this._addEventListeners()}return j.prototype.next=function(){this._isSliding||this._slide(q.NEXT)},j.prototype.nextWhenVisible=function(){document.hidden||this.next()},j.prototype.prev=function(){this._isSliding||this._slide(q.PREVIOUS)},j.prototype.pause=function(b){b||(this._isPaused=!0),a(this._element).find(t.NEXT_PREV)[0]&&f.supportsTransitionEnd()&&(f.triggerTransitionEnd(this._element),this.cycle(!0)),clearInterval(this._interval),this._interval=null},j.prototype.cycle=function(b){b||(this._isPaused=!1),this._interval&&(clearInterval(this._interval),this._interval=null),this._config.interval&&!this._isPaused&&(this._interval=setInterval(a.proxy(document.visibilityState?this.nextWhenVisible:this.next,this),this._config.interval))},j.prototype.to=function(b){var c=this;this._activeElement=a(this._element).find(t.ACTIVE_ITEM)[0];var d=this._getItemIndex(this._activeElement);if(!(b>this._items.length-1||b<0)){if(this._isSliding)return void a(this._element).one(r.SLID,function(){return c.to(b)});if(d===b)return this.pause(),void this.cycle();var e=b>d?q.NEXT:q.PREVIOUS;this._slide(e,this._items[b])}},j.prototype.dispose=function(){a(this._element).off(i),a.removeData(this._element,h),this._items=null,this._config=null,this._element=null,this._interval=null,this._isPaused=null,this._isSliding=null,this._activeElement=null,this._indicatorsElement=null},j.prototype._getConfig=function(c){return c=a.extend({},o,c),f.typeCheckConfig(b,c,p),c},j.prototype._addEventListeners=function(){this._config.keyboard&&a(this._element).on(r.KEYDOWN,a.proxy(this._keydown,this)),"hover"!==this._config.pause||"ontouchstart"in document.documentElement||a(this._element).on(r.MOUSEENTER,a.proxy(this.pause,this)).on(r.MOUSELEAVE,a.proxy(this.cycle,this))},j.prototype._keydown=function(a){if(a.preventDefault(),!/input|textarea/i.test(a.target.tagName))switch(a.which){case m:this.prev();break;case n:this.next();break;default:return}},j.prototype._getItemIndex=function(b){return this._items=a.makeArray(a(b).parent().find(t.ITEM)),this._items.indexOf(b)},j.prototype._getItemByDirection=function(a,b){var c=a===q.NEXT,d=a===q.PREVIOUS,e=this._getItemIndex(b),f=this._items.length-1,g=d&&0===e||c&&e===f;if(g&&!this._config.wrap)return b;var h=a===q.PREVIOUS?-1:1,i=(e+h)%this._items.length;return i===-1?this._items[this._items.length-1]:this._items[i]},j.prototype._triggerSlideEvent=function(b,c){var d=a.Event(r.SLIDE,{relatedTarget:b,direction:c});return a(this._element).trigger(d),d},j.prototype._setActiveIndicatorElement=function(b){if(this._indicatorsElement){a(this._indicatorsElement).find(t.ACTIVE).removeClass(s.ACTIVE);var c=this._indicatorsElement.children[this._getItemIndex(b)];c&&a(c).addClass(s.ACTIVE)}},j.prototype._slide=function(b,c){var d=this,e=a(this._element).find(t.ACTIVE_ITEM)[0],g=c||e&&this._getItemByDirection(b,e),h=Boolean(this._interval),i=b===q.NEXT?s.LEFT:s.RIGHT;if(g&&a(g).hasClass(s.ACTIVE))return void(this._isSliding=!1);var j=this._triggerSlideEvent(g,i);if(!j.isDefaultPrevented()&&e&&g){this._isSliding=!0,h&&this.pause(),this._setActiveIndicatorElement(g);var k=a.Event(r.SLID,{relatedTarget:g,direction:i});f.supportsTransitionEnd()&&a(this._element).hasClass(s.SLIDE)?(a(g).addClass(b),f.reflow(g),a(e).addClass(i),a(g).addClass(i),a(e).one(f.TRANSITION_END,function(){a(g).removeClass(i).removeClass(b),a(g).addClass(s.ACTIVE),a(e).removeClass(s.ACTIVE).removeClass(b).removeClass(i),d._isSliding=!1,setTimeout(function(){return a(d._element).trigger(k)},0)}).emulateTransitionEnd(l)):(a(e).removeClass(s.ACTIVE),a(g).addClass(s.ACTIVE),this._isSliding=!1,a(this._element).trigger(k)),h&&this.cycle()}},j._jQueryInterface=function(b){return this.each(function(){var c=a(this).data(h),e=a.extend({},o,a(this).data());"object"===("undefined"==typeof b?"undefined":d(b))&&a.extend(e,b);var f="string"==typeof b?b:e.slide;if(c||(c=new j(this,e),a(this).data(h,c)),"number"==typeof b)c.to(b);else if("string"==typeof f){if(void 0===c[f])throw new Error('No method named "'+f+'"');c[f]()}else e.interval&&(c.pause(),c.cycle())})},j._dataApiClickHandler=function(b){var c=f.getSelectorFromElement(this);if(c){var d=a(c)[0];if(d&&a(d).hasClass(s.CAROUSEL)){var e=a.extend({},a(d).data(),a(this).data()),g=this.getAttribute("data-slide-to");g&&(e.interval=!1),j._jQueryInterface.call(a(d),e),g&&a(d).data(h).to(g),b.preventDefault()}}},e(j,null,[{key:"VERSION",get:function(){return g}},{key:"Default",get:function(){return o}}]),j}();return a(document).on(r.CLICK_DATA_API,t.DATA_SLIDE,u._dataApiClickHandler),a(window).on(r.LOAD_DATA_API,function(){a(t.DATA_RIDE).each(function(){var b=a(this);u._jQueryInterface.call(b,b.data())})}),a.fn[b]=u._jQueryInterface,a.fn[b].Constructor=u,a.fn[b].noConflict=function(){return a.fn[b]=k,u._jQueryInterface},u}(jQuery),function(a){var b="collapse",g="4.0.0-alpha.5",h="bs.collapse",i="."+h,j=".data-api",k=a.fn[b],l=600,m={toggle:!0,parent:""},n={toggle:"boolean",parent:"string"},o={SHOW:"show"+i,SHOWN:"shown"+i,HIDE:"hide"+i,HIDDEN:"hidden"+i,CLICK_DATA_API:"click"+i+j},p={IN:"in",COLLAPSE:"collapse",COLLAPSING:"collapsing",COLLAPSED:"collapsed"},q={WIDTH:"width",HEIGHT:"height"},r={ACTIVES:".card > .in, .card > .collapsing",DATA_TOGGLE:'[data-toggle="collapse"]'},s=function(){function i(b,d){c(this,i),this._isTransitioning=!1,this._element=b,this._config=this._getConfig(d),this._triggerArray=a.makeArray(a('[data-toggle="collapse"][href="#'+b.id+'"],'+('[data-toggle="collapse"][data-target="#'+b.id+'"]'))),this._parent=this._config.parent?this._getParent():null,this._config.parent||this._addAriaAndCollapsedClass(this._element,this._triggerArray),this._config.toggle&&this.toggle()}return i.prototype.toggle=function(){a(this._element).hasClass(p.IN)?this.hide():this.show()},i.prototype.show=function(){var b=this;if(!this._isTransitioning&&!a(this._element).hasClass(p.IN)){var c=void 0,d=void 0;if(this._parent&&(c=a.makeArray(a(r.ACTIVES)),c.length||(c=null)),!(c&&(d=a(c).data(h),d&&d._isTransitioning))){var e=a.Event(o.SHOW);if(a(this._element).trigger(e),!e.isDefaultPrevented()){c&&(i._jQueryInterface.call(a(c),"hide"),d||a(c).data(h,null));var g=this._getDimension();a(this._element).removeClass(p.COLLAPSE).addClass(p.COLLAPSING),this._element.style[g]=0,this._element.setAttribute("aria-expanded",!0),this._triggerArray.length&&a(this._triggerArray).removeClass(p.COLLAPSED).attr("aria-expanded",!0),this.setTransitioning(!0);var j=function(){a(b._element).removeClass(p.COLLAPSING).addClass(p.COLLAPSE).addClass(p.IN),b._element.style[g]="",b.setTransitioning(!1),a(b._element).trigger(o.SHOWN)};if(!f.supportsTransitionEnd())return void j();var k=g[0].toUpperCase()+g.slice(1),m="scroll"+k;a(this._element).one(f.TRANSITION_END,j).emulateTransitionEnd(l),this._element.style[g]=this._element[m]+"px"}}}},i.prototype.hide=function(){var b=this;if(!this._isTransitioning&&a(this._element).hasClass(p.IN)){var c=a.Event(o.HIDE);if(a(this._element).trigger(c),!c.isDefaultPrevented()){var d=this._getDimension(),e=d===q.WIDTH?"offsetWidth":"offsetHeight";this._element.style[d]=this._element[e]+"px",f.reflow(this._element),a(this._element).addClass(p.COLLAPSING).removeClass(p.COLLAPSE).removeClass(p.IN),this._element.setAttribute("aria-expanded",!1),this._triggerArray.length&&a(this._triggerArray).addClass(p.COLLAPSED).attr("aria-expanded",!1),this.setTransitioning(!0);var g=function(){b.setTransitioning(!1),a(b._element).removeClass(p.COLLAPSING).addClass(p.COLLAPSE).trigger(o.HIDDEN)};return this._element.style[d]="",f.supportsTransitionEnd()?void a(this._element).one(f.TRANSITION_END,g).emulateTransitionEnd(l):void g()}}},i.prototype.setTransitioning=function(a){this._isTransitioning=a},i.prototype.dispose=function(){a.removeData(this._element,h),this._config=null,this._parent=null,this._element=null,this._triggerArray=null,this._isTransitioning=null},i.prototype._getConfig=function(c){return c=a.extend({},m,c),c.toggle=Boolean(c.toggle),f.typeCheckConfig(b,c,n),c},i.prototype._getDimension=function(){var b=a(this._element).hasClass(q.WIDTH);return b?q.WIDTH:q.HEIGHT},i.prototype._getParent=function(){var b=this,c=a(this._config.parent)[0],d='[data-toggle="collapse"][data-parent="'+this._config.parent+'"]';return a(c).find(d).each(function(a,c){b._addAriaAndCollapsedClass(i._getTargetFromElement(c),[c])}),c},i.prototype._addAriaAndCollapsedClass=function(b,c){if(b){var d=a(b).hasClass(p.IN);b.setAttribute("aria-expanded",d),c.length&&a(c).toggleClass(p.COLLAPSED,!d).attr("aria-expanded",d)}},i._getTargetFromElement=function(b){var c=f.getSelectorFromElement(b);return c?a(c)[0]:null},i._jQueryInterface=function(b){return this.each(function(){var c=a(this),e=c.data(h),f=a.extend({},m,c.data(),"object"===("undefined"==typeof b?"undefined":d(b))&&b);if(!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||(e=new i(this,f),c.data(h,e)),"string"==typeof b){if(void 0===e[b])throw new Error('No method named "'+b+'"');e[b]()}})},e(i,null,[{key:"VERSION",get:function(){return g}},{key:"Default",get:function(){return m}}]),i}();return a(document).on(o.CLICK_DATA_API,r.DATA_TOGGLE,function(b){b.preventDefault();var c=s._getTargetFromElement(this),d=a(c).data(h),e=d?"toggle":a(this).data();s._jQueryInterface.call(a(c),e)}),a.fn[b]=s._jQueryInterface,a.fn[b].Constructor=s,a.fn[b].noConflict=function(){return a.fn[b]=k,s._jQueryInterface},s}(jQuery),function(a){var b="dropdown",d="4.0.0-alpha.5",g="bs.dropdown",h="."+g,i=".data-api",j=a.fn[b],k=27,l=38,m=40,n=3,o={HIDE:"hide"+h,HIDDEN:"hidden"+h,SHOW:"show"+h,SHOWN:"shown"+h,CLICK:"click"+h,CLICK_DATA_API:"click"+h+i,KEYDOWN_DATA_API:"keydown"+h+i},p={BACKDROP:"dropdown-backdrop",DISABLED:"disabled",OPEN:"open"},q={BACKDROP:".dropdown-backdrop",DATA_TOGGLE:'[data-toggle="dropdown"]',FORM_CHILD:".dropdown form",ROLE_MENU:'[role="menu"]',ROLE_LISTBOX:'[role="listbox"]',NAVBAR_NAV:".navbar-nav",VISIBLE_ITEMS:'[role="menu"] li:not(.disabled) a, [role="listbox"] li:not(.disabled) a'},r=function(){function b(a){c(this,b),this._element=a,this._addEventListeners()}return b.prototype.toggle=function(){if(this.disabled||a(this).hasClass(p.DISABLED))return!1;var c=b._getParentFromElement(this),d=a(c).hasClass(p.OPEN);if(b._clearMenus(),d)return!1;if("ontouchstart"in document.documentElement&&!a(c).closest(q.NAVBAR_NAV).length){var e=document.createElement("div");e.className=p.BACKDROP,a(e).insertBefore(this),a(e).on("click",b._clearMenus)}var f={relatedTarget:this},g=a.Event(o.SHOW,f);return a(c).trigger(g),!g.isDefaultPrevented()&&(this.focus(),this.setAttribute("aria-expanded","true"),a(c).toggleClass(p.OPEN),a(c).trigger(a.Event(o.SHOWN,f)),!1)},b.prototype.dispose=function(){a.removeData(this._element,g),a(this._element).off(h),this._element=null},b.prototype._addEventListeners=function(){a(this._element).on(o.CLICK,this.toggle)},b._jQueryInterface=function(c){return this.each(function(){var d=a(this).data(g);if(d||a(this).data(g,d=new b(this)),"string"==typeof c){if(void 0===d[c])throw new Error('No method named "'+c+'"');d[c].call(this)}})},b._clearMenus=function(c){if(!c||c.which!==n){var d=a(q.BACKDROP)[0];d&&d.parentNode.removeChild(d);for(var e=a.makeArray(a(q.DATA_TOGGLE)),f=0;f<e.length;f++){var g=b._getParentFromElement(e[f]),h={relatedTarget:e[f]};if(a(g).hasClass(p.OPEN)&&!(c&&"click"===c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(g,c.target))){var i=a.Event(o.HIDE,h);a(g).trigger(i),i.isDefaultPrevented()||(e[f].setAttribute("aria-expanded","false"),a(g).removeClass(p.OPEN).trigger(a.Event(o.HIDDEN,h)))}}}},b._getParentFromElement=function(b){var c=void 0,d=f.getSelectorFromElement(b);return d&&(c=a(d)[0]),c||b.parentNode},b._dataApiKeydownHandler=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)&&(c.preventDefault(),c.stopPropagation(),!this.disabled&&!a(this).hasClass(p.DISABLED))){var d=b._getParentFromElement(this),e=a(d).hasClass(p.OPEN);if(!e&&c.which!==k||e&&c.which===k){if(c.which===k){var f=a(d).find(q.DATA_TOGGLE)[0];a(f).trigger("focus")}return void a(this).trigger("click")}var g=a.makeArray(a(q.VISIBLE_ITEMS));if(g=g.filter(function(a){return a.offsetWidth||a.offsetHeight}),g.length){var h=g.indexOf(c.target);c.which===l&&h>0&&h--,c.which===m&&h<g.length-1&&h++,h<0&&(h=0),g[h].focus()}}},e(b,null,[{key:"VERSION",get:function(){return d}}]),b}();return a(document).on(o.KEYDOWN_DATA_API,q.DATA_TOGGLE,r._dataApiKeydownHandler).on(o.KEYDOWN_DATA_API,q.ROLE_MENU,r._dataApiKeydownHandler).on(o.KEYDOWN_DATA_API,q.ROLE_LISTBOX,r._dataApiKeydownHandler).on(o.CLICK_DATA_API,r._clearMenus).on(o.CLICK_DATA_API,q.DATA_TOGGLE,r.prototype.toggle).on(o.CLICK_DATA_API,q.FORM_CHILD,function(a){a.stopPropagation()}),a.fn[b]=r._jQueryInterface,a.fn[b].Constructor=r,a.fn[b].noConflict=function(){return a.fn[b]=j,r._jQueryInterface},r}(jQuery),function(a){var b="modal",g="4.0.0-alpha.5",h="bs.modal",i="."+h,j=".data-api",k=a.fn[b],l=300,m=150,n=27,o={backdrop:!0,keyboard:!0,focus:!0,show:!0},p={backdrop:"(boolean|string)",keyboard:"boolean",focus:"boolean",show:"boolean"},q={HIDE:"hide"+i,HIDDEN:"hidden"+i,SHOW:"show"+i,SHOWN:"shown"+i,FOCUSIN:"focusin"+i,RESIZE:"resize"+i,CLICK_DISMISS:"click.dismiss"+i,KEYDOWN_DISMISS:"keydown.dismiss"+i,MOUSEUP_DISMISS:"mouseup.dismiss"+i,MOUSEDOWN_DISMISS:"mousedown.dismiss"+i,CLICK_DATA_API:"click"+i+j},r={SCROLLBAR_MEASURER:"modal-scrollbar-measure",BACKDROP:"modal-backdrop",OPEN:"modal-open",FADE:"fade",IN:"in"},s={DIALOG:".modal-dialog",DATA_TOGGLE:'[data-toggle="modal"]',DATA_DISMISS:'[data-dismiss="modal"]',FIXED_CONTENT:".navbar-fixed-top, .navbar-fixed-bottom, .is-fixed"},t=function(){function j(b,d){c(this,j),this._config=this._getConfig(d),this._element=b,this._dialog=a(b).find(s.DIALOG)[0],this._backdrop=null,this._isShown=!1,this._isBodyOverflowing=!1,this._ignoreBackdropClick=!1,this._originalBodyPadding=0,this._scrollbarWidth=0}return j.prototype.toggle=function(a){return this._isShown?this.hide():this.show(a)},j.prototype.show=function(b){var c=this,d=a.Event(q.SHOW,{relatedTarget:b});a(this._element).trigger(d),this._isShown||d.isDefaultPrevented()||(this._isShown=!0,this._checkScrollbar(),this._setScrollbar(),a(document.body).addClass(r.OPEN),this._setEscapeEvent(),this._setResizeEvent(),a(this._element).on(q.CLICK_DISMISS,s.DATA_DISMISS,a.proxy(this.hide,this)),a(this._dialog).on(q.MOUSEDOWN_DISMISS,function(){a(c._element).one(q.MOUSEUP_DISMISS,function(b){a(b.target).is(c._element)&&(c._ignoreBackdropClick=!0)})}),this._showBackdrop(a.proxy(this._showElement,this,b)))},j.prototype.hide=function(b){b&&b.preventDefault();var c=a.Event(q.HIDE);a(this._element).trigger(c),this._isShown&&!c.isDefaultPrevented()&&(this._isShown=!1,this._setEscapeEvent(),this._setResizeEvent(),a(document).off(q.FOCUSIN),a(this._element).removeClass(r.IN),a(this._element).off(q.CLICK_DISMISS),a(this._dialog).off(q.MOUSEDOWN_DISMISS),f.supportsTransitionEnd()&&a(this._element).hasClass(r.FADE)?a(this._element).one(f.TRANSITION_END,a.proxy(this._hideModal,this)).emulateTransitionEnd(l):this._hideModal())},j.prototype.dispose=function(){a.removeData(this._element,h),a(window).off(i),a(document).off(i),a(this._element).off(i),a(this._backdrop).off(i),this._config=null,this._element=null,this._dialog=null,this._backdrop=null,this._isShown=null,this._isBodyOverflowing=null,this._ignoreBackdropClick=null,this._originalBodyPadding=null,this._scrollbarWidth=null},j.prototype._getConfig=function(c){return c=a.extend({},o,c),f.typeCheckConfig(b,c,p),c},j.prototype._showElement=function(b){var c=this,d=f.supportsTransitionEnd()&&a(this._element).hasClass(r.FADE);this._element.parentNode&&this._element.parentNode.nodeType===Node.ELEMENT_NODE||document.body.appendChild(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.scrollTop=0,d&&f.reflow(this._element),a(this._element).addClass(r.IN),this._config.focus&&this._enforceFocus();var e=a.Event(q.SHOWN,{relatedTarget:b}),g=function(){c._config.focus&&c._element.focus(),a(c._element).trigger(e)};d?a(this._dialog).one(f.TRANSITION_END,g).emulateTransitionEnd(l):g()},j.prototype._enforceFocus=function(){var b=this;a(document).off(q.FOCUSIN).on(q.FOCUSIN,function(c){document===c.target||b._element===c.target||a(b._element).has(c.target).length||b._element.focus()})},j.prototype._setEscapeEvent=function(){var b=this;this._isShown&&this._config.keyboard?a(this._element).on(q.KEYDOWN_DISMISS,function(a){a.which===n&&b.hide()}):this._isShown||a(this._element).off(q.KEYDOWN_DISMISS)},j.prototype._setResizeEvent=function(){this._isShown?a(window).on(q.RESIZE,a.proxy(this._handleUpdate,this)):a(window).off(q.RESIZE)},j.prototype._hideModal=function(){var b=this;this._element.style.display="none",this._element.setAttribute("aria-hidden","true"),this._showBackdrop(function(){a(document.body).removeClass(r.OPEN),b._resetAdjustments(),b._resetScrollbar(),a(b._element).trigger(q.HIDDEN)})},j.prototype._removeBackdrop=function(){this._backdrop&&(a(this._backdrop).remove(),this._backdrop=null)},j.prototype._showBackdrop=function(b){var c=this,d=a(this._element).hasClass(r.FADE)?r.FADE:"";if(this._isShown&&this._config.backdrop){var e=f.supportsTransitionEnd()&&d;if(this._backdrop=document.createElement("div"),this._backdrop.className=r.BACKDROP,d&&a(this._backdrop).addClass(d),a(this._backdrop).appendTo(document.body),a(this._element).on(q.CLICK_DISMISS,function(a){return c._ignoreBackdropClick?void(c._ignoreBackdropClick=!1):void(a.target===a.currentTarget&&("static"===c._config.backdrop?c._element.focus():c.hide()))}),e&&f.reflow(this._backdrop),a(this._backdrop).addClass(r.IN),!b)return;if(!e)return void b();a(this._backdrop).one(f.TRANSITION_END,b).emulateTransitionEnd(m)}else if(!this._isShown&&this._backdrop){a(this._backdrop).removeClass(r.IN);var g=function(){c._removeBackdrop(),b&&b()};f.supportsTransitionEnd()&&a(this._element).hasClass(r.FADE)?a(this._backdrop).one(f.TRANSITION_END,g).emulateTransitionEnd(m):g()}else b&&b()},j.prototype._handleUpdate=function(){this._adjustDialog()},j.prototype._adjustDialog=function(){var a=this._element.scrollHeight>document.documentElement.clientHeight;!this._isBodyOverflowing&&a&&(this._element.style.paddingLeft=this._scrollbarWidth+"px"),this._isBodyOverflowing&&!a&&(this._element.style.paddingRight=this._scrollbarWidth+"px")},j.prototype._resetAdjustments=function(){this._element.style.paddingLeft="",this._element.style.paddingRight=""},j.prototype._checkScrollbar=function(){this._isBodyOverflowing=document.body.clientWidth<window.innerWidth,this._scrollbarWidth=this._getScrollbarWidth()},j.prototype._setScrollbar=function(){var b=parseInt(a(s.FIXED_CONTENT).css("padding-right")||0,10);this._originalBodyPadding=document.body.style.paddingRight||"",this._isBodyOverflowing&&(document.body.style.paddingRight=b+this._scrollbarWidth+"px")},j.prototype._resetScrollbar=function(){document.body.style.paddingRight=this._originalBodyPadding},j.prototype._getScrollbarWidth=function(){var a=document.createElement("div");a.className=r.SCROLLBAR_MEASURER,document.body.appendChild(a);var b=a.offsetWidth-a.clientWidth;return document.body.removeChild(a),b},j._jQueryInterface=function(b,c){return this.each(function(){var e=a(this).data(h),f=a.extend({},j.Default,a(this).data(),"object"===("undefined"==typeof b?"undefined":d(b))&&b);if(e||(e=new j(this,f),a(this).data(h,e)),"string"==typeof b){if(void 0===e[b])throw new Error('No method named "'+b+'"');e[b](c)}else f.show&&e.show(c)})},e(j,null,[{key:"VERSION",get:function(){return g}},{key:"Default",get:function(){return o}}]),j}();return a(document).on(q.CLICK_DATA_API,s.DATA_TOGGLE,function(b){var c=this,d=void 0,e=f.getSelectorFromElement(this);e&&(d=a(e)[0]);var g=a(d).data(h)?"toggle":a.extend({},a(d).data(),a(this).data());"A"===this.tagName&&b.preventDefault();var i=a(d).one(q.SHOW,function(b){b.isDefaultPrevented()||i.one(q.HIDDEN,function(){a(c).is(":visible")&&c.focus()})});t._jQueryInterface.call(a(d),g,this)}),a.fn[b]=t._jQueryInterface,a.fn[b].Constructor=t,a.fn[b].noConflict=function(){return a.fn[b]=k,t._jQueryInterface},t}(jQuery),function(a){var b="scrollspy",g="4.0.0-alpha.5",h="bs.scrollspy",i="."+h,j=".data-api",k=a.fn[b],l={offset:10,method:"auto",target:""},m={offset:"number",method:"string",target:"(string|element)"},n={ACTIVATE:"activate"+i,SCROLL:"scroll"+i,LOAD_DATA_API:"load"+i+j},o={DROPDOWN_ITEM:"dropdown-item",DROPDOWN_MENU:"dropdown-menu",NAV_LINK:"nav-link",NAV:"nav",ACTIVE:"active"},p={DATA_SPY:'[data-spy="scroll"]',ACTIVE:".active",LIST_ITEM:".list-item",LI:"li",LI_DROPDOWN:"li.dropdown",NAV_LINKS:".nav-link",DROPDOWN:".dropdown",DROPDOWN_ITEMS:".dropdown-item",DROPDOWN_TOGGLE:".dropdown-toggle"},q={OFFSET:"offset",POSITION:"position"},r=function(){function j(b,d){c(this,j),this._element=b,this._scrollElement="BODY"===b.tagName?window:b,this._config=this._getConfig(d),this._selector=this._config.target+" "+p.NAV_LINKS+","+(this._config.target+" "+p.DROPDOWN_ITEMS),this._offsets=[],this._targets=[],this._activeTarget=null,this._scrollHeight=0,a(this._scrollElement).on(n.SCROLL,a.proxy(this._process,this)),this.refresh(),this._process()}return j.prototype.refresh=function(){var b=this,c=this._scrollElement!==this._scrollElement.window?q.POSITION:q.OFFSET,d="auto"===this._config.method?c:this._config.method,e=d===q.POSITION?this._getScrollTop():0;this._offsets=[],this._targets=[],this._scrollHeight=this._getScrollHeight();var g=a.makeArray(a(this._selector));g.map(function(b){var c=void 0,g=f.getSelectorFromElement(b);return g&&(c=a(g)[0]),c&&(c.offsetWidth||c.offsetHeight)?[a(c)[d]().top+e,g]:null}).filter(function(a){return a}).sort(function(a,b){return a[0]-b[0]}).forEach(function(a){b._offsets.push(a[0]),b._targets.push(a[1])})},j.prototype.dispose=function(){a.removeData(this._element,h),a(this._scrollElement).off(i),this._element=null,this._scrollElement=null,this._config=null,this._selector=null,this._offsets=null,this._targets=null,this._activeTarget=null,this._scrollHeight=null},j.prototype._getConfig=function(c){if(c=a.extend({},l,c),"string"!=typeof c.target){var d=a(c.target).attr("id");d||(d=f.getUID(b),a(c.target).attr("id",d)),c.target="#"+d}return f.typeCheckConfig(b,c,m),c},j.prototype._getScrollTop=function(){return this._scrollElement===window?this._scrollElement.scrollY:this._scrollElement.scrollTop},j.prototype._getScrollHeight=function(){return this._scrollElement.scrollHeight||Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)},j.prototype._process=function(){var a=this._getScrollTop()+this._config.offset,b=this._getScrollHeight(),c=this._config.offset+b-this._scrollElement.offsetHeight;if(this._scrollHeight!==b&&this.refresh(),a>=c){var d=this._targets[this._targets.length-1];this._activeTarget!==d&&this._activate(d)}if(this._activeTarget&&a<this._offsets[0])return this._activeTarget=null,void this._clear();for(var e=this._offsets.length;e--;){var f=this._activeTarget!==this._targets[e]&&a>=this._offsets[e]&&(void 0===this._offsets[e+1]||a<this._offsets[e+1]);f&&this._activate(this._targets[e])}},j.prototype._activate=function(b){this._activeTarget=b,this._clear();var c=this._selector.split(",");c=c.map(function(a){return a+'[data-target="'+b+'"],'+(a+'[href="'+b+'"]')});var d=a(c.join(","));d.hasClass(o.DROPDOWN_ITEM)?(d.closest(p.DROPDOWN).find(p.DROPDOWN_TOGGLE).addClass(o.ACTIVE),d.addClass(o.ACTIVE)):d.parents(p.LI).find(p.NAV_LINKS).addClass(o.ACTIVE),a(this._scrollElement).trigger(n.ACTIVATE,{relatedTarget:b})},j.prototype._clear=function(){a(this._selector).filter(p.ACTIVE).removeClass(o.ACTIVE)},j._jQueryInterface=function(b){return this.each(function(){var c=a(this).data(h),e="object"===("undefined"==typeof b?"undefined":d(b))&&b||null;if(c||(c=new j(this,e),a(this).data(h,c)),"string"==typeof b){if(void 0===c[b])throw new Error('No method named "'+b+'"');c[b]()}})},e(j,null,[{key:"VERSION",get:function(){return g}},{key:"Default",get:function(){return l}}]),j}();return a(window).on(n.LOAD_DATA_API,function(){for(var b=a.makeArray(a(p.DATA_SPY)),c=b.length;c--;){var d=a(b[c]);r._jQueryInterface.call(d,d.data())}}),a.fn[b]=r._jQueryInterface,a.fn[b].Constructor=r,a.fn[b].noConflict=function(){return a.fn[b]=k,r._jQueryInterface},r}(jQuery),function(a){var b="tab",d="4.0.0-alpha.5",g="bs.tab",h="."+g,i=".data-api",j=a.fn[b],k=150,l={HIDE:"hide"+h,HIDDEN:"hidden"+h,SHOW:"show"+h,SHOWN:"shown"+h,CLICK_DATA_API:"click"+h+i},m={DROPDOWN_MENU:"dropdown-menu",ACTIVE:"active",FADE:"fade",IN:"in"},n={A:"a",LI:"li",DROPDOWN:".dropdown",UL:"ul:not(.dropdown-menu)",FADE_CHILD:"> .nav-item .fade, > .fade",ACTIVE:".active",ACTIVE_CHILD:"> .nav-item > .active, > .active",DATA_TOGGLE:'[data-toggle="tab"], [data-toggle="pill"]', DROPDOWN_TOGGLE:".dropdown-toggle",DROPDOWN_ACTIVE_CHILD:"> .dropdown-menu .active"},o=function(){function b(a){c(this,b),this._element=a}return b.prototype.show=function(){var b=this;if(!this._element.parentNode||this._element.parentNode.nodeType!==Node.ELEMENT_NODE||!a(this._element).hasClass(m.ACTIVE)){var c=void 0,d=void 0,e=a(this._element).closest(n.UL)[0],g=f.getSelectorFromElement(this._element);e&&(d=a.makeArray(a(e).find(n.ACTIVE)),d=d[d.length-1]);var h=a.Event(l.HIDE,{relatedTarget:this._element}),i=a.Event(l.SHOW,{relatedTarget:d});if(d&&a(d).trigger(h),a(this._element).trigger(i),!i.isDefaultPrevented()&&!h.isDefaultPrevented()){g&&(c=a(g)[0]),this._activate(this._element,e);var j=function(){var c=a.Event(l.HIDDEN,{relatedTarget:b._element}),e=a.Event(l.SHOWN,{relatedTarget:d});a(d).trigger(c),a(b._element).trigger(e)};c?this._activate(c,c.parentNode,j):j()}}},b.prototype.dispose=function(){a.removeClass(this._element,g),this._element=null},b.prototype._activate=function(b,c,d){var e=a(c).find(n.ACTIVE_CHILD)[0],g=d&&f.supportsTransitionEnd()&&(e&&a(e).hasClass(m.FADE)||Boolean(a(c).find(n.FADE_CHILD)[0])),h=a.proxy(this._transitionComplete,this,b,e,g,d);e&&g?a(e).one(f.TRANSITION_END,h).emulateTransitionEnd(k):h(),e&&a(e).removeClass(m.IN)},b.prototype._transitionComplete=function(b,c,d,e){if(c){a(c).removeClass(m.ACTIVE);var g=a(c).find(n.DROPDOWN_ACTIVE_CHILD)[0];g&&a(g).removeClass(m.ACTIVE),c.setAttribute("aria-expanded",!1)}if(a(b).addClass(m.ACTIVE),b.setAttribute("aria-expanded",!0),d?(f.reflow(b),a(b).addClass(m.IN)):a(b).removeClass(m.FADE),b.parentNode&&a(b.parentNode).hasClass(m.DROPDOWN_MENU)){var h=a(b).closest(n.DROPDOWN)[0];h&&a(h).find(n.DROPDOWN_TOGGLE).addClass(m.ACTIVE),b.setAttribute("aria-expanded",!0)}e&&e()},b._jQueryInterface=function(c){return this.each(function(){var d=a(this),e=d.data(g);if(e||(e=e=new b(this),d.data(g,e)),"string"==typeof c){if(void 0===e[c])throw new Error('No method named "'+c+'"');e[c]()}})},e(b,null,[{key:"VERSION",get:function(){return d}}]),b}();return a(document).on(l.CLICK_DATA_API,n.DATA_TOGGLE,function(b){b.preventDefault(),o._jQueryInterface.call(a(this),"show")}),a.fn[b]=o._jQueryInterface,a.fn[b].Constructor=o,a.fn[b].noConflict=function(){return a.fn[b]=j,o._jQueryInterface},o}(jQuery),function(a){if(void 0===window.Tether)throw new Error("Bootstrap tooltips require Tether (http://tether.io/)");var b="tooltip",g="4.0.0-alpha.5",h="bs.tooltip",i="."+h,j=a.fn[b],k=150,l="bs-tether",m={animation:!0,template:'<div class="tooltip" role="tooltip"><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,selector:!1,placement:"top",offset:"0 0",constraints:[]},n={animation:"boolean",template:"string",title:"(string|element|function)",trigger:"string",delay:"(number|object)",html:"boolean",selector:"(string|boolean)",placement:"(string|function)",offset:"string",constraints:"array"},o={TOP:"bottom center",RIGHT:"middle left",BOTTOM:"top center",LEFT:"middle right"},p={IN:"in",OUT:"out"},q={HIDE:"hide"+i,HIDDEN:"hidden"+i,SHOW:"show"+i,SHOWN:"shown"+i,INSERTED:"inserted"+i,CLICK:"click"+i,FOCUSIN:"focusin"+i,FOCUSOUT:"focusout"+i,MOUSEENTER:"mouseenter"+i,MOUSELEAVE:"mouseleave"+i},r={FADE:"fade",IN:"in"},s={TOOLTIP:".tooltip",TOOLTIP_INNER:".tooltip-inner"},t={element:!1,enabled:!1},u={HOVER:"hover",FOCUS:"focus",CLICK:"click",MANUAL:"manual"},v=function(){function j(a,b){c(this,j),this._isEnabled=!0,this._timeout=0,this._hoverState="",this._activeTrigger={},this._tether=null,this.element=a,this.config=this._getConfig(b),this.tip=null,this._setListeners()}return j.prototype.enable=function(){this._isEnabled=!0},j.prototype.disable=function(){this._isEnabled=!1},j.prototype.toggleEnabled=function(){this._isEnabled=!this._isEnabled},j.prototype.toggle=function(b){if(b){var c=this.constructor.DATA_KEY,d=a(b.currentTarget).data(c);d||(d=new this.constructor(b.currentTarget,this._getDelegateConfig()),a(b.currentTarget).data(c,d)),d._activeTrigger.click=!d._activeTrigger.click,d._isWithActiveTrigger()?d._enter(null,d):d._leave(null,d)}else{if(a(this.getTipElement()).hasClass(r.IN))return void this._leave(null,this);this._enter(null,this)}},j.prototype.dispose=function(){clearTimeout(this._timeout),this.cleanupTether(),a.removeData(this.element,this.constructor.DATA_KEY),a(this.element).off(this.constructor.EVENT_KEY),this.tip&&a(this.tip).remove(),this._isEnabled=null,this._timeout=null,this._hoverState=null,this._activeTrigger=null,this._tether=null,this.element=null,this.config=null,this.tip=null},j.prototype.show=function(){var b=this,c=a.Event(this.constructor.Event.SHOW);if(this.isWithContent()&&this._isEnabled){a(this.element).trigger(c);var d=a.contains(this.element.ownerDocument.documentElement,this.element);if(c.isDefaultPrevented()||!d)return;var e=this.getTipElement(),g=f.getUID(this.constructor.NAME);e.setAttribute("id",g),this.element.setAttribute("aria-describedby",g),this.setContent(),this.config.animation&&a(e).addClass(r.FADE);var h="function"==typeof this.config.placement?this.config.placement.call(this,e,this.element):this.config.placement,i=this._getAttachment(h);a(e).data(this.constructor.DATA_KEY,this).appendTo(document.body),a(this.element).trigger(this.constructor.Event.INSERTED),this._tether=new Tether({attachment:i,element:e,target:this.element,classes:t,classPrefix:l,offset:this.config.offset,constraints:this.config.constraints,addTargetClasses:!1}),f.reflow(e),this._tether.position(),a(e).addClass(r.IN);var k=function(){var c=b._hoverState;b._hoverState=null,a(b.element).trigger(b.constructor.Event.SHOWN),c===p.OUT&&b._leave(null,b)};if(f.supportsTransitionEnd()&&a(this.tip).hasClass(r.FADE))return void a(this.tip).one(f.TRANSITION_END,k).emulateTransitionEnd(j._TRANSITION_DURATION);k()}},j.prototype.hide=function(b){var c=this,d=this.getTipElement(),e=a.Event(this.constructor.Event.HIDE),g=function(){c._hoverState!==p.IN&&d.parentNode&&d.parentNode.removeChild(d),c.element.removeAttribute("aria-describedby"),a(c.element).trigger(c.constructor.Event.HIDDEN),c.cleanupTether(),b&&b()};a(this.element).trigger(e),e.isDefaultPrevented()||(a(d).removeClass(r.IN),f.supportsTransitionEnd()&&a(this.tip).hasClass(r.FADE)?a(d).one(f.TRANSITION_END,g).emulateTransitionEnd(k):g(),this._hoverState="")},j.prototype.isWithContent=function(){return Boolean(this.getTitle())},j.prototype.getTipElement=function(){return this.tip=this.tip||a(this.config.template)[0]},j.prototype.setContent=function(){var b=a(this.getTipElement());this.setElementContent(b.find(s.TOOLTIP_INNER),this.getTitle()),b.removeClass(r.FADE).removeClass(r.IN),this.cleanupTether()},j.prototype.setElementContent=function(b,c){var e=this.config.html;"object"===("undefined"==typeof c?"undefined":d(c))&&(c.nodeType||c.jquery)?e?a(c).parent().is(b)||b.empty().append(c):b.text(a(c).text()):b[e?"html":"text"](c)},j.prototype.getTitle=function(){var a=this.element.getAttribute("data-original-title");return a||(a="function"==typeof this.config.title?this.config.title.call(this.element):this.config.title),a},j.prototype.cleanupTether=function(){this._tether&&this._tether.destroy()},j.prototype._getAttachment=function(a){return o[a.toUpperCase()]},j.prototype._setListeners=function(){var b=this,c=this.config.trigger.split(" ");c.forEach(function(c){if("click"===c)a(b.element).on(b.constructor.Event.CLICK,b.config.selector,a.proxy(b.toggle,b));else if(c!==u.MANUAL){var d=c===u.HOVER?b.constructor.Event.MOUSEENTER:b.constructor.Event.FOCUSIN,e=c===u.HOVER?b.constructor.Event.MOUSELEAVE:b.constructor.Event.FOCUSOUT;a(b.element).on(d,b.config.selector,a.proxy(b._enter,b)).on(e,b.config.selector,a.proxy(b._leave,b))}}),this.config.selector?this.config=a.extend({},this.config,{trigger:"manual",selector:""}):this._fixTitle()},j.prototype._fixTitle=function(){var a=d(this.element.getAttribute("data-original-title"));(this.element.getAttribute("title")||"string"!==a)&&(this.element.setAttribute("data-original-title",this.element.getAttribute("title")||""),this.element.setAttribute("title",""))},j.prototype._enter=function(b,c){var d=this.constructor.DATA_KEY;return c=c||a(b.currentTarget).data(d),c||(c=new this.constructor(b.currentTarget,this._getDelegateConfig()),a(b.currentTarget).data(d,c)),b&&(c._activeTrigger["focusin"===b.type?u.FOCUS:u.HOVER]=!0),a(c.getTipElement()).hasClass(r.IN)||c._hoverState===p.IN?void(c._hoverState=p.IN):(clearTimeout(c._timeout),c._hoverState=p.IN,c.config.delay&&c.config.delay.show?void(c._timeout=setTimeout(function(){c._hoverState===p.IN&&c.show()},c.config.delay.show)):void c.show())},j.prototype._leave=function(b,c){var d=this.constructor.DATA_KEY;if(c=c||a(b.currentTarget).data(d),c||(c=new this.constructor(b.currentTarget,this._getDelegateConfig()),a(b.currentTarget).data(d,c)),b&&(c._activeTrigger["focusout"===b.type?u.FOCUS:u.HOVER]=!1),!c._isWithActiveTrigger())return clearTimeout(c._timeout),c._hoverState=p.OUT,c.config.delay&&c.config.delay.hide?void(c._timeout=setTimeout(function(){c._hoverState===p.OUT&&c.hide()},c.config.delay.hide)):void c.hide()},j.prototype._isWithActiveTrigger=function(){for(var a in this._activeTrigger)if(this._activeTrigger[a])return!0;return!1},j.prototype._getConfig=function(c){return c=a.extend({},this.constructor.Default,a(this.element).data(),c),c.delay&&"number"==typeof c.delay&&(c.delay={show:c.delay,hide:c.delay}),f.typeCheckConfig(b,c,this.constructor.DefaultType),c},j.prototype._getDelegateConfig=function(){var a={};if(this.config)for(var b in this.config)this.constructor.Default[b]!==this.config[b]&&(a[b]=this.config[b]);return a},j._jQueryInterface=function(b){return this.each(function(){var c=a(this).data(h),e="object"===("undefined"==typeof b?"undefined":d(b))?b:null;if((c||!/dispose|hide/.test(b))&&(c||(c=new j(this,e),a(this).data(h,c)),"string"==typeof b)){if(void 0===c[b])throw new Error('No method named "'+b+'"');c[b]()}})},e(j,null,[{key:"VERSION",get:function(){return g}},{key:"Default",get:function(){return m}},{key:"NAME",get:function(){return b}},{key:"DATA_KEY",get:function(){return h}},{key:"Event",get:function(){return q}},{key:"EVENT_KEY",get:function(){return i}},{key:"DefaultType",get:function(){return n}}]),j}();return a.fn[b]=v._jQueryInterface,a.fn[b].Constructor=v,a.fn[b].noConflict=function(){return a.fn[b]=j,v._jQueryInterface},v}(jQuery));(function(f){var h="popover",i="4.0.0-alpha.5",j="bs.popover",k="."+j,l=f.fn[h],m=f.extend({},g.Default,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),n=f.extend({},g.DefaultType,{content:"(string|element|function)"}),o={FADE:"fade",IN:"in"},p={TITLE:".popover-title",CONTENT:".popover-content"},q={HIDE:"hide"+k,HIDDEN:"hidden"+k,SHOW:"show"+k,SHOWN:"shown"+k,INSERTED:"inserted"+k,CLICK:"click"+k,FOCUSIN:"focusin"+k,FOCUSOUT:"focusout"+k,MOUSEENTER:"mouseenter"+k,MOUSELEAVE:"mouseleave"+k},r=function(g){function l(){return c(this,l),a(this,g.apply(this,arguments))}return b(l,g),l.prototype.isWithContent=function(){return this.getTitle()||this._getContent()},l.prototype.getTipElement=function(){return this.tip=this.tip||f(this.config.template)[0]},l.prototype.setContent=function(){var a=f(this.getTipElement());this.setElementContent(a.find(p.TITLE),this.getTitle()),this.setElementContent(a.find(p.CONTENT),this._getContent()),a.removeClass(o.FADE).removeClass(o.IN),this.cleanupTether()},l.prototype._getContent=function(){return this.element.getAttribute("data-content")||("function"==typeof this.config.content?this.config.content.call(this.element):this.config.content)},l._jQueryInterface=function(a){return this.each(function(){var b=f(this).data(j),c="object"===("undefined"==typeof a?"undefined":d(a))?a:null;if((b||!/destroy|hide/.test(a))&&(b||(b=new l(this,c),f(this).data(j,b)),"string"==typeof a)){if(void 0===b[a])throw new Error('No method named "'+a+'"');b[a]()}})},e(l,null,[{key:"VERSION",get:function(){return i}},{key:"Default",get:function(){return m}},{key:"NAME",get:function(){return h}},{key:"DATA_KEY",get:function(){return j}},{key:"Event",get:function(){return q}},{key:"EVENT_KEY",get:function(){return k}},{key:"DefaultType",get:function(){return n}}]),l}(g);return f.fn[h]=r._jQueryInterface,f.fn[h].Constructor=r,f.fn[h].noConflict=function(){return f.fn[h]=l,r._jQueryInterface},r})(jQuery)}(); // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js end bootstrap js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js // begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js begin wow js /*! WOW - v1.1.2 - 2015-04-07 * Copyright (c) 2015 Matthieu Aussaguel; Licensed MIT */ (function(){var a,b,c,d,e,f=function(a,b){return function(){return a.apply(b,arguments)}},g=[].indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(b in this&&this[b]===a)return b;return-1};b=function(){function a(){}return a.prototype.extend=function(a,b){var c,d;for(c in b)d=b[c],null==a[c]&&(a[c]=d);return a},a.prototype.isMobile=function(a){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(a)},a.prototype.createEvent=function(a,b,c,d){var e;return null==b&&(b=!1),null==c&&(c=!1),null==d&&(d=null),null!=document.createEvent?(e=document.createEvent("CustomEvent"),e.initCustomEvent(a,b,c,d)):null!=document.createEventObject?(e=document.createEventObject(),e.eventType=a):e.eventName=a,e},a.prototype.emitEvent=function(a,b){return null!=a.dispatchEvent?a.dispatchEvent(b):b in(null!=a)?a[b]():"on"+b in(null!=a)?a["on"+b]():void 0},a.prototype.addEvent=function(a,b,c){return null!=a.addEventListener?a.addEventListener(b,c,!1):null!=a.attachEvent?a.attachEvent("on"+b,c):a[b]=c},a.prototype.removeEvent=function(a,b,c){return null!=a.removeEventListener?a.removeEventListener(b,c,!1):null!=a.detachEvent?a.detachEvent("on"+b,c):delete a[b]},a.prototype.innerHeight=function(){return"innerHeight"in window?window.innerHeight:document.documentElement.clientHeight},a}(),c=this.WeakMap||this.MozWeakMap||(c=function(){function a(){this.keys=[],this.values=[]}return a.prototype.get=function(a){var b,c,d,e,f;for(f=this.keys,b=d=0,e=f.length;e>d;b=++d)if(c=f[b],c===a)return this.values[b]},a.prototype.set=function(a,b){var c,d,e,f,g;for(g=this.keys,c=e=0,f=g.length;f>e;c=++e)if(d=g[c],d===a)return void(this.values[c]=b);return this.keys.push(a),this.values.push(b)},a}()),a=this.MutationObserver||this.WebkitMutationObserver||this.MozMutationObserver||(a=function(){function a(){"undefined"!=typeof console&&null!==console&&console.warn("MutationObserver is not supported by your browser."),"undefined"!=typeof console&&null!==console&&console.warn("WOW.js cannot detect dom mutations, please call .sync() after loading new content.")}return a.notSupported=!0,a.prototype.observe=function(){},a}()),d=this.getComputedStyle||function(a){return this.getPropertyValue=function(b){var c;return"float"===b&&(b="styleFloat"),e.test(b)&&b.replace(e,function(a,b){return b.toUpperCase()}),(null!=(c=a.currentStyle)?c[b]:void 0)||null},this},e=/(\-([a-z]){1})/g,this.WOW=function(){function e(a){null==a&&(a={}),this.scrollCallback=f(this.scrollCallback,this),this.scrollHandler=f(this.scrollHandler,this),this.resetAnimation=f(this.resetAnimation,this),this.start=f(this.start,this),this.scrolled=!0,this.config=this.util().extend(a,this.defaults),this.animationNameCache=new c,this.wowEvent=this.util().createEvent(this.config.boxClass)}return e.prototype.defaults={boxClass:"wow",animateClass:"animated",offset:0,mobile:!0,live:!0,callback:null},e.prototype.init=function(){var a;return this.element=window.document.documentElement,"interactive"===(a=document.readyState)||"complete"===a?this.start():this.util().addEvent(document,"DOMContentLoaded",this.start),this.finished=[]},e.prototype.start=function(){var b,c,d,e;if(this.stopped=!1,this.boxes=function(){var a,c,d,e;for(d=this.element.querySelectorAll("."+this.config.boxClass),e=[],a=0,c=d.length;c>a;a++)b=d[a],e.push(b);return e}.call(this),this.all=function(){var a,c,d,e;for(d=this.boxes,e=[],a=0,c=d.length;c>a;a++)b=d[a],e.push(b);return e}.call(this),this.boxes.length)if(this.disabled())this.resetStyle();else for(e=this.boxes,c=0,d=e.length;d>c;c++)b=e[c],this.applyStyle(b,!0);return this.disabled()||(this.util().addEvent(window,"scroll",this.scrollHandler),this.util().addEvent(window,"resize",this.scrollHandler),this.interval=setInterval(this.scrollCallback,50)),this.config.live?new a(function(a){return function(b){var c,d,e,f,g;for(g=[],c=0,d=b.length;d>c;c++)f=b[c],g.push(function(){var a,b,c,d;for(c=f.addedNodes||[],d=[],a=0,b=c.length;b>a;a++)e=c[a],d.push(this.doSync(e));return d}.call(a));return g}}(this)).observe(document.body,{childList:!0,subtree:!0}):void 0},e.prototype.stop=function(){return this.stopped=!0,this.util().removeEvent(window,"scroll",this.scrollHandler),this.util().removeEvent(window,"resize",this.scrollHandler),null!=this.interval?clearInterval(this.interval):void 0},e.prototype.sync=function(){return a.notSupported?this.doSync(this.element):void 0},e.prototype.doSync=function(a){var b,c,d,e,f;if(null==a&&(a=this.element),1===a.nodeType){for(a=a.parentNode||a,e=a.querySelectorAll("."+this.config.boxClass),f=[],c=0,d=e.length;d>c;c++)b=e[c],g.call(this.all,b)<0?(this.boxes.push(b),this.all.push(b),this.stopped||this.disabled()?this.resetStyle():this.applyStyle(b,!0),f.push(this.scrolled=!0)):f.push(void 0);return f}},e.prototype.show=function(a){return this.applyStyle(a),a.className=a.className+" "+this.config.animateClass,null!=this.config.callback&&this.config.callback(a),this.util().emitEvent(a,this.wowEvent),this.util().addEvent(a,"animationend",this.resetAnimation),this.util().addEvent(a,"oanimationend",this.resetAnimation),this.util().addEvent(a,"webkitAnimationEnd",this.resetAnimation),this.util().addEvent(a,"MSAnimationEnd",this.resetAnimation),a},e.prototype.applyStyle=function(a,b){var c,d,e;return d=a.getAttribute("data-wow-duration"),c=a.getAttribute("data-wow-delay"),e=a.getAttribute("data-wow-iteration"),this.animate(function(f){return function(){return f.customStyle(a,b,d,c,e)}}(this))},e.prototype.animate=function(){return"requestAnimationFrame"in window?function(a){return window.requestAnimationFrame(a)}:function(a){return a()}}(),e.prototype.resetStyle=function(){var a,b,c,d,e;for(d=this.boxes,e=[],b=0,c=d.length;c>b;b++)a=d[b],e.push(a.style.visibility="visible");return e},e.prototype.resetAnimation=function(a){var b;return a.type.toLowerCase().indexOf("animationend")>=0?(b=a.target||a.srcElement,b.className=b.className.replace(this.config.animateClass,"").trim()):void 0},e.prototype.customStyle=function(a,b,c,d,e){return b&&this.cacheAnimationName(a),a.style.visibility=b?"hidden":"visible",c&&this.vendorSet(a.style,{animationDuration:c}),d&&this.vendorSet(a.style,{animationDelay:d}),e&&this.vendorSet(a.style,{animationIterationCount:e}),this.vendorSet(a.style,{animationName:b?"none":this.cachedAnimationName(a)}),a},e.prototype.vendors=["moz","webkit"],e.prototype.vendorSet=function(a,b){var c,d,e,f;d=[];for(c in b)e=b[c],a[""+c]=e,d.push(function(){var b,d,g,h;for(g=this.vendors,h=[],b=0,d=g.length;d>b;b++)f=g[b],h.push(a[""+f+c.charAt(0).toUpperCase()+c.substr(1)]=e);return h}.call(this));return d},e.prototype.vendorCSS=function(a,b){var c,e,f,g,h,i;for(h=d(a),g=h.getPropertyCSSValue(b),f=this.vendors,c=0,e=f.length;e>c;c++)i=f[c],g=g||h.getPropertyCSSValue("-"+i+"-"+b);return g},e.prototype.animationName=function(a){var b;try{b=this.vendorCSS(a,"animation-name").cssText}catch(c){b=d(a).getPropertyValue("animation-name")}return"none"===b?"":b},e.prototype.cacheAnimationName=function(a){return this.animationNameCache.set(a,this.animationName(a))},e.prototype.cachedAnimationName=function(a){return this.animationNameCache.get(a)},e.prototype.scrollHandler=function(){return this.scrolled=!0},e.prototype.scrollCallback=function(){var a;return!this.scrolled||(this.scrolled=!1,this.boxes=function(){var b,c,d,e;for(d=this.boxes,e=[],b=0,c=d.length;c>b;b++)a=d[b],a&&(this.isVisible(a)?this.show(a):e.push(a));return e}.call(this),this.boxes.length||this.config.live)?void 0:this.stop()},e.prototype.offsetTop=function(a){for(var b;void 0===a.offsetTop;)a=a.parentNode;for(b=a.offsetTop;a=a.offsetParent;)b+=a.offsetTop;return b},e.prototype.isVisible=function(a){var b,c,d,e,f;return c=a.getAttribute("data-wow-offset")||this.config.offset,f=window.pageYOffset,e=f+Math.min(this.element.clientHeight,this.util().innerHeight())-c,d=this.offsetTop(a),b=d+a.clientHeight,e>=d&&b>=f},e.prototype.util=function(){return null!=this._util?this._util:this._util=new b},e.prototype.disabled=function(){return!this.config.mobile&&this.util().isMobile(navigator.userAgent)},e}()}).call(this); /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ /* end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow end wow */ // end jquery // begin tweenmax // begin tweenmax // begin tweenmax // begin tweenmax // begin tweenmax // begin tweenmax /*! * VERSION: 1.18.5 * DATE: 2016-05-24 * UPDATES AND DOCS AT: http://greensock.com * * Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin * * @license Copyright (c) 2008-2016, GreenSock. All rights reserved. * This work is subject to the terms at http://greensock.com/standard-license or for * Club GreenSock members, the software agreement that was issued with your membership. * * @author: Jack Doyle, [email protected] **/ var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";_gsScope._gsDefine("TweenMax",["core.Animation","core.SimpleTimeline","TweenLite"],function(a,b,c){var d=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},e=function(a,b,c){var d,e,f=a.cycle;for(d in f)e=f[d],a[d]="function"==typeof e?e.call(b[c],c):e[c%e.length];delete a.cycle},f=function(a,b,d){c.call(this,a,b,d),this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._dirty=!0,this.render=f.prototype.render},g=1e-10,h=c._internals,i=h.isSelector,j=h.isArray,k=f.prototype=c.to({},.1,{}),l=[];f.version="1.18.5",k.constructor=f,k.kill()._gc=!1,f.killTweensOf=f.killDelayedCallsTo=c.killTweensOf,f.getTweensOf=c.getTweensOf,f.lagSmoothing=c.lagSmoothing,f.ticker=c.ticker,f.render=c.render,k.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),c.prototype.invalidate.call(this)},k.updateTo=function(a,b){var d,e=this.ratio,f=this.vars.immediateRender||a.immediateRender;b&&this._startTime<this._timeline._time&&(this._startTime=this._timeline._time,this._uncache(!1),this._gc?this._enabled(!0,!1):this._timeline.insert(this,this._startTime-this._delay));for(d in a)this.vars[d]=a[d];if(this._initted||f)if(b)this._initted=!1,f&&this.render(0,!0,!0);else if(this._gc&&this._enabled(!0,!1),this._notifyPluginsOfEnabled&&this._firstPT&&c._onPluginEvent("_onDisable",this),this._time/this._duration>.998){var g=this._totalTime;this.render(0,!0,!1),this._initted=!1,this.render(g,!0,!1)}else if(this._initted=!1,this._init(),this._time>0||f)for(var h,i=1/(1-e),j=this._firstPT;j;)h=j.s+j.c,j.c*=i,j.s=h-j.c,j=j._next;return this},k.render=function(a,b,c){this._initted||0===this._duration&&this.vars.repeat&&this.invalidate();var d,e,f,i,j,k,l,m,n=this._dirty?this.totalDuration():this._totalDuration,o=this._time,p=this._totalTime,q=this._cycle,r=this._duration,s=this._rawPrevTime;if(a>=n-1e-7?(this._totalTime=n,this._cycle=this._repeat,this._yoyo&&0!==(1&this._cycle)?(this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0):(this._time=r,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1),this._reversed||(d=!0,e="onComplete",c=c||this._timeline.autoRemoveChildren),0===r&&(this._initted||!this.vars.lazy||c)&&(this._startTime===this._timeline._duration&&(a=0),(0>s||0>=a&&a>=-1e-7||s===g&&"isPause"!==this.data)&&s!==a&&(c=!0,s>g&&(e="onReverseComplete")),this._rawPrevTime=m=!b||a||s===a?a:g)):1e-7>a?(this._totalTime=this._time=this._cycle=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==p||0===r&&s>0)&&(e="onReverseComplete",d=this._reversed),0>a&&(this._active=!1,0===r&&(this._initted||!this.vars.lazy||c)&&(s>=0&&(c=!0),this._rawPrevTime=m=!b||a||s===a?a:g)),this._initted||(c=!0)):(this._totalTime=this._time=a,0!==this._repeat&&(i=r+this._repeatDelay,this._cycle=this._totalTime/i>>0,0!==this._cycle&&this._cycle===this._totalTime/i&&a>=p&&this._cycle--,this._time=this._totalTime-this._cycle*i,this._yoyo&&0!==(1&this._cycle)&&(this._time=r-this._time),this._time>r?this._time=r:this._time<0&&(this._time=0)),this._easeType?(j=this._time/r,k=this._easeType,l=this._easePower,(1===k||3===k&&j>=.5)&&(j=1-j),3===k&&(j*=2),1===l?j*=j:2===l?j*=j*j:3===l?j*=j*j*j:4===l&&(j*=j*j*j*j),1===k?this.ratio=1-j:2===k?this.ratio=j:this._time/r<.5?this.ratio=j/2:this.ratio=1-j/2):this.ratio=this._ease.getRatio(this._time/r)),o===this._time&&!c&&q===this._cycle)return void(p!==this._totalTime&&this._onUpdate&&(b||this._callback("onUpdate")));if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!c&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=o,this._totalTime=p,this._rawPrevTime=s,this._cycle=q,h.lazyTweens.push(this),void(this._lazy=[a,b]);this._time&&!d?this.ratio=this._ease.getRatio(this._time/r):d&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==o&&a>=0&&(this._active=!0),0===p&&(2===this._initted&&a>0&&this._init(),this._startAt&&(a>=0?this._startAt.render(a,b,c):e||(e="_dummyGS")),this.vars.onStart&&(0!==this._totalTime||0===r)&&(b||this._callback("onStart"))),f=this._firstPT;f;)f.f?f.t[f.p](f.c*this.ratio+f.s):f.t[f.p]=f.c*this.ratio+f.s,f=f._next;this._onUpdate&&(0>a&&this._startAt&&this._startTime&&this._startAt.render(a,b,c),b||(this._totalTime!==p||e)&&this._callback("onUpdate")),this._cycle!==q&&(b||this._gc||this.vars.onRepeat&&this._callback("onRepeat")),e&&(!this._gc||c)&&(0>a&&this._startAt&&!this._onUpdate&&this._startTime&&this._startAt.render(a,b,c),d&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[e]&&this._callback(e),0===r&&this._rawPrevTime===g&&m!==g&&(this._rawPrevTime=0))},f.to=function(a,b,c){return new f(a,b,c)},f.from=function(a,b,c){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,new f(a,b,c)},f.fromTo=function(a,b,c,d){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,new f(a,b,d)},f.staggerTo=f.allTo=function(a,b,g,h,k,m,n){h=h||0;var o,p,q,r,s=0,t=[],u=function(){g.onComplete&&g.onComplete.apply(g.onCompleteScope||this,arguments),k.apply(n||g.callbackScope||this,m||l)},v=g.cycle,w=g.startAt&&g.startAt.cycle;for(j(a)||("string"==typeof a&&(a=c.selector(a)||a),i(a)&&(a=d(a))),a=a||[],0>h&&(a=d(a),a.reverse(),h*=-1),o=a.length-1,q=0;o>=q;q++){p={};for(r in g)p[r]=g[r];if(v&&(e(p,a,q),null!=p.duration&&(b=p.duration,delete p.duration)),w){w=p.startAt={};for(r in g.startAt)w[r]=g.startAt[r];e(p.startAt,a,q)}p.delay=s+(p.delay||0),q===o&&k&&(p.onComplete=u),t[q]=new f(a[q],b,p),s+=h}return t},f.staggerFrom=f.allFrom=function(a,b,c,d,e,g,h){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,f.staggerTo(a,b,c,d,e,g,h)},f.staggerFromTo=f.allFromTo=function(a,b,c,d,e,g,h,i){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,f.staggerTo(a,b,d,e,g,h,i)},f.delayedCall=function(a,b,c,d,e){return new f(b,0,{delay:a,onComplete:b,onCompleteParams:c,callbackScope:d,onReverseComplete:b,onReverseCompleteParams:c,immediateRender:!1,useFrames:e,overwrite:0})},f.set=function(a,b){return new f(a,0,b)},f.isTweening=function(a){return c.getTweensOf(a,!0).length>0};var m=function(a,b){for(var d=[],e=0,f=a._first;f;)f instanceof c?d[e++]=f:(b&&(d[e++]=f),d=d.concat(m(f,b)),e=d.length),f=f._next;return d},n=f.getAllTweens=function(b){return m(a._rootTimeline,b).concat(m(a._rootFramesTimeline,b))};f.killAll=function(a,c,d,e){null==c&&(c=!0),null==d&&(d=!0);var f,g,h,i=n(0!=e),j=i.length,k=c&&d&&e;for(h=0;j>h;h++)g=i[h],(k||g instanceof b||(f=g.target===g.vars.onComplete)&&d||c&&!f)&&(a?g.totalTime(g._reversed?0:g.totalDuration()):g._enabled(!1,!1))},f.killChildTweensOf=function(a,b){if(null!=a){var e,g,k,l,m,n=h.tweenLookup;if("string"==typeof a&&(a=c.selector(a)||a),i(a)&&(a=d(a)),j(a))for(l=a.length;--l>-1;)f.killChildTweensOf(a[l],b);else{e=[];for(k in n)for(g=n[k].target.parentNode;g;)g===a&&(e=e.concat(n[k].tweens)),g=g.parentNode;for(m=e.length,l=0;m>l;l++)b&&e[l].totalTime(e[l].totalDuration()),e[l]._enabled(!1,!1)}}};var o=function(a,c,d,e){c=c!==!1,d=d!==!1,e=e!==!1;for(var f,g,h=n(e),i=c&&d&&e,j=h.length;--j>-1;)g=h[j],(i||g instanceof b||(f=g.target===g.vars.onComplete)&&d||c&&!f)&&g.paused(a)};return f.pauseAll=function(a,b,c){o(!0,a,b,c)},f.resumeAll=function(a,b,c){o(!1,a,b,c)},f.globalTimeScale=function(b){var d=a._rootTimeline,e=c.ticker.time;return arguments.length?(b=b||g,d._startTime=e-(e-d._startTime)*d._timeScale/b,d=a._rootFramesTimeline,e=c.ticker.frame,d._startTime=e-(e-d._startTime)*d._timeScale/b,d._timeScale=a._rootTimeline._timeScale=b,b):d._timeScale},k.progress=function(a,b){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-a:a)+this._cycle*(this._duration+this._repeatDelay),b):this._time/this.duration()},k.totalProgress=function(a,b){return arguments.length?this.totalTime(this.totalDuration()*a,b):this._totalTime/this.totalDuration()},k.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),a>this._duration&&(a=this._duration),this._yoyo&&0!==(1&this._cycle)?a=this._duration-a+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(a+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(a,b)):this._time},k.duration=function(b){return arguments.length?a.prototype.duration.call(this,b):this._duration},k.totalDuration=function(a){return arguments.length?-1===this._repeat?this:this.duration((a-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat,this._dirty=!1),this._totalDuration)},k.repeat=function(a){return arguments.length?(this._repeat=a,this._uncache(!0)):this._repeat},k.repeatDelay=function(a){return arguments.length?(this._repeatDelay=a,this._uncache(!0)):this._repeatDelay},k.yoyo=function(a){return arguments.length?(this._yoyo=a,this):this._yoyo},f},!0),_gsScope._gsDefine("TimelineLite",["core.Animation","core.SimpleTimeline","TweenLite"],function(a,b,c){var d=function(a){b.call(this,a),this._labels={},this.autoRemoveChildren=this.vars.autoRemoveChildren===!0,this.smoothChildTiming=this.vars.smoothChildTiming===!0,this._sortChildren=!0,this._onUpdate=this.vars.onUpdate;var c,d,e=this.vars;for(d in e)c=e[d],i(c)&&-1!==c.join("").indexOf("{self}")&&(e[d]=this._swapSelfInParams(c));i(e.tweens)&&this.add(e.tweens,0,e.align,e.stagger)},e=1e-10,f=c._internals,g=d._internals={},h=f.isSelector,i=f.isArray,j=f.lazyTweens,k=f.lazyRender,l=_gsScope._gsDefine.globals,m=function(a){var b,c={};for(b in a)c[b]=a[b];return c},n=function(a,b,c){var d,e,f=a.cycle;for(d in f)e=f[d],a[d]="function"==typeof e?e.call(b[c],c):e[c%e.length];delete a.cycle},o=g.pauseCallback=function(){},p=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},q=d.prototype=new b;return d.version="1.18.5",q.constructor=d,q.kill()._gc=q._forcingPlayhead=q._hasPause=!1,q.to=function(a,b,d,e){var f=d.repeat&&l.TweenMax||c;return b?this.add(new f(a,b,d),e):this.set(a,d,e)},q.from=function(a,b,d,e){return this.add((d.repeat&&l.TweenMax||c).from(a,b,d),e)},q.fromTo=function(a,b,d,e,f){var g=e.repeat&&l.TweenMax||c;return b?this.add(g.fromTo(a,b,d,e),f):this.set(a,e,f)},q.staggerTo=function(a,b,e,f,g,i,j,k){var l,o,q=new d({onComplete:i,onCompleteParams:j,callbackScope:k,smoothChildTiming:this.smoothChildTiming}),r=e.cycle;for("string"==typeof a&&(a=c.selector(a)||a),a=a||[],h(a)&&(a=p(a)),f=f||0,0>f&&(a=p(a),a.reverse(),f*=-1),o=0;o<a.length;o++)l=m(e),l.startAt&&(l.startAt=m(l.startAt),l.startAt.cycle&&n(l.startAt,a,o)),r&&(n(l,a,o),null!=l.duration&&(b=l.duration,delete l.duration)),q.to(a[o],b,l,o*f);return this.add(q,g)},q.staggerFrom=function(a,b,c,d,e,f,g,h){return c.immediateRender=0!=c.immediateRender,c.runBackwards=!0,this.staggerTo(a,b,c,d,e,f,g,h)},q.staggerFromTo=function(a,b,c,d,e,f,g,h,i){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,this.staggerTo(a,b,d,e,f,g,h,i)},q.call=function(a,b,d,e){return this.add(c.delayedCall(0,a,b,d),e)},q.set=function(a,b,d){return d=this._parseTimeOrLabel(d,0,!0),null==b.immediateRender&&(b.immediateRender=d===this._time&&!this._paused),this.add(new c(a,0,b),d)},d.exportRoot=function(a,b){a=a||{},null==a.smoothChildTiming&&(a.smoothChildTiming=!0);var e,f,g=new d(a),h=g._timeline;for(null==b&&(b=!0),h._remove(g,!0),g._startTime=0,g._rawPrevTime=g._time=g._totalTime=h._time,e=h._first;e;)f=e._next,b&&e instanceof c&&e.target===e.vars.onComplete||g.add(e,e._startTime-e._delay),e=f;return h.add(g,0),g},q.add=function(e,f,g,h){var j,k,l,m,n,o;if("number"!=typeof f&&(f=this._parseTimeOrLabel(f,0,!0,e)),!(e instanceof a)){if(e instanceof Array||e&&e.push&&i(e)){for(g=g||"normal",h=h||0,j=f,k=e.length,l=0;k>l;l++)i(m=e[l])&&(m=new d({tweens:m})),this.add(m,j),"string"!=typeof m&&"function"!=typeof m&&("sequence"===g?j=m._startTime+m.totalDuration()/m._timeScale:"start"===g&&(m._startTime-=m.delay())),j+=h;return this._uncache(!0)}if("string"==typeof e)return this.addLabel(e,f);if("function"!=typeof e)throw"Cannot add "+e+" into the timeline; it is not a tween, timeline, function, or string.";e=c.delayedCall(0,e)}if(b.prototype.add.call(this,e,f),(this._gc||this._time===this._duration)&&!this._paused&&this._duration<this.duration())for(n=this,o=n.rawTime()>e._startTime;n._timeline;)o&&n._timeline.smoothChildTiming?n.totalTime(n._totalTime,!0):n._gc&&n._enabled(!0,!1),n=n._timeline;return this},q.remove=function(b){if(b instanceof a){this._remove(b,!1);var c=b._timeline=b.vars.useFrames?a._rootFramesTimeline:a._rootTimeline;return b._startTime=(b._paused?b._pauseTime:c._time)-(b._reversed?b.totalDuration()-b._totalTime:b._totalTime)/b._timeScale,this}if(b instanceof Array||b&&b.push&&i(b)){for(var d=b.length;--d>-1;)this.remove(b[d]);return this}return"string"==typeof b?this.removeLabel(b):this.kill(null,b)},q._remove=function(a,c){b.prototype._remove.call(this,a,c);var d=this._last;return d?this._time>d._startTime+d._totalDuration/d._timeScale&&(this._time=this.duration(),this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},q.append=function(a,b){return this.add(a,this._parseTimeOrLabel(null,b,!0,a))},q.insert=q.insertMultiple=function(a,b,c,d){return this.add(a,b||0,c,d)},q.appendMultiple=function(a,b,c,d){return this.add(a,this._parseTimeOrLabel(null,b,!0,a),c,d)},q.addLabel=function(a,b){return this._labels[a]=this._parseTimeOrLabel(b),this},q.addPause=function(a,b,d,e){var f=c.delayedCall(0,o,d,e||this);return f.vars.onComplete=f.vars.onReverseComplete=b,f.data="isPause",this._hasPause=!0,this.add(f,a)},q.removeLabel=function(a){return delete this._labels[a],this},q.getLabelTime=function(a){return null!=this._labels[a]?this._labels[a]:-1},q._parseTimeOrLabel=function(b,c,d,e){var f;if(e instanceof a&&e.timeline===this)this.remove(e);else if(e&&(e instanceof Array||e.push&&i(e)))for(f=e.length;--f>-1;)e[f]instanceof a&&e[f].timeline===this&&this.remove(e[f]);if("string"==typeof c)return this._parseTimeOrLabel(c,d&&"number"==typeof b&&null==this._labels[c]?b-this.duration():0,d);if(c=c||0,"string"!=typeof b||!isNaN(b)&&null==this._labels[b])null==b&&(b=this.duration());else{if(f=b.indexOf("="),-1===f)return null==this._labels[b]?d?this._labels[b]=this.duration()+c:c:this._labels[b]+c;c=parseInt(b.charAt(f-1)+"1",10)*Number(b.substr(f+1)),b=f>1?this._parseTimeOrLabel(b.substr(0,f-1),0,d):this.duration()}return Number(b)+c},q.seek=function(a,b){return this.totalTime("number"==typeof a?a:this._parseTimeOrLabel(a),b!==!1)},q.stop=function(){return this.paused(!0)},q.gotoAndPlay=function(a,b){return this.play(a,b)},q.gotoAndStop=function(a,b){return this.pause(a,b)},q.render=function(a,b,c){this._gc&&this._enabled(!0,!1);var d,f,g,h,i,l,m,n=this._dirty?this.totalDuration():this._totalDuration,o=this._time,p=this._startTime,q=this._timeScale,r=this._paused;if(a>=n-1e-7)this._totalTime=this._time=n,this._reversed||this._hasPausedChild()||(f=!0,h="onComplete",i=!!this._timeline.autoRemoveChildren,0===this._duration&&(0>=a&&a>=-1e-7||this._rawPrevTime<0||this._rawPrevTime===e)&&this._rawPrevTime!==a&&this._first&&(i=!0,this._rawPrevTime>e&&(h="onReverseComplete"))),this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,a=n+1e-4;else if(1e-7>a)if(this._totalTime=this._time=0,(0!==o||0===this._duration&&this._rawPrevTime!==e&&(this._rawPrevTime>0||0>a&&this._rawPrevTime>=0))&&(h="onReverseComplete",f=this._reversed),0>a)this._active=!1,this._timeline.autoRemoveChildren&&this._reversed?(i=f=!0,h="onReverseComplete"):this._rawPrevTime>=0&&this._first&&(i=!0),this._rawPrevTime=a;else{if(this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,0===a&&f)for(d=this._first;d&&0===d._startTime;)d._duration||(f=!1),d=d._next;a=0,this._initted||(i=!0)}else{if(this._hasPause&&!this._forcingPlayhead&&!b){if(a>=o)for(d=this._first;d&&d._startTime<=a&&!l;)d._duration||"isPause"!==d.data||d.ratio||0===d._startTime&&0===this._rawPrevTime||(l=d),d=d._next;else for(d=this._last;d&&d._startTime>=a&&!l;)d._duration||"isPause"===d.data&&d._rawPrevTime>0&&(l=d),d=d._prev;l&&(this._time=a=l._startTime,this._totalTime=a+this._cycle*(this._totalDuration+this._repeatDelay))}this._totalTime=this._time=this._rawPrevTime=a}if(this._time!==o&&this._first||c||i||l){if(this._initted||(this._initted=!0),this._active||!this._paused&&this._time!==o&&a>0&&(this._active=!0),0===o&&this.vars.onStart&&(0===this._time&&this._duration||b||this._callback("onStart")),m=this._time,m>=o)for(d=this._first;d&&(g=d._next,m===this._time&&(!this._paused||r));)(d._active||d._startTime<=m&&!d._paused&&!d._gc)&&(l===d&&this.pause(),d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)),d=g;else for(d=this._last;d&&(g=d._prev,m===this._time&&(!this._paused||r));){if(d._active||d._startTime<=o&&!d._paused&&!d._gc){if(l===d){for(l=d._prev;l&&l.endTime()>this._time;)l.render(l._reversed?l.totalDuration()-(a-l._startTime)*l._timeScale:(a-l._startTime)*l._timeScale,b,c),l=l._prev;l=null,this.pause()}d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)}d=g}this._onUpdate&&(b||(j.length&&k(),this._callback("onUpdate"))),h&&(this._gc||(p===this._startTime||q!==this._timeScale)&&(0===this._time||n>=this.totalDuration())&&(f&&(j.length&&k(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[h]&&this._callback(h)))}},q._hasPausedChild=function(){for(var a=this._first;a;){if(a._paused||a instanceof d&&a._hasPausedChild())return!0;a=a._next}return!1},q.getChildren=function(a,b,d,e){e=e||-9999999999;for(var f=[],g=this._first,h=0;g;)g._startTime<e||(g instanceof c?b!==!1&&(f[h++]=g):(d!==!1&&(f[h++]=g),a!==!1&&(f=f.concat(g.getChildren(!0,b,d)),h=f.length))),g=g._next;return f},q.getTweensOf=function(a,b){var d,e,f=this._gc,g=[],h=0;for(f&&this._enabled(!0,!0),d=c.getTweensOf(a),e=d.length;--e>-1;)(d[e].timeline===this||b&&this._contains(d[e]))&&(g[h++]=d[e]);return f&&this._enabled(!1,!0),g},q.recent=function(){return this._recent},q._contains=function(a){for(var b=a.timeline;b;){if(b===this)return!0;b=b.timeline}return!1},q.shiftChildren=function(a,b,c){c=c||0;for(var d,e=this._first,f=this._labels;e;)e._startTime>=c&&(e._startTime+=a),e=e._next;if(b)for(d in f)f[d]>=c&&(f[d]+=a);return this._uncache(!0)},q._kill=function(a,b){if(!a&&!b)return this._enabled(!1,!1);for(var c=b?this.getTweensOf(b):this.getChildren(!0,!0,!1),d=c.length,e=!1;--d>-1;)c[d]._kill(a,b)&&(e=!0);return e},q.clear=function(a){var b=this.getChildren(!1,!0,!0),c=b.length;for(this._time=this._totalTime=0;--c>-1;)b[c]._enabled(!1,!1);return a!==!1&&(this._labels={}),this._uncache(!0)},q.invalidate=function(){for(var b=this._first;b;)b.invalidate(),b=b._next;return a.prototype.invalidate.call(this)},q._enabled=function(a,c){if(a===this._gc)for(var d=this._first;d;)d._enabled(a,!0),d=d._next;return b.prototype._enabled.call(this,a,c)},q.totalTime=function(b,c,d){this._forcingPlayhead=!0;var e=a.prototype.totalTime.apply(this,arguments);return this._forcingPlayhead=!1,e},q.duration=function(a){return arguments.length?(0!==this.duration()&&0!==a&&this.timeScale(this._duration/a),this):(this._dirty&&this.totalDuration(),this._duration)},q.totalDuration=function(a){if(!arguments.length){if(this._dirty){for(var b,c,d=0,e=this._last,f=999999999999;e;)b=e._prev,e._dirty&&e.totalDuration(),e._startTime>f&&this._sortChildren&&!e._paused?this.add(e,e._startTime-e._delay):f=e._startTime,e._startTime<0&&!e._paused&&(d-=e._startTime,this._timeline.smoothChildTiming&&(this._startTime+=e._startTime/this._timeScale),this.shiftChildren(-e._startTime,!1,-9999999999),f=0),c=e._startTime+e._totalDuration/e._timeScale,c>d&&(d=c),e=b;this._duration=this._totalDuration=d,this._dirty=!1}return this._totalDuration}return a&&this.totalDuration()?this.timeScale(this._totalDuration/a):this},q.paused=function(b){if(!b)for(var c=this._first,d=this._time;c;)c._startTime===d&&"isPause"===c.data&&(c._rawPrevTime=0),c=c._next;return a.prototype.paused.apply(this,arguments)},q.usesFrames=function(){for(var b=this._timeline;b._timeline;)b=b._timeline;return b===a._rootFramesTimeline},q.rawTime=function(){return this._paused?this._totalTime:(this._timeline.rawTime()-this._startTime)*this._timeScale},d},!0),_gsScope._gsDefine("TimelineMax",["TimelineLite","TweenLite","easing.Ease"],function(a,b,c){var d=function(b){a.call(this,b),this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._dirty=!0},e=1e-10,f=b._internals,g=f.lazyTweens,h=f.lazyRender,i=new c(null,null,1,0),j=d.prototype=new a;return j.constructor=d,j.kill()._gc=!1,d.version="1.18.5",j.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),a.prototype.invalidate.call(this)},j.addCallback=function(a,c,d,e){return this.add(b.delayedCall(0,a,d,e),c)},j.removeCallback=function(a,b){if(a)if(null==b)this._kill(null,a);else for(var c=this.getTweensOf(a,!1),d=c.length,e=this._parseTimeOrLabel(b);--d>-1;)c[d]._startTime===e&&c[d]._enabled(!1,!1);return this},j.removePause=function(b){return this.removeCallback(a._internals.pauseCallback,b)},j.tweenTo=function(a,c){c=c||{};var d,e,f,g={ease:i,useFrames:this.usesFrames(),immediateRender:!1};for(e in c)g[e]=c[e];return g.time=this._parseTimeOrLabel(a),d=Math.abs(Number(g.time)-this._time)/this._timeScale||.001,f=new b(this,d,g),g.onStart=function(){f.target.paused(!0),f.vars.time!==f.target.time()&&d===f.duration()&&f.duration(Math.abs(f.vars.time-f.target.time())/f.target._timeScale),c.onStart&&f._callback("onStart")},f},j.tweenFromTo=function(a,b,c){c=c||{},a=this._parseTimeOrLabel(a),c.startAt={onComplete:this.seek,onCompleteParams:[a],callbackScope:this},c.immediateRender=c.immediateRender!==!1;var d=this.tweenTo(b,c);return d.duration(Math.abs(d.vars.time-a)/this._timeScale||.001)},j.render=function(a,b,c){this._gc&&this._enabled(!0,!1);var d,f,i,j,k,l,m,n,o=this._dirty?this.totalDuration():this._totalDuration,p=this._duration,q=this._time,r=this._totalTime,s=this._startTime,t=this._timeScale,u=this._rawPrevTime,v=this._paused,w=this._cycle;if(a>=o-1e-7)this._locked||(this._totalTime=o,this._cycle=this._repeat),this._reversed||this._hasPausedChild()||(f=!0,j="onComplete",k=!!this._timeline.autoRemoveChildren,0===this._duration&&(0>=a&&a>=-1e-7||0>u||u===e)&&u!==a&&this._first&&(k=!0,u>e&&(j="onReverseComplete"))),this._rawPrevTime=this._duration||!b||a||this._rawPrevTime===a?a:e,this._yoyo&&0!==(1&this._cycle)?this._time=a=0:(this._time=p,a=p+1e-4);else if(1e-7>a)if(this._locked||(this._totalTime=this._cycle=0),this._time=0,(0!==q||0===p&&u!==e&&(u>0||0>a&&u>=0)&&!this._locked)&&(j="onReverseComplete",f=this._reversed),0>a)this._active=!1,this._timeline.autoRemoveChildren&&this._reversed?(k=f=!0,j="onReverseComplete"):u>=0&&this._first&&(k=!0),this._rawPrevTime=a;else{if(this._rawPrevTime=p||!b||a||this._rawPrevTime===a?a:e,0===a&&f)for(d=this._first;d&&0===d._startTime;)d._duration||(f=!1),d=d._next;a=0,this._initted||(k=!0)}else if(0===p&&0>u&&(k=!0),this._time=this._rawPrevTime=a,this._locked||(this._totalTime=a,0!==this._repeat&&(l=p+this._repeatDelay,this._cycle=this._totalTime/l>>0,0!==this._cycle&&this._cycle===this._totalTime/l&&a>=r&&this._cycle--,this._time=this._totalTime-this._cycle*l,this._yoyo&&0!==(1&this._cycle)&&(this._time=p-this._time),this._time>p?(this._time=p,a=p+1e-4):this._time<0?this._time=a=0:a=this._time)),this._hasPause&&!this._forcingPlayhead&&!b){if(a=this._time,a>=q)for(d=this._first;d&&d._startTime<=a&&!m;)d._duration||"isPause"!==d.data||d.ratio||0===d._startTime&&0===this._rawPrevTime||(m=d),d=d._next;else for(d=this._last;d&&d._startTime>=a&&!m;)d._duration||"isPause"===d.data&&d._rawPrevTime>0&&(m=d),d=d._prev;m&&(this._time=a=m._startTime,this._totalTime=a+this._cycle*(this._totalDuration+this._repeatDelay))}if(this._cycle!==w&&!this._locked){var x=this._yoyo&&0!==(1&w),y=x===(this._yoyo&&0!==(1&this._cycle)),z=this._totalTime,A=this._cycle,B=this._rawPrevTime,C=this._time;if(this._totalTime=w*p,this._cycle<w?x=!x:this._totalTime+=p,this._time=q,this._rawPrevTime=0===p?u-1e-4:u,this._cycle=w,this._locked=!0,q=x?0:p,this.render(q,b,0===p),b||this._gc||this.vars.onRepeat&&this._callback("onRepeat"),q!==this._time)return;if(y&&(q=x?p+1e-4:-1e-4,this.render(q,!0,!1)),this._locked=!1,this._paused&&!v)return;this._time=C,this._totalTime=z,this._cycle=A,this._rawPrevTime=B}if(!(this._time!==q&&this._first||c||k||m))return void(r!==this._totalTime&&this._onUpdate&&(b||this._callback("onUpdate")));if(this._initted||(this._initted=!0),this._active||!this._paused&&this._totalTime!==r&&a>0&&(this._active=!0),0===r&&this.vars.onStart&&(0===this._totalTime&&this._totalDuration||b||this._callback("onStart")),n=this._time,n>=q)for(d=this._first;d&&(i=d._next,n===this._time&&(!this._paused||v));)(d._active||d._startTime<=this._time&&!d._paused&&!d._gc)&&(m===d&&this.pause(),d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)),d=i;else for(d=this._last;d&&(i=d._prev,n===this._time&&(!this._paused||v));){if(d._active||d._startTime<=q&&!d._paused&&!d._gc){if(m===d){for(m=d._prev;m&&m.endTime()>this._time;)m.render(m._reversed?m.totalDuration()-(a-m._startTime)*m._timeScale:(a-m._startTime)*m._timeScale,b,c),m=m._prev;m=null,this.pause()}d._reversed?d.render((d._dirty?d.totalDuration():d._totalDuration)-(a-d._startTime)*d._timeScale,b,c):d.render((a-d._startTime)*d._timeScale,b,c)}d=i}this._onUpdate&&(b||(g.length&&h(),this._callback("onUpdate"))),j&&(this._locked||this._gc||(s===this._startTime||t!==this._timeScale)&&(0===this._time||o>=this.totalDuration())&&(f&&(g.length&&h(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[j]&&this._callback(j)))},j.getActive=function(a,b,c){null==a&&(a=!0),null==b&&(b=!0),null==c&&(c=!1);var d,e,f=[],g=this.getChildren(a,b,c),h=0,i=g.length;for(d=0;i>d;d++)e=g[d],e.isActive()&&(f[h++]=e);return f},j.getLabelAfter=function(a){a||0!==a&&(a=this._time);var b,c=this.getLabelsArray(),d=c.length;for(b=0;d>b;b++)if(c[b].time>a)return c[b].name;return null},j.getLabelBefore=function(a){null==a&&(a=this._time);for(var b=this.getLabelsArray(),c=b.length;--c>-1;)if(b[c].time<a)return b[c].name;return null},j.getLabelsArray=function(){var a,b=[],c=0;for(a in this._labels)b[c++]={time:this._labels[a],name:a};return b.sort(function(a,b){return a.time-b.time}),b},j.progress=function(a,b){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-a:a)+this._cycle*(this._duration+this._repeatDelay),b):this._time/this.duration()},j.totalProgress=function(a,b){return arguments.length?this.totalTime(this.totalDuration()*a,b):this._totalTime/this.totalDuration()},j.totalDuration=function(b){return arguments.length?-1!==this._repeat&&b?this.timeScale(this.totalDuration()/b):this:(this._dirty&&(a.prototype.totalDuration.call(this),this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat),this._totalDuration)},j.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),a>this._duration&&(a=this._duration),this._yoyo&&0!==(1&this._cycle)?a=this._duration-a+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(a+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(a,b)):this._time},j.repeat=function(a){return arguments.length?(this._repeat=a,this._uncache(!0)):this._repeat},j.repeatDelay=function(a){return arguments.length?(this._repeatDelay=a,this._uncache(!0)):this._repeatDelay},j.yoyo=function(a){return arguments.length?(this._yoyo=a,this):this._yoyo},j.currentLabel=function(a){return arguments.length?this.seek(a,!0):this.getLabelBefore(this._time+1e-8)},d},!0),function(){var a=180/Math.PI,b=[],c=[],d=[],e={},f=_gsScope._gsDefine.globals,g=function(a,b,c,d){c===d&&(c=d-(d-b)/1e6),a===b&&(b=a+(c-a)/1e6),this.a=a,this.b=b,this.c=c,this.d=d,this.da=d-a,this.ca=c-a,this.ba=b-a},h=",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",i=function(a,b,c,d){var e={a:a},f={},g={},h={c:d},i=(a+b)/2,j=(b+c)/2,k=(c+d)/2,l=(i+j)/2,m=(j+k)/2,n=(m-l)/8;return e.b=i+(a-i)/4,f.b=l+n,e.c=f.a=(e.b+f.b)/2,f.c=g.a=(l+m)/2,g.b=m-n,h.b=k+(d-k)/4,g.c=h.a=(g.b+h.b)/2,[e,f,g,h]},j=function(a,e,f,g,h){var j,k,l,m,n,o,p,q,r,s,t,u,v,w=a.length-1,x=0,y=a[0].a;for(j=0;w>j;j++)n=a[x],k=n.a,l=n.d,m=a[x+1].d,h?(t=b[j],u=c[j],v=(u+t)*e*.25/(g?.5:d[j]||.5),o=l-(l-k)*(g?.5*e:0!==t?v/t:0),p=l+(m-l)*(g?.5*e:0!==u?v/u:0),q=l-(o+((p-o)*(3*t/(t+u)+.5)/4||0))):(o=l-(l-k)*e*.5,p=l+(m-l)*e*.5,q=l-(o+p)/2),o+=q,p+=q,n.c=r=o,0!==j?n.b=y:n.b=y=n.a+.6*(n.c-n.a),n.da=l-k,n.ca=r-k,n.ba=y-k,f?(s=i(k,y,r,l),a.splice(x,1,s[0],s[1],s[2],s[3]),x+=4):x++,y=p;n=a[x],n.b=y,n.c=y+.4*(n.d-y),n.da=n.d-n.a,n.ca=n.c-n.a,n.ba=y-n.a,f&&(s=i(n.a,y,n.c,n.d),a.splice(x,1,s[0],s[1],s[2],s[3]))},k=function(a,d,e,f){var h,i,j,k,l,m,n=[];if(f)for(a=[f].concat(a),i=a.length;--i>-1;)"string"==typeof(m=a[i][d])&&"="===m.charAt(1)&&(a[i][d]=f[d]+Number(m.charAt(0)+m.substr(2)));if(h=a.length-2,0>h)return n[0]=new g(a[0][d],0,0,a[-1>h?0:1][d]),n;for(i=0;h>i;i++)j=a[i][d],k=a[i+1][d],n[i]=new g(j,0,0,k),e&&(l=a[i+2][d],b[i]=(b[i]||0)+(k-j)*(k-j),c[i]=(c[i]||0)+(l-k)*(l-k));return n[i]=new g(a[i][d],0,0,a[i+1][d]),n},l=function(a,f,g,i,l,m){var n,o,p,q,r,s,t,u,v={},w=[],x=m||a[0];l="string"==typeof l?","+l+",":h,null==f&&(f=1);for(o in a[0])w.push(o);if(a.length>1){for(u=a[a.length-1],t=!0,n=w.length;--n>-1;)if(o=w[n],Math.abs(x[o]-u[o])>.05){t=!1;break}t&&(a=a.concat(),m&&a.unshift(m),a.push(a[1]),m=a[a.length-3])}for(b.length=c.length=d.length=0,n=w.length;--n>-1;)o=w[n],e[o]=-1!==l.indexOf(","+o+","),v[o]=k(a,o,e[o],m);for(n=b.length;--n>-1;)b[n]=Math.sqrt(b[n]),c[n]=Math.sqrt(c[n]);if(!i){for(n=w.length;--n>-1;)if(e[o])for(p=v[w[n]],s=p.length-1,q=0;s>q;q++)r=p[q+1].da/c[q]+p[q].da/b[q]||0,d[q]=(d[q]||0)+r*r;for(n=d.length;--n>-1;)d[n]=Math.sqrt(d[n])}for(n=w.length,q=g?4:1;--n>-1;)o=w[n],p=v[o],j(p,f,g,i,e[o]),t&&(p.splice(0,q),p.splice(p.length-q,q));return v},m=function(a,b,c){b=b||"soft";var d,e,f,h,i,j,k,l,m,n,o,p={},q="cubic"===b?3:2,r="soft"===b,s=[];if(r&&c&&(a=[c].concat(a)),null==a||a.length<q+1)throw"invalid Bezier data";for(m in a[0])s.push(m);for(j=s.length;--j>-1;){for(m=s[j],p[m]=i=[],n=0,l=a.length,k=0;l>k;k++)d=null==c?a[k][m]:"string"==typeof(o=a[k][m])&&"="===o.charAt(1)?c[m]+Number(o.charAt(0)+o.substr(2)):Number(o),r&&k>1&&l-1>k&&(i[n++]=(d+i[n-2])/2),i[n++]=d;for(l=n-q+1,n=0,k=0;l>k;k+=q)d=i[k],e=i[k+1],f=i[k+2],h=2===q?0:i[k+3],i[n++]=o=3===q?new g(d,e,f,h):new g(d,(2*e+d)/3,(2*e+f)/3,f);i.length=n}return p},n=function(a,b,c){for(var d,e,f,g,h,i,j,k,l,m,n,o=1/c,p=a.length;--p>-1;)for(m=a[p],f=m.a,g=m.d-f,h=m.c-f,i=m.b-f,d=e=0,k=1;c>=k;k++)j=o*k,l=1-j,d=e-(e=(j*j*g+3*l*(j*h+l*i))*j),n=p*c+k-1,b[n]=(b[n]||0)+d*d},o=function(a,b){b=b>>0||6;var c,d,e,f,g=[],h=[],i=0,j=0,k=b-1,l=[],m=[];for(c in a)n(a[c],g,b);for(e=g.length,d=0;e>d;d++)i+=Math.sqrt(g[d]),f=d%b,m[f]=i,f===k&&(j+=i,f=d/b>>0,l[f]=m,h[f]=j,i=0,m=[]);return{length:j,lengths:h,segments:l}},p=_gsScope._gsDefine.plugin({propName:"bezier", priority:-1,version:"1.3.6",API:2,global:!0,init:function(a,b,c){this._target=a,b instanceof Array&&(b={values:b}),this._func={},this._round={},this._props=[],this._timeRes=null==b.timeResolution?6:parseInt(b.timeResolution,10);var d,e,f,g,h,i=b.values||[],j={},k=i[0],n=b.autoRotate||c.vars.orientToBezier;this._autoRotate=n?n instanceof Array?n:[["x","y","rotation",n===!0?0:Number(n)||0]]:null;for(d in k)this._props.push(d);for(f=this._props.length;--f>-1;)d=this._props[f],this._overwriteProps.push(d),e=this._func[d]="function"==typeof a[d],j[d]=e?a[d.indexOf("set")||"function"!=typeof a["get"+d.substr(3)]?d:"get"+d.substr(3)]():parseFloat(a[d]),h||j[d]!==i[0][d]&&(h=j);if(this._beziers="cubic"!==b.type&&"quadratic"!==b.type&&"soft"!==b.type?l(i,isNaN(b.curviness)?1:b.curviness,!1,"thruBasic"===b.type,b.correlate,h):m(i,b.type,j),this._segCount=this._beziers[d].length,this._timeRes){var p=o(this._beziers,this._timeRes);this._length=p.length,this._lengths=p.lengths,this._segments=p.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(n=this._autoRotate)for(this._initialRotations=[],n[0]instanceof Array||(this._autoRotate=n=[n]),f=n.length;--f>-1;){for(g=0;3>g;g++)d=n[f][g],this._func[d]="function"==typeof a[d]?a[d.indexOf("set")||"function"!=typeof a["get"+d.substr(3)]?d:"get"+d.substr(3)]:!1;d=n[f][2],this._initialRotations[f]=(this._func[d]?this._func[d].call(this._target):this._target[d])||0}return this._startRatio=c.vars.runBackwards?1:0,!0},set:function(b){var c,d,e,f,g,h,i,j,k,l,m=this._segCount,n=this._func,o=this._target,p=b!==this._startRatio;if(this._timeRes){if(k=this._lengths,l=this._curSeg,b*=this._length,e=this._li,b>this._l2&&m-1>e){for(j=m-1;j>e&&(this._l2=k[++e])<=b;);this._l1=k[e-1],this._li=e,this._curSeg=l=this._segments[e],this._s2=l[this._s1=this._si=0]}else if(b<this._l1&&e>0){for(;e>0&&(this._l1=k[--e])>=b;);0===e&&b<this._l1?this._l1=0:e++,this._l2=k[e],this._li=e,this._curSeg=l=this._segments[e],this._s1=l[(this._si=l.length-1)-1]||0,this._s2=l[this._si]}if(c=e,b-=this._l1,e=this._si,b>this._s2&&e<l.length-1){for(j=l.length-1;j>e&&(this._s2=l[++e])<=b;);this._s1=l[e-1],this._si=e}else if(b<this._s1&&e>0){for(;e>0&&(this._s1=l[--e])>=b;);0===e&&b<this._s1?this._s1=0:e++,this._s2=l[e],this._si=e}h=(e+(b-this._s1)/(this._s2-this._s1))*this._prec||0}else c=0>b?0:b>=1?m-1:m*b>>0,h=(b-c*(1/m))*m;for(d=1-h,e=this._props.length;--e>-1;)f=this._props[e],g=this._beziers[f][c],i=(h*h*g.da+3*d*(h*g.ca+d*g.ba))*h+g.a,this._round[f]&&(i=Math.round(i)),n[f]?o[f](i):o[f]=i;if(this._autoRotate){var q,r,s,t,u,v,w,x=this._autoRotate;for(e=x.length;--e>-1;)f=x[e][2],v=x[e][3]||0,w=x[e][4]===!0?1:a,g=this._beziers[x[e][0]],q=this._beziers[x[e][1]],g&&q&&(g=g[c],q=q[c],r=g.a+(g.b-g.a)*h,t=g.b+(g.c-g.b)*h,r+=(t-r)*h,t+=(g.c+(g.d-g.c)*h-t)*h,s=q.a+(q.b-q.a)*h,u=q.b+(q.c-q.b)*h,s+=(u-s)*h,u+=(q.c+(q.d-q.c)*h-u)*h,i=p?Math.atan2(u-s,t-r)*w+v:this._initialRotations[e],n[f]?o[f](i):o[f]=i)}}}),q=p.prototype;p.bezierThrough=l,p.cubicToQuadratic=i,p._autoCSS=!0,p.quadraticToCubic=function(a,b,c){return new g(a,(2*b+a)/3,(2*b+c)/3,c)},p._cssRegister=function(){var a=f.CSSPlugin;if(a){var b=a._internals,c=b._parseToProxy,d=b._setPluginRatio,e=b.CSSPropTween;b._registerComplexSpecialProp("bezier",{parser:function(a,b,f,g,h,i){b instanceof Array&&(b={values:b}),i=new p;var j,k,l,m=b.values,n=m.length-1,o=[],q={};if(0>n)return h;for(j=0;n>=j;j++)l=c(a,m[j],g,h,i,n!==j),o[j]=l.end;for(k in b)q[k]=b[k];return q.values=o,h=new e(a,"bezier",0,0,l.pt,2),h.data=l,h.plugin=i,h.setRatio=d,0===q.autoRotate&&(q.autoRotate=!0),!q.autoRotate||q.autoRotate instanceof Array||(j=q.autoRotate===!0?0:Number(q.autoRotate),q.autoRotate=null!=l.end.left?[["left","top","rotation",j,!1]]:null!=l.end.x?[["x","y","rotation",j,!1]]:!1),q.autoRotate&&(g._transform||g._enableTransforms(!1),l.autoRotate=g._target._gsTransform,l.proxy.rotation=l.autoRotate.rotation||0),i._onInitTween(l.proxy,q,g._tween),h}})}},q._roundProps=function(a,b){for(var c=this._overwriteProps,d=c.length;--d>-1;)(a[c[d]]||a.bezier||a.bezierThrough)&&(this._round[c[d]]=b)},q._kill=function(a){var b,c,d=this._props;for(b in this._beziers)if(b in a)for(delete this._beziers[b],delete this._func[b],c=d.length;--c>-1;)d[c]===b&&d.splice(c,1);return this._super._kill.call(this,a)}}(),_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(a,b){var c,d,e,f,g=function(){a.call(this,"css"),this._overwriteProps.length=0,this.setRatio=g.prototype.setRatio},h=_gsScope._gsDefine.globals,i={},j=g.prototype=new a("css");j.constructor=g,g.version="1.18.5",g.API=2,g.defaultTransformPerspective=0,g.defaultSkewType="compensated",g.defaultSmoothOrigin=!0,j="px",g.suffixMap={top:j,right:j,bottom:j,left:j,width:j,height:j,fontSize:j,padding:j,margin:j,perspective:j,lineHeight:""};var k,l,m,n,o,p,q=/(?:\-|\.|\b)(\d|\.|e\-)+/g,r=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,s=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,t=/(?![+-]?\d*\.?\d+|[+-]|e[+-]\d+)[^0-9]/g,u=/(?:\d|\-|\+|=|#|\.)*/g,v=/opacity *= *([^)]*)/i,w=/opacity:([^;]*)/i,x=/alpha\(opacity *=.+?\)/i,y=/^(rgb|hsl)/,z=/([A-Z])/g,A=/-([a-z])/gi,B=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,C=function(a,b){return b.toUpperCase()},D=/(?:Left|Right|Width)/i,E=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,F=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,G=/,(?=[^\)]*(?:\(|$))/gi,H=/[\s,\(]/i,I=Math.PI/180,J=180/Math.PI,K={},L=document,M=function(a){return L.createElementNS?L.createElementNS("http://www.w3.org/1999/xhtml",a):L.createElement(a)},N=M("div"),O=M("img"),P=g._internals={_specialProps:i},Q=navigator.userAgent,R=function(){var a=Q.indexOf("Android"),b=M("a");return m=-1!==Q.indexOf("Safari")&&-1===Q.indexOf("Chrome")&&(-1===a||Number(Q.substr(a+8,1))>3),o=m&&Number(Q.substr(Q.indexOf("Version/")+8,1))<6,n=-1!==Q.indexOf("Firefox"),(/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(Q)||/Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(Q))&&(p=parseFloat(RegExp.$1)),b?(b.style.cssText="top:1px;opacity:.55;",/^0.55/.test(b.style.opacity)):!1}(),S=function(a){return v.test("string"==typeof a?a:(a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100:1},T=function(a){window.console&&console.log(a)},U="",V="",W=function(a,b){b=b||N;var c,d,e=b.style;if(void 0!==e[a])return a;for(a=a.charAt(0).toUpperCase()+a.substr(1),c=["O","Moz","ms","Ms","Webkit"],d=5;--d>-1&&void 0===e[c[d]+a];);return d>=0?(V=3===d?"ms":c[d],U="-"+V.toLowerCase()+"-",V+a):null},X=L.defaultView?L.defaultView.getComputedStyle:function(){},Y=g.getStyle=function(a,b,c,d,e){var f;return R||"opacity"!==b?(!d&&a.style[b]?f=a.style[b]:(c=c||X(a))?f=c[b]||c.getPropertyValue(b)||c.getPropertyValue(b.replace(z,"-$1").toLowerCase()):a.currentStyle&&(f=a.currentStyle[b]),null==e||f&&"none"!==f&&"auto"!==f&&"auto auto"!==f?f:e):S(a)},Z=P.convertToPixels=function(a,c,d,e,f){if("px"===e||!e)return d;if("auto"===e||!d)return 0;var h,i,j,k=D.test(c),l=a,m=N.style,n=0>d,o=1===d;if(n&&(d=-d),o&&(d*=100),"%"===e&&-1!==c.indexOf("border"))h=d/100*(k?a.clientWidth:a.clientHeight);else{if(m.cssText="border:0 solid red;position:"+Y(a,"position")+";line-height:0;","%"!==e&&l.appendChild&&"v"!==e.charAt(0)&&"rem"!==e)m[k?"borderLeftWidth":"borderTopWidth"]=d+e;else{if(l=a.parentNode||L.body,i=l._gsCache,j=b.ticker.frame,i&&k&&i.time===j)return i.width*d/100;m[k?"width":"height"]=d+e}l.appendChild(N),h=parseFloat(N[k?"offsetWidth":"offsetHeight"]),l.removeChild(N),k&&"%"===e&&g.cacheWidths!==!1&&(i=l._gsCache=l._gsCache||{},i.time=j,i.width=h/d*100),0!==h||f||(h=Z(a,c,d,e,!0))}return o&&(h/=100),n?-h:h},$=P.calculateOffset=function(a,b,c){if("absolute"!==Y(a,"position",c))return 0;var d="left"===b?"Left":"Top",e=Y(a,"margin"+d,c);return a["offset"+d]-(Z(a,b,parseFloat(e),e.replace(u,""))||0)},_=function(a,b){var c,d,e,f={};if(b=b||X(a,null))if(c=b.length)for(;--c>-1;)e=b[c],(-1===e.indexOf("-transform")||Aa===e)&&(f[e.replace(A,C)]=b.getPropertyValue(e));else for(c in b)(-1===c.indexOf("Transform")||za===c)&&(f[c]=b[c]);else if(b=a.currentStyle||a.style)for(c in b)"string"==typeof c&&void 0===f[c]&&(f[c.replace(A,C)]=b[c]);return R||(f.opacity=S(a)),d=Na(a,b,!1),f.rotation=d.rotation,f.skewX=d.skewX,f.scaleX=d.scaleX,f.scaleY=d.scaleY,f.x=d.x,f.y=d.y,Ca&&(f.z=d.z,f.rotationX=d.rotationX,f.rotationY=d.rotationY,f.scaleZ=d.scaleZ),f.filters&&delete f.filters,f},aa=function(a,b,c,d,e){var f,g,h,i={},j=a.style;for(g in c)"cssText"!==g&&"length"!==g&&isNaN(g)&&(b[g]!==(f=c[g])||e&&e[g])&&-1===g.indexOf("Origin")&&("number"==typeof f||"string"==typeof f)&&(i[g]="auto"!==f||"left"!==g&&"top"!==g?""!==f&&"auto"!==f&&"none"!==f||"string"!=typeof b[g]||""===b[g].replace(t,"")?f:0:$(a,g),void 0!==j[g]&&(h=new pa(j,g,j[g],h)));if(d)for(g in d)"className"!==g&&(i[g]=d[g]);return{difs:i,firstMPT:h}},ba={width:["Left","Right"],height:["Top","Bottom"]},ca=["marginLeft","marginRight","marginTop","marginBottom"],da=function(a,b,c){if("svg"===(a.nodeName+"").toLowerCase())return(c||X(a))[b]||0;if(a.getBBox&&Ka(a))return a.getBBox()[b]||0;var d=parseFloat("width"===b?a.offsetWidth:a.offsetHeight),e=ba[b],f=e.length;for(c=c||X(a,null);--f>-1;)d-=parseFloat(Y(a,"padding"+e[f],c,!0))||0,d-=parseFloat(Y(a,"border"+e[f]+"Width",c,!0))||0;return d},ea=function(a,b){if("contain"===a||"auto"===a||"auto auto"===a)return a+" ";(null==a||""===a)&&(a="0 0");var c,d=a.split(" "),e=-1!==a.indexOf("left")?"0%":-1!==a.indexOf("right")?"100%":d[0],f=-1!==a.indexOf("top")?"0%":-1!==a.indexOf("bottom")?"100%":d[1];if(d.length>3&&!b){for(d=a.split(", ").join(",").split(","),a=[],c=0;c<d.length;c++)a.push(ea(d[c]));return a.join(",")}return null==f?f="center"===e?"50%":"0":"center"===f&&(f="50%"),("center"===e||isNaN(parseFloat(e))&&-1===(e+"").indexOf("="))&&(e="50%"),a=e+" "+f+(d.length>2?" "+d[2]:""),b&&(b.oxp=-1!==e.indexOf("%"),b.oyp=-1!==f.indexOf("%"),b.oxr="="===e.charAt(1),b.oyr="="===f.charAt(1),b.ox=parseFloat(e.replace(t,"")),b.oy=parseFloat(f.replace(t,"")),b.v=a),b||a},fa=function(a,b){return"string"==typeof a&&"="===a.charAt(1)?parseInt(a.charAt(0)+"1",10)*parseFloat(a.substr(2)):parseFloat(a)-parseFloat(b)||0},ga=function(a,b){return null==a?b:"string"==typeof a&&"="===a.charAt(1)?parseInt(a.charAt(0)+"1",10)*parseFloat(a.substr(2))+b:parseFloat(a)||0},ha=function(a,b,c,d){var e,f,g,h,i,j=1e-6;return null==a?h=b:"number"==typeof a?h=a:(e=360,f=a.split("_"),i="="===a.charAt(1),g=(i?parseInt(a.charAt(0)+"1",10)*parseFloat(f[0].substr(2)):parseFloat(f[0]))*(-1===a.indexOf("rad")?1:J)-(i?0:b),f.length&&(d&&(d[c]=b+g),-1!==a.indexOf("short")&&(g%=e,g!==g%(e/2)&&(g=0>g?g+e:g-e)),-1!==a.indexOf("_cw")&&0>g?g=(g+9999999999*e)%e-(g/e|0)*e:-1!==a.indexOf("ccw")&&g>0&&(g=(g-9999999999*e)%e-(g/e|0)*e)),h=b+g),j>h&&h>-j&&(h=0),h},ia={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},ja=function(a,b,c){return a=0>a?a+1:a>1?a-1:a,255*(1>6*a?b+(c-b)*a*6:.5>a?c:2>3*a?b+(c-b)*(2/3-a)*6:b)+.5|0},ka=g.parseColor=function(a,b){var c,d,e,f,g,h,i,j,k,l,m;if(a)if("number"==typeof a)c=[a>>16,a>>8&255,255&a];else{if(","===a.charAt(a.length-1)&&(a=a.substr(0,a.length-1)),ia[a])c=ia[a];else if("#"===a.charAt(0))4===a.length&&(d=a.charAt(1),e=a.charAt(2),f=a.charAt(3),a="#"+d+d+e+e+f+f),a=parseInt(a.substr(1),16),c=[a>>16,a>>8&255,255&a];else if("hsl"===a.substr(0,3))if(c=m=a.match(q),b){if(-1!==a.indexOf("="))return a.match(r)}else g=Number(c[0])%360/360,h=Number(c[1])/100,i=Number(c[2])/100,e=.5>=i?i*(h+1):i+h-i*h,d=2*i-e,c.length>3&&(c[3]=Number(a[3])),c[0]=ja(g+1/3,d,e),c[1]=ja(g,d,e),c[2]=ja(g-1/3,d,e);else c=a.match(q)||ia.transparent;c[0]=Number(c[0]),c[1]=Number(c[1]),c[2]=Number(c[2]),c.length>3&&(c[3]=Number(c[3]))}else c=ia.black;return b&&!m&&(d=c[0]/255,e=c[1]/255,f=c[2]/255,j=Math.max(d,e,f),k=Math.min(d,e,f),i=(j+k)/2,j===k?g=h=0:(l=j-k,h=i>.5?l/(2-j-k):l/(j+k),g=j===d?(e-f)/l+(f>e?6:0):j===e?(f-d)/l+2:(d-e)/l+4,g*=60),c[0]=g+.5|0,c[1]=100*h+.5|0,c[2]=100*i+.5|0),c},la=function(a,b){var c,d,e,f=a.match(ma)||[],g=0,h=f.length?"":a;for(c=0;c<f.length;c++)d=f[c],e=a.substr(g,a.indexOf(d,g)-g),g+=e.length+d.length,d=ka(d,b),3===d.length&&d.push(1),h+=e+(b?"hsla("+d[0]+","+d[1]+"%,"+d[2]+"%,"+d[3]:"rgba("+d.join(","))+")";return h+a.substr(g)},ma="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#(?:[0-9a-f]{3}){1,2}\\b";for(j in ia)ma+="|"+j+"\\b";ma=new RegExp(ma+")","gi"),g.colorStringFilter=function(a){var b,c=a[0]+a[1];ma.test(c)&&(b=-1!==c.indexOf("hsl(")||-1!==c.indexOf("hsla("),a[0]=la(a[0],b),a[1]=la(a[1],b)),ma.lastIndex=0},b.defaultStringFilter||(b.defaultStringFilter=g.colorStringFilter);var na=function(a,b,c,d){if(null==a)return function(a){return a};var e,f=b?(a.match(ma)||[""])[0]:"",g=a.split(f).join("").match(s)||[],h=a.substr(0,a.indexOf(g[0])),i=")"===a.charAt(a.length-1)?")":"",j=-1!==a.indexOf(" ")?" ":",",k=g.length,l=k>0?g[0].replace(q,""):"";return k?e=b?function(a){var b,m,n,o;if("number"==typeof a)a+=l;else if(d&&G.test(a)){for(o=a.replace(G,"|").split("|"),n=0;n<o.length;n++)o[n]=e(o[n]);return o.join(",")}if(b=(a.match(ma)||[f])[0],m=a.split(b).join("").match(s)||[],n=m.length,k>n--)for(;++n<k;)m[n]=c?m[(n-1)/2|0]:g[n];return h+m.join(j)+j+b+i+(-1!==a.indexOf("inset")?" inset":"")}:function(a){var b,f,m;if("number"==typeof a)a+=l;else if(d&&G.test(a)){for(f=a.replace(G,"|").split("|"),m=0;m<f.length;m++)f[m]=e(f[m]);return f.join(",")}if(b=a.match(s)||[],m=b.length,k>m--)for(;++m<k;)b[m]=c?b[(m-1)/2|0]:g[m];return h+b.join(j)+i}:function(a){return a}},oa=function(a){return a=a.split(","),function(b,c,d,e,f,g,h){var i,j=(c+"").split(" ");for(h={},i=0;4>i;i++)h[a[i]]=j[i]=j[i]||j[(i-1)/2>>0];return e.parse(b,h,f,g)}},pa=(P._setPluginRatio=function(a){this.plugin.setRatio(a);for(var b,c,d,e,f,g=this.data,h=g.proxy,i=g.firstMPT,j=1e-6;i;)b=h[i.v],i.r?b=Math.round(b):j>b&&b>-j&&(b=0),i.t[i.p]=b,i=i._next;if(g.autoRotate&&(g.autoRotate.rotation=h.rotation),1===a||0===a)for(i=g.firstMPT,f=1===a?"e":"b";i;){if(c=i.t,c.type){if(1===c.type){for(e=c.xs0+c.s+c.xs1,d=1;d<c.l;d++)e+=c["xn"+d]+c["xs"+(d+1)];c[f]=e}}else c[f]=c.s+c.xs0;i=i._next}},function(a,b,c,d,e){this.t=a,this.p=b,this.v=c,this.r=e,d&&(d._prev=this,this._next=d)}),qa=(P._parseToProxy=function(a,b,c,d,e,f){var g,h,i,j,k,l=d,m={},n={},o=c._transform,p=K;for(c._transform=null,K=b,d=k=c.parse(a,b,d,e),K=p,f&&(c._transform=o,l&&(l._prev=null,l._prev&&(l._prev._next=null)));d&&d!==l;){if(d.type<=1&&(h=d.p,n[h]=d.s+d.c,m[h]=d.s,f||(j=new pa(d,"s",h,j,d.r),d.c=0),1===d.type))for(g=d.l;--g>0;)i="xn"+g,h=d.p+"_"+i,n[h]=d.data[i],m[h]=d[i],f||(j=new pa(d,i,h,j,d.rxp[i]));d=d._next}return{proxy:m,end:n,firstMPT:j,pt:k}},P.CSSPropTween=function(a,b,d,e,g,h,i,j,k,l,m){this.t=a,this.p=b,this.s=d,this.c=e,this.n=i||b,a instanceof qa||f.push(this.n),this.r=j,this.type=h||0,k&&(this.pr=k,c=!0),this.b=void 0===l?d:l,this.e=void 0===m?d+e:m,g&&(this._next=g,g._prev=this)}),ra=function(a,b,c,d,e,f){var g=new qa(a,b,c,d-c,e,-1,f);return g.b=c,g.e=g.xs0=d,g},sa=g.parseComplex=function(a,b,c,d,e,f,h,i,j,l){c=c||f||"",h=new qa(a,b,0,0,h,l?2:1,null,!1,i,c,d),d+="",e&&ma.test(d+c)&&(d=[c,d],g.colorStringFilter(d),c=d[0],d=d[1]);var m,n,o,p,s,t,u,v,w,x,y,z,A,B=c.split(", ").join(",").split(" "),C=d.split(", ").join(",").split(" "),D=B.length,E=k!==!1;for((-1!==d.indexOf(",")||-1!==c.indexOf(","))&&(B=B.join(" ").replace(G,", ").split(" "),C=C.join(" ").replace(G,", ").split(" "),D=B.length),D!==C.length&&(B=(f||"").split(" "),D=B.length),h.plugin=j,h.setRatio=l,ma.lastIndex=0,m=0;D>m;m++)if(p=B[m],s=C[m],v=parseFloat(p),v||0===v)h.appendXtra("",v,fa(s,v),s.replace(r,""),E&&-1!==s.indexOf("px"),!0);else if(e&&ma.test(p))z=s.indexOf(")")+1,z=")"+(z?s.substr(z):""),A=-1!==s.indexOf("hsl")&&R,p=ka(p,A),s=ka(s,A),w=p.length+s.length>6,w&&!R&&0===s[3]?(h["xs"+h.l]+=h.l?" transparent":"transparent",h.e=h.e.split(C[m]).join("transparent")):(R||(w=!1),A?h.appendXtra(w?"hsla(":"hsl(",p[0],fa(s[0],p[0]),",",!1,!0).appendXtra("",p[1],fa(s[1],p[1]),"%,",!1).appendXtra("",p[2],fa(s[2],p[2]),w?"%,":"%"+z,!1):h.appendXtra(w?"rgba(":"rgb(",p[0],s[0]-p[0],",",!0,!0).appendXtra("",p[1],s[1]-p[1],",",!0).appendXtra("",p[2],s[2]-p[2],w?",":z,!0),w&&(p=p.length<4?1:p[3],h.appendXtra("",p,(s.length<4?1:s[3])-p,z,!1))),ma.lastIndex=0;else if(t=p.match(q)){if(u=s.match(r),!u||u.length!==t.length)return h;for(o=0,n=0;n<t.length;n++)y=t[n],x=p.indexOf(y,o),h.appendXtra(p.substr(o,x-o),Number(y),fa(u[n],y),"",E&&"px"===p.substr(x+y.length,2),0===n),o=x+y.length;h["xs"+h.l]+=p.substr(o)}else h["xs"+h.l]+=h.l||h["xs"+h.l]?" "+s:s;if(-1!==d.indexOf("=")&&h.data){for(z=h.xs0+h.data.s,m=1;m<h.l;m++)z+=h["xs"+m]+h.data["xn"+m];h.e=z+h["xs"+m]}return h.l||(h.type=-1,h.xs0=h.e),h.xfirst||h},ta=9;for(j=qa.prototype,j.l=j.pr=0;--ta>0;)j["xn"+ta]=0,j["xs"+ta]="";j.xs0="",j._next=j._prev=j.xfirst=j.data=j.plugin=j.setRatio=j.rxp=null,j.appendXtra=function(a,b,c,d,e,f){var g=this,h=g.l;return g["xs"+h]+=f&&(h||g["xs"+h])?" "+a:a||"",c||0===h||g.plugin?(g.l++,g.type=g.setRatio?2:1,g["xs"+g.l]=d||"",h>0?(g.data["xn"+h]=b+c,g.rxp["xn"+h]=e,g["xn"+h]=b,g.plugin||(g.xfirst=new qa(g,"xn"+h,b,c,g.xfirst||g,0,g.n,e,g.pr),g.xfirst.xs0=0),g):(g.data={s:b+c},g.rxp={},g.s=b,g.c=c,g.r=e,g)):(g["xs"+h]+=b+(d||""),g)};var ua=function(a,b){b=b||{},this.p=b.prefix?W(a)||a:a,i[a]=i[this.p]=this,this.format=b.formatter||na(b.defaultValue,b.color,b.collapsible,b.multi),b.parser&&(this.parse=b.parser),this.clrs=b.color,this.multi=b.multi,this.keyword=b.keyword,this.dflt=b.defaultValue,this.pr=b.priority||0},va=P._registerComplexSpecialProp=function(a,b,c){"object"!=typeof b&&(b={parser:c});var d,e,f=a.split(","),g=b.defaultValue;for(c=c||[g],d=0;d<f.length;d++)b.prefix=0===d&&b.prefix,b.defaultValue=c[d]||g,e=new ua(f[d],b)},wa=function(a){if(!i[a]){var b=a.charAt(0).toUpperCase()+a.substr(1)+"Plugin";va(a,{parser:function(a,c,d,e,f,g,j){var k=h.com.greensock.plugins[b];return k?(k._cssRegister(),i[d].parse(a,c,d,e,f,g,j)):(T("Error: "+b+" js file not loaded."),f)}})}};j=ua.prototype,j.parseComplex=function(a,b,c,d,e,f){var g,h,i,j,k,l,m=this.keyword;if(this.multi&&(G.test(c)||G.test(b)?(h=b.replace(G,"|").split("|"),i=c.replace(G,"|").split("|")):m&&(h=[b],i=[c])),i){for(j=i.length>h.length?i.length:h.length,g=0;j>g;g++)b=h[g]=h[g]||this.dflt,c=i[g]=i[g]||this.dflt,m&&(k=b.indexOf(m),l=c.indexOf(m),k!==l&&(-1===l?h[g]=h[g].split(m).join(""):-1===k&&(h[g]+=" "+m)));b=h.join(", "),c=i.join(", ")}return sa(a,this.p,b,c,this.clrs,this.dflt,d,this.pr,e,f)},j.parse=function(a,b,c,d,f,g,h){return this.parseComplex(a.style,this.format(Y(a,this.p,e,!1,this.dflt)),this.format(b),f,g)},g.registerSpecialProp=function(a,b,c){va(a,{parser:function(a,d,e,f,g,h,i){var j=new qa(a,e,0,0,g,2,e,!1,c);return j.plugin=h,j.setRatio=b(a,d,f._tween,e),j},priority:c})},g.useSVGTransformAttr=m||n;var xa,ya="scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent".split(","),za=W("transform"),Aa=U+"transform",Ba=W("transformOrigin"),Ca=null!==W("perspective"),Da=P.Transform=function(){this.perspective=parseFloat(g.defaultTransformPerspective)||0,this.force3D=g.defaultForce3D!==!1&&Ca?g.defaultForce3D||"auto":!1},Ea=window.SVGElement,Fa=function(a,b,c){var d,e=L.createElementNS("http://www.w3.org/2000/svg",a),f=/([a-z])([A-Z])/g;for(d in c)e.setAttributeNS(null,d.replace(f,"$1-$2").toLowerCase(),c[d]);return b.appendChild(e),e},Ga=L.documentElement,Ha=function(){var a,b,c,d=p||/Android/i.test(Q)&&!window.chrome;return L.createElementNS&&!d&&(a=Fa("svg",Ga),b=Fa("rect",a,{width:100,height:50,x:100}),c=b.getBoundingClientRect().width,b.style[Ba]="50% 50%",b.style[za]="scaleX(0.5)",d=c===b.getBoundingClientRect().width&&!(n&&Ca),Ga.removeChild(a)),d}(),Ia=function(a,b,c,d,e,f){var h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=a._gsTransform,w=Ma(a,!0);v&&(t=v.xOrigin,u=v.yOrigin),(!d||(h=d.split(" ")).length<2)&&(n=a.getBBox(),b=ea(b).split(" "),h=[(-1!==b[0].indexOf("%")?parseFloat(b[0])/100*n.width:parseFloat(b[0]))+n.x,(-1!==b[1].indexOf("%")?parseFloat(b[1])/100*n.height:parseFloat(b[1]))+n.y]),c.xOrigin=k=parseFloat(h[0]),c.yOrigin=l=parseFloat(h[1]),d&&w!==La&&(m=w[0],n=w[1],o=w[2],p=w[3],q=w[4],r=w[5],s=m*p-n*o,i=k*(p/s)+l*(-o/s)+(o*r-p*q)/s,j=k*(-n/s)+l*(m/s)-(m*r-n*q)/s,k=c.xOrigin=h[0]=i,l=c.yOrigin=h[1]=j),v&&(f&&(c.xOffset=v.xOffset,c.yOffset=v.yOffset,v=c),e||e!==!1&&g.defaultSmoothOrigin!==!1?(i=k-t,j=l-u,v.xOffset+=i*w[0]+j*w[2]-i,v.yOffset+=i*w[1]+j*w[3]-j):v.xOffset=v.yOffset=0),f||a.setAttribute("data-svg-origin",h.join(" "))},Ja=function(a){try{return a.getBBox()}catch(a){}},Ka=function(a){return!!(Ea&&a.getBBox&&a.getCTM&&Ja(a)&&(!a.parentNode||a.parentNode.getBBox&&a.parentNode.getCTM))},La=[1,0,0,1,0,0],Ma=function(a,b){var c,d,e,f,g,h,i=a._gsTransform||new Da,j=1e5,k=a.style;if(za?d=Y(a,Aa,null,!0):a.currentStyle&&(d=a.currentStyle.filter.match(E),d=d&&4===d.length?[d[0].substr(4),Number(d[2].substr(4)),Number(d[1].substr(4)),d[3].substr(4),i.x||0,i.y||0].join(","):""),c=!d||"none"===d||"matrix(1, 0, 0, 1, 0, 0)"===d,c&&za&&((h="none"===X(a).display)||!a.parentNode)&&(h&&(f=k.display,k.display="block"),a.parentNode||(g=1,Ga.appendChild(a)),d=Y(a,Aa,null,!0),c=!d||"none"===d||"matrix(1, 0, 0, 1, 0, 0)"===d,f?k.display=f:h&&Ra(k,"display"),g&&Ga.removeChild(a)),(i.svg||a.getBBox&&Ka(a))&&(c&&-1!==(k[za]+"").indexOf("matrix")&&(d=k[za],c=0),e=a.getAttribute("transform"),c&&e&&(-1!==e.indexOf("matrix")?(d=e,c=0):-1!==e.indexOf("translate")&&(d="matrix(1,0,0,1,"+e.match(/(?:\-|\b)[\d\-\.e]+\b/gi).join(",")+")",c=0))),c)return La;for(e=(d||"").match(q)||[],ta=e.length;--ta>-1;)f=Number(e[ta]),e[ta]=(g=f-(f|=0))?(g*j+(0>g?-.5:.5)|0)/j+f:f;return b&&e.length>6?[e[0],e[1],e[4],e[5],e[12],e[13]]:e},Na=P.getTransform=function(a,c,d,e){if(a._gsTransform&&d&&!e)return a._gsTransform;var f,h,i,j,k,l,m=d?a._gsTransform||new Da:new Da,n=m.scaleX<0,o=2e-5,p=1e5,q=Ca?parseFloat(Y(a,Ba,c,!1,"0 0 0").split(" ")[2])||m.zOrigin||0:0,r=parseFloat(g.defaultTransformPerspective)||0;if(m.svg=!(!a.getBBox||!Ka(a)),m.svg&&(Ia(a,Y(a,Ba,c,!1,"50% 50%")+"",m,a.getAttribute("data-svg-origin")),xa=g.useSVGTransformAttr||Ha),f=Ma(a),f!==La){if(16===f.length){var s,t,u,v,w,x=f[0],y=f[1],z=f[2],A=f[3],B=f[4],C=f[5],D=f[6],E=f[7],F=f[8],G=f[9],H=f[10],I=f[12],K=f[13],L=f[14],M=f[11],N=Math.atan2(D,H);m.zOrigin&&(L=-m.zOrigin,I=F*L-f[12],K=G*L-f[13],L=H*L+m.zOrigin-f[14]),m.rotationX=N*J,N&&(v=Math.cos(-N),w=Math.sin(-N),s=B*v+F*w,t=C*v+G*w,u=D*v+H*w,F=B*-w+F*v,G=C*-w+G*v,H=D*-w+H*v,M=E*-w+M*v,B=s,C=t,D=u),N=Math.atan2(-z,H),m.rotationY=N*J,N&&(v=Math.cos(-N),w=Math.sin(-N),s=x*v-F*w,t=y*v-G*w,u=z*v-H*w,G=y*w+G*v,H=z*w+H*v,M=A*w+M*v,x=s,y=t,z=u),N=Math.atan2(y,x),m.rotation=N*J,N&&(v=Math.cos(-N),w=Math.sin(-N),x=x*v+B*w,t=y*v+C*w,C=y*-w+C*v,D=z*-w+D*v,y=t),m.rotationX&&Math.abs(m.rotationX)+Math.abs(m.rotation)>359.9&&(m.rotationX=m.rotation=0,m.rotationY=180-m.rotationY),m.scaleX=(Math.sqrt(x*x+y*y)*p+.5|0)/p,m.scaleY=(Math.sqrt(C*C+G*G)*p+.5|0)/p,m.scaleZ=(Math.sqrt(D*D+H*H)*p+.5|0)/p,m.rotationX||m.rotationY?m.skewX=0:(m.skewX=B||C?Math.atan2(B,C)*J+m.rotation:m.skewX||0,Math.abs(m.skewX)>90&&Math.abs(m.skewX)<270&&(n?(m.scaleX*=-1,m.skewX+=m.rotation<=0?180:-180,m.rotation+=m.rotation<=0?180:-180):(m.scaleY*=-1,m.skewX+=m.skewX<=0?180:-180))),m.perspective=M?1/(0>M?-M:M):0,m.x=I,m.y=K,m.z=L,m.svg&&(m.x-=m.xOrigin-(m.xOrigin*x-m.yOrigin*B),m.y-=m.yOrigin-(m.yOrigin*y-m.xOrigin*C))}else if(!Ca||e||!f.length||m.x!==f[4]||m.y!==f[5]||!m.rotationX&&!m.rotationY){var O=f.length>=6,P=O?f[0]:1,Q=f[1]||0,R=f[2]||0,S=O?f[3]:1;m.x=f[4]||0,m.y=f[5]||0,i=Math.sqrt(P*P+Q*Q),j=Math.sqrt(S*S+R*R),k=P||Q?Math.atan2(Q,P)*J:m.rotation||0,l=R||S?Math.atan2(R,S)*J+k:m.skewX||0,Math.abs(l)>90&&Math.abs(l)<270&&(n?(i*=-1,l+=0>=k?180:-180,k+=0>=k?180:-180):(j*=-1,l+=0>=l?180:-180)),m.scaleX=i,m.scaleY=j,m.rotation=k,m.skewX=l,Ca&&(m.rotationX=m.rotationY=m.z=0,m.perspective=r,m.scaleZ=1),m.svg&&(m.x-=m.xOrigin-(m.xOrigin*P+m.yOrigin*R),m.y-=m.yOrigin-(m.xOrigin*Q+m.yOrigin*S))}m.zOrigin=q;for(h in m)m[h]<o&&m[h]>-o&&(m[h]=0)}return d&&(a._gsTransform=m,m.svg&&(xa&&a.style[za]?b.delayedCall(.001,function(){Ra(a.style,za)}):!xa&&a.getAttribute("transform")&&b.delayedCall(.001,function(){a.removeAttribute("transform")}))),m},Oa=function(a){var b,c,d=this.data,e=-d.rotation*I,f=e+d.skewX*I,g=1e5,h=(Math.cos(e)*d.scaleX*g|0)/g,i=(Math.sin(e)*d.scaleX*g|0)/g,j=(Math.sin(f)*-d.scaleY*g|0)/g,k=(Math.cos(f)*d.scaleY*g|0)/g,l=this.t.style,m=this.t.currentStyle;if(m){c=i,i=-j,j=-c,b=m.filter,l.filter="";var n,o,q=this.t.offsetWidth,r=this.t.offsetHeight,s="absolute"!==m.position,t="progid:DXImageTransform.Microsoft.Matrix(M11="+h+", M12="+i+", M21="+j+", M22="+k,w=d.x+q*d.xPercent/100,x=d.y+r*d.yPercent/100;if(null!=d.ox&&(n=(d.oxp?q*d.ox*.01:d.ox)-q/2,o=(d.oyp?r*d.oy*.01:d.oy)-r/2,w+=n-(n*h+o*i),x+=o-(n*j+o*k)),s?(n=q/2,o=r/2,t+=", Dx="+(n-(n*h+o*i)+w)+", Dy="+(o-(n*j+o*k)+x)+")"):t+=", sizingMethod='auto expand')",-1!==b.indexOf("DXImageTransform.Microsoft.Matrix(")?l.filter=b.replace(F,t):l.filter=t+" "+b,(0===a||1===a)&&1===h&&0===i&&0===j&&1===k&&(s&&-1===t.indexOf("Dx=0, Dy=0")||v.test(b)&&100!==parseFloat(RegExp.$1)||-1===b.indexOf(b.indexOf("Alpha"))&&l.removeAttribute("filter")),!s){var y,z,A,B=8>p?1:-1;for(n=d.ieOffsetX||0,o=d.ieOffsetY||0,d.ieOffsetX=Math.round((q-((0>h?-h:h)*q+(0>i?-i:i)*r))/2+w),d.ieOffsetY=Math.round((r-((0>k?-k:k)*r+(0>j?-j:j)*q))/2+x),ta=0;4>ta;ta++)z=ca[ta],y=m[z],c=-1!==y.indexOf("px")?parseFloat(y):Z(this.t,z,parseFloat(y),y.replace(u,""))||0,A=c!==d[z]?2>ta?-d.ieOffsetX:-d.ieOffsetY:2>ta?n-d.ieOffsetX:o-d.ieOffsetY,l[z]=(d[z]=Math.round(c-A*(0===ta||2===ta?1:B)))+"px"}}},Pa=P.set3DTransformRatio=P.setTransformRatio=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,o,p,q,r,s,t,u,v,w,x,y,z=this.data,A=this.t.style,B=z.rotation,C=z.rotationX,D=z.rotationY,E=z.scaleX,F=z.scaleY,G=z.scaleZ,H=z.x,J=z.y,K=z.z,L=z.svg,M=z.perspective,N=z.force3D;if(((1===a||0===a)&&"auto"===N&&(this.tween._totalTime===this.tween._totalDuration||!this.tween._totalTime)||!N)&&!K&&!M&&!D&&!C&&1===G||xa&&L||!Ca)return void(B||z.skewX||L?(B*=I,x=z.skewX*I,y=1e5,b=Math.cos(B)*E,e=Math.sin(B)*E,c=Math.sin(B-x)*-F,f=Math.cos(B-x)*F,x&&"simple"===z.skewType&&(s=Math.tan(x),s=Math.sqrt(1+s*s),c*=s,f*=s,z.skewY&&(b*=s,e*=s)),L&&(H+=z.xOrigin-(z.xOrigin*b+z.yOrigin*c)+z.xOffset,J+=z.yOrigin-(z.xOrigin*e+z.yOrigin*f)+z.yOffset,xa&&(z.xPercent||z.yPercent)&&(p=this.t.getBBox(),H+=.01*z.xPercent*p.width,J+=.01*z.yPercent*p.height),p=1e-6,p>H&&H>-p&&(H=0),p>J&&J>-p&&(J=0)),u=(b*y|0)/y+","+(e*y|0)/y+","+(c*y|0)/y+","+(f*y|0)/y+","+H+","+J+")",L&&xa?this.t.setAttribute("transform","matrix("+u):A[za]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix(":"matrix(")+u):A[za]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix(":"matrix(")+E+",0,0,"+F+","+H+","+J+")");if(n&&(p=1e-4,p>E&&E>-p&&(E=G=2e-5),p>F&&F>-p&&(F=G=2e-5),!M||z.z||z.rotationX||z.rotationY||(M=0)),B||z.skewX)B*=I,q=b=Math.cos(B),r=e=Math.sin(B),z.skewX&&(B-=z.skewX*I,q=Math.cos(B),r=Math.sin(B),"simple"===z.skewType&&(s=Math.tan(z.skewX*I),s=Math.sqrt(1+s*s),q*=s,r*=s,z.skewY&&(b*=s,e*=s))),c=-r,f=q;else{if(!(D||C||1!==G||M||L))return void(A[za]=(z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) translate3d(":"translate3d(")+H+"px,"+J+"px,"+K+"px)"+(1!==E||1!==F?" scale("+E+","+F+")":""));b=f=1,c=e=0}j=1,d=g=h=i=k=l=0,m=M?-1/M:0,o=z.zOrigin,p=1e-6,v=",",w="0",B=D*I,B&&(q=Math.cos(B),r=Math.sin(B),h=-r,k=m*-r,d=b*r,g=e*r,j=q,m*=q,b*=q,e*=q),B=C*I,B&&(q=Math.cos(B),r=Math.sin(B),s=c*q+d*r,t=f*q+g*r,i=j*r,l=m*r,d=c*-r+d*q,g=f*-r+g*q,j*=q,m*=q,c=s,f=t),1!==G&&(d*=G,g*=G,j*=G,m*=G),1!==F&&(c*=F,f*=F,i*=F,l*=F),1!==E&&(b*=E,e*=E,h*=E,k*=E),(o||L)&&(o&&(H+=d*-o,J+=g*-o,K+=j*-o+o),L&&(H+=z.xOrigin-(z.xOrigin*b+z.yOrigin*c)+z.xOffset,J+=z.yOrigin-(z.xOrigin*e+z.yOrigin*f)+z.yOffset),p>H&&H>-p&&(H=w),p>J&&J>-p&&(J=w),p>K&&K>-p&&(K=0)),u=z.xPercent||z.yPercent?"translate("+z.xPercent+"%,"+z.yPercent+"%) matrix3d(":"matrix3d(",u+=(p>b&&b>-p?w:b)+v+(p>e&&e>-p?w:e)+v+(p>h&&h>-p?w:h),u+=v+(p>k&&k>-p?w:k)+v+(p>c&&c>-p?w:c)+v+(p>f&&f>-p?w:f),C||D||1!==G?(u+=v+(p>i&&i>-p?w:i)+v+(p>l&&l>-p?w:l)+v+(p>d&&d>-p?w:d),u+=v+(p>g&&g>-p?w:g)+v+(p>j&&j>-p?w:j)+v+(p>m&&m>-p?w:m)+v):u+=",0,0,0,0,1,0,",u+=H+v+J+v+K+v+(M?1+-K/M:1)+")",A[za]=u};j=Da.prototype,j.x=j.y=j.z=j.skewX=j.skewY=j.rotation=j.rotationX=j.rotationY=j.zOrigin=j.xPercent=j.yPercent=j.xOffset=j.yOffset=0,j.scaleX=j.scaleY=j.scaleZ=1,va("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,svgOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent,smoothOrigin",{parser:function(a,b,c,d,f,h,i){if(d._lastParsedTransform===i)return f;d._lastParsedTransform=i;var j,k,l,m,n,o,p,q,r,s=a._gsTransform,t=a.style,u=1e-6,v=ya.length,w=i,x={},y="transformOrigin",z=Na(a,e,!0,i.parseTransform);if(d._transform=z,"string"==typeof w.transform&&za)k=N.style,k[za]=w.transform,k.display="block",k.position="absolute",L.body.appendChild(N),j=Na(N,null,!1),z.svg&&(p=z.xOrigin,q=z.yOrigin,j.x-=z.xOffset,j.y-=z.yOffset,(w.transformOrigin||w.svgOrigin)&&(l={},Ia(a,ea(w.transformOrigin),l,w.svgOrigin,w.smoothOrigin,!0),p=l.xOrigin,q=l.yOrigin,j.x-=l.xOffset-z.xOffset,j.y-=l.yOffset-z.yOffset),(p||q)&&(r=Ma(N,!0),j.x-=p-(p*r[0]+q*r[2]),j.y-=q-(p*r[1]+q*r[3]))),L.body.removeChild(N),j.perspective||(j.perspective=z.perspective),null!=w.xPercent&&(j.xPercent=ga(w.xPercent,z.xPercent)),null!=w.yPercent&&(j.yPercent=ga(w.yPercent,z.yPercent));else if("object"==typeof w){if(j={scaleX:ga(null!=w.scaleX?w.scaleX:w.scale,z.scaleX),scaleY:ga(null!=w.scaleY?w.scaleY:w.scale,z.scaleY),scaleZ:ga(w.scaleZ,z.scaleZ),x:ga(w.x,z.x),y:ga(w.y,z.y),z:ga(w.z,z.z),xPercent:ga(w.xPercent,z.xPercent),yPercent:ga(w.yPercent,z.yPercent),perspective:ga(w.transformPerspective,z.perspective)},o=w.directionalRotation,null!=o)if("object"==typeof o)for(k in o)w[k]=o[k];else w.rotation=o;"string"==typeof w.x&&-1!==w.x.indexOf("%")&&(j.x=0,j.xPercent=ga(w.x,z.xPercent)),"string"==typeof w.y&&-1!==w.y.indexOf("%")&&(j.y=0,j.yPercent=ga(w.y,z.yPercent)),j.rotation=ha("rotation"in w?w.rotation:"shortRotation"in w?w.shortRotation+"_short":"rotationZ"in w?w.rotationZ:z.rotation-z.skewY,z.rotation-z.skewY,"rotation",x),Ca&&(j.rotationX=ha("rotationX"in w?w.rotationX:"shortRotationX"in w?w.shortRotationX+"_short":z.rotationX||0,z.rotationX,"rotationX",x),j.rotationY=ha("rotationY"in w?w.rotationY:"shortRotationY"in w?w.shortRotationY+"_short":z.rotationY||0,z.rotationY,"rotationY",x)),j.skewX=ha(w.skewX,z.skewX-z.skewY),(j.skewY=ha(w.skewY,z.skewY))&&(j.skewX+=j.skewY,j.rotation+=j.skewY)}for(Ca&&null!=w.force3D&&(z.force3D=w.force3D,n=!0),z.skewType=w.skewType||z.skewType||g.defaultSkewType,m=z.force3D||z.z||z.rotationX||z.rotationY||j.z||j.rotationX||j.rotationY||j.perspective,m||null==w.scale||(j.scaleZ=1);--v>-1;)c=ya[v],l=j[c]-z[c],(l>u||-u>l||null!=w[c]||null!=K[c])&&(n=!0,f=new qa(z,c,z[c],l,f),c in x&&(f.e=x[c]),f.xs0=0,f.plugin=h,d._overwriteProps.push(f.n));return l=w.transformOrigin,z.svg&&(l||w.svgOrigin)&&(p=z.xOffset,q=z.yOffset,Ia(a,ea(l),j,w.svgOrigin,w.smoothOrigin),f=ra(z,"xOrigin",(s?z:j).xOrigin,j.xOrigin,f,y),f=ra(z,"yOrigin",(s?z:j).yOrigin,j.yOrigin,f,y),(p!==z.xOffset||q!==z.yOffset)&&(f=ra(z,"xOffset",s?p:z.xOffset,z.xOffset,f,y),f=ra(z,"yOffset",s?q:z.yOffset,z.yOffset,f,y)),l=xa?null:"0px 0px"),(l||Ca&&m&&z.zOrigin)&&(za?(n=!0,c=Ba,l=(l||Y(a,c,e,!1,"50% 50%"))+"",f=new qa(t,c,0,0,f,-1,y),f.b=t[c],f.plugin=h,Ca?(k=z.zOrigin,l=l.split(" "),z.zOrigin=(l.length>2&&(0===k||"0px"!==l[2])?parseFloat(l[2]):k)||0, f.xs0=f.e=l[0]+" "+(l[1]||"50%")+" 0px",f=new qa(z,"zOrigin",0,0,f,-1,f.n),f.b=k,f.xs0=f.e=z.zOrigin):f.xs0=f.e=l):ea(l+"",z)),n&&(d._transformType=z.svg&&xa||!m&&3!==this._transformType?2:3),f},prefix:!0}),va("boxShadow",{defaultValue:"0px 0px 0px 0px #999",prefix:!0,color:!0,multi:!0,keyword:"inset"}),va("borderRadius",{defaultValue:"0px",parser:function(a,b,c,f,g,h){b=this.format(b);var i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],z=a.style;for(q=parseFloat(a.offsetWidth),r=parseFloat(a.offsetHeight),i=b.split(" "),j=0;j<y.length;j++)this.p.indexOf("border")&&(y[j]=W(y[j])),m=l=Y(a,y[j],e,!1,"0px"),-1!==m.indexOf(" ")&&(l=m.split(" "),m=l[0],l=l[1]),n=k=i[j],o=parseFloat(m),t=m.substr((o+"").length),u="="===n.charAt(1),u?(p=parseInt(n.charAt(0)+"1",10),n=n.substr(2),p*=parseFloat(n),s=n.substr((p+"").length-(0>p?1:0))||""):(p=parseFloat(n),s=n.substr((p+"").length)),""===s&&(s=d[c]||t),s!==t&&(v=Z(a,"borderLeft",o,t),w=Z(a,"borderTop",o,t),"%"===s?(m=v/q*100+"%",l=w/r*100+"%"):"em"===s?(x=Z(a,"borderLeft",1,"em"),m=v/x+"em",l=w/x+"em"):(m=v+"px",l=w+"px"),u&&(n=parseFloat(m)+p+s,k=parseFloat(l)+p+s)),g=sa(z,y[j],m+" "+l,n+" "+k,!1,"0px",g);return g},prefix:!0,formatter:na("0px 0px 0px 0px",!1,!0)}),va("borderBottomLeftRadius,borderBottomRightRadius,borderTopLeftRadius,borderTopRightRadius",{defaultValue:"0px",parser:function(a,b,c,d,f,g){return sa(a.style,c,this.format(Y(a,c,e,!1,"0px 0px")),this.format(b),!1,"0px",f)},prefix:!0,formatter:na("0px 0px",!1,!0)}),va("backgroundPosition",{defaultValue:"0 0",parser:function(a,b,c,d,f,g){var h,i,j,k,l,m,n="background-position",o=e||X(a,null),q=this.format((o?p?o.getPropertyValue(n+"-x")+" "+o.getPropertyValue(n+"-y"):o.getPropertyValue(n):a.currentStyle.backgroundPositionX+" "+a.currentStyle.backgroundPositionY)||"0 0"),r=this.format(b);if(-1!==q.indexOf("%")!=(-1!==r.indexOf("%"))&&r.split(",").length<2&&(m=Y(a,"backgroundImage").replace(B,""),m&&"none"!==m)){for(h=q.split(" "),i=r.split(" "),O.setAttribute("src",m),j=2;--j>-1;)q=h[j],k=-1!==q.indexOf("%"),k!==(-1!==i[j].indexOf("%"))&&(l=0===j?a.offsetWidth-O.width:a.offsetHeight-O.height,h[j]=k?parseFloat(q)/100*l+"px":parseFloat(q)/l*100+"%");q=h.join(" ")}return this.parseComplex(a.style,q,r,f,g)},formatter:ea}),va("backgroundSize",{defaultValue:"0 0",formatter:ea}),va("perspective",{defaultValue:"0px",prefix:!0}),va("perspectiveOrigin",{defaultValue:"50% 50%",prefix:!0}),va("transformStyle",{prefix:!0}),va("backfaceVisibility",{prefix:!0}),va("userSelect",{prefix:!0}),va("margin",{parser:oa("marginTop,marginRight,marginBottom,marginLeft")}),va("padding",{parser:oa("paddingTop,paddingRight,paddingBottom,paddingLeft")}),va("clip",{defaultValue:"rect(0px,0px,0px,0px)",parser:function(a,b,c,d,f,g){var h,i,j;return 9>p?(i=a.currentStyle,j=8>p?" ":",",h="rect("+i.clipTop+j+i.clipRight+j+i.clipBottom+j+i.clipLeft+")",b=this.format(b).split(",").join(j)):(h=this.format(Y(a,this.p,e,!1,this.dflt)),b=this.format(b)),this.parseComplex(a.style,h,b,f,g)}}),va("textShadow",{defaultValue:"0px 0px 0px #999",color:!0,multi:!0}),va("autoRound,strictUnits",{parser:function(a,b,c,d,e){return e}}),va("border",{defaultValue:"0px solid #000",parser:function(a,b,c,d,f,g){var h=Y(a,"borderTopWidth",e,!1,"0px"),i=this.format(b).split(" "),j=i[0].replace(u,"");return"px"!==j&&(h=parseFloat(h)/Z(a,"borderTopWidth",1,j)+j),this.parseComplex(a.style,this.format(h+" "+Y(a,"borderTopStyle",e,!1,"solid")+" "+Y(a,"borderTopColor",e,!1,"#000")),i.join(" "),f,g)},color:!0,formatter:function(a){var b=a.split(" ");return b[0]+" "+(b[1]||"solid")+" "+(a.match(ma)||["#000"])[0]}}),va("borderWidth",{parser:oa("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}),va("float,cssFloat,styleFloat",{parser:function(a,b,c,d,e,f){var g=a.style,h="cssFloat"in g?"cssFloat":"styleFloat";return new qa(g,h,0,0,e,-1,c,!1,0,g[h],b)}});var Qa=function(a){var b,c=this.t,d=c.filter||Y(this.data,"filter")||"",e=this.s+this.c*a|0;100===e&&(-1===d.indexOf("atrix(")&&-1===d.indexOf("radient(")&&-1===d.indexOf("oader(")?(c.removeAttribute("filter"),b=!Y(this.data,"filter")):(c.filter=d.replace(x,""),b=!0)),b||(this.xn1&&(c.filter=d=d||"alpha(opacity="+e+")"),-1===d.indexOf("pacity")?0===e&&this.xn1||(c.filter=d+" alpha(opacity="+e+")"):c.filter=d.replace(v,"opacity="+e))};va("opacity,alpha,autoAlpha",{defaultValue:"1",parser:function(a,b,c,d,f,g){var h=parseFloat(Y(a,"opacity",e,!1,"1")),i=a.style,j="autoAlpha"===c;return"string"==typeof b&&"="===b.charAt(1)&&(b=("-"===b.charAt(0)?-1:1)*parseFloat(b.substr(2))+h),j&&1===h&&"hidden"===Y(a,"visibility",e)&&0!==b&&(h=0),R?f=new qa(i,"opacity",h,b-h,f):(f=new qa(i,"opacity",100*h,100*(b-h),f),f.xn1=j?1:0,i.zoom=1,f.type=2,f.b="alpha(opacity="+f.s+")",f.e="alpha(opacity="+(f.s+f.c)+")",f.data=a,f.plugin=g,f.setRatio=Qa),j&&(f=new qa(i,"visibility",0,0,f,-1,null,!1,0,0!==h?"inherit":"hidden",0===b?"hidden":"inherit"),f.xs0="inherit",d._overwriteProps.push(f.n),d._overwriteProps.push(c)),f}});var Ra=function(a,b){b&&(a.removeProperty?(("ms"===b.substr(0,2)||"webkit"===b.substr(0,6))&&(b="-"+b),a.removeProperty(b.replace(z,"-$1").toLowerCase())):a.removeAttribute(b))},Sa=function(a){if(this.t._gsClassPT=this,1===a||0===a){this.t.setAttribute("class",0===a?this.b:this.e);for(var b=this.data,c=this.t.style;b;)b.v?c[b.p]=b.v:Ra(c,b.p),b=b._next;1===a&&this.t._gsClassPT===this&&(this.t._gsClassPT=null)}else this.t.getAttribute("class")!==this.e&&this.t.setAttribute("class",this.e)};va("className",{parser:function(a,b,d,f,g,h,i){var j,k,l,m,n,o=a.getAttribute("class")||"",p=a.style.cssText;if(g=f._classNamePT=new qa(a,d,0,0,g,2),g.setRatio=Sa,g.pr=-11,c=!0,g.b=o,k=_(a,e),l=a._gsClassPT){for(m={},n=l.data;n;)m[n.p]=1,n=n._next;l.setRatio(1)}return a._gsClassPT=g,g.e="="!==b.charAt(1)?b:o.replace(new RegExp("(?:\\s|^)"+b.substr(2)+"(?![\\w-])"),"")+("+"===b.charAt(0)?" "+b.substr(2):""),a.setAttribute("class",g.e),j=aa(a,k,_(a),i,m),a.setAttribute("class",o),g.data=j.firstMPT,a.style.cssText=p,g=g.xfirst=f.parse(a,j.difs,g,h)}});var Ta=function(a){if((1===a||0===a)&&this.data._totalTime===this.data._totalDuration&&"isFromStart"!==this.data.data){var b,c,d,e,f,g=this.t.style,h=i.transform.parse;if("all"===this.e)g.cssText="",e=!0;else for(b=this.e.split(" ").join("").split(","),d=b.length;--d>-1;)c=b[d],i[c]&&(i[c].parse===h?e=!0:c="transformOrigin"===c?Ba:i[c].p),Ra(g,c);e&&(Ra(g,za),f=this.t._gsTransform,f&&(f.svg&&(this.t.removeAttribute("data-svg-origin"),this.t.removeAttribute("transform")),delete this.t._gsTransform))}};for(va("clearProps",{parser:function(a,b,d,e,f){return f=new qa(a,d,0,0,f,2),f.setRatio=Ta,f.e=b,f.pr=-10,f.data=e._tween,c=!0,f}}),j="bezier,throwProps,physicsProps,physics2D".split(","),ta=j.length;ta--;)wa(j[ta]);j=g.prototype,j._firstPT=j._lastParsedTransform=j._transform=null,j._onInitTween=function(a,b,h){if(!a.nodeType)return!1;this._target=a,this._tween=h,this._vars=b,k=b.autoRound,c=!1,d=b.suffixMap||g.suffixMap,e=X(a,""),f=this._overwriteProps;var j,n,p,q,r,s,t,u,v,x=a.style;if(l&&""===x.zIndex&&(j=Y(a,"zIndex",e),("auto"===j||""===j)&&this._addLazySet(x,"zIndex",0)),"string"==typeof b&&(q=x.cssText,j=_(a,e),x.cssText=q+";"+b,j=aa(a,j,_(a)).difs,!R&&w.test(b)&&(j.opacity=parseFloat(RegExp.$1)),b=j,x.cssText=q),b.className?this._firstPT=n=i.className.parse(a,b.className,"className",this,null,null,b):this._firstPT=n=this.parse(a,b,null),this._transformType){for(v=3===this._transformType,za?m&&(l=!0,""===x.zIndex&&(t=Y(a,"zIndex",e),("auto"===t||""===t)&&this._addLazySet(x,"zIndex",0)),o&&this._addLazySet(x,"WebkitBackfaceVisibility",this._vars.WebkitBackfaceVisibility||(v?"visible":"hidden"))):x.zoom=1,p=n;p&&p._next;)p=p._next;u=new qa(a,"transform",0,0,null,2),this._linkCSSP(u,null,p),u.setRatio=za?Pa:Oa,u.data=this._transform||Na(a,e,!0),u.tween=h,u.pr=-1,f.pop()}if(c){for(;n;){for(s=n._next,p=q;p&&p.pr>n.pr;)p=p._next;(n._prev=p?p._prev:r)?n._prev._next=n:q=n,(n._next=p)?p._prev=n:r=n,n=s}this._firstPT=q}return!0},j.parse=function(a,b,c,f){var g,h,j,l,m,n,o,p,q,r,s=a.style;for(g in b)n=b[g],h=i[g],h?c=h.parse(a,n,g,this,c,f,b):(m=Y(a,g,e)+"",q="string"==typeof n,"color"===g||"fill"===g||"stroke"===g||-1!==g.indexOf("Color")||q&&y.test(n)?(q||(n=ka(n),n=(n.length>3?"rgba(":"rgb(")+n.join(",")+")"),c=sa(s,g,m,n,!0,"transparent",c,0,f)):q&&H.test(n)?c=sa(s,g,m,n,!0,null,c,0,f):(j=parseFloat(m),o=j||0===j?m.substr((j+"").length):"",(""===m||"auto"===m)&&("width"===g||"height"===g?(j=da(a,g,e),o="px"):"left"===g||"top"===g?(j=$(a,g,e),o="px"):(j="opacity"!==g?0:1,o="")),r=q&&"="===n.charAt(1),r?(l=parseInt(n.charAt(0)+"1",10),n=n.substr(2),l*=parseFloat(n),p=n.replace(u,"")):(l=parseFloat(n),p=q?n.replace(u,""):""),""===p&&(p=g in d?d[g]:o),n=l||0===l?(r?l+j:l)+p:b[g],o!==p&&""!==p&&(l||0===l)&&j&&(j=Z(a,g,j,o),"%"===p?(j/=Z(a,g,100,"%")/100,b.strictUnits!==!0&&(m=j+"%")):"em"===p||"rem"===p||"vw"===p||"vh"===p?j/=Z(a,g,1,p):"px"!==p&&(l=Z(a,g,l,p),p="px"),r&&(l||0===l)&&(n=l+j+p)),r&&(l+=j),!j&&0!==j||!l&&0!==l?void 0!==s[g]&&(n||n+""!="NaN"&&null!=n)?(c=new qa(s,g,l||j||0,0,c,-1,g,!1,0,m,n),c.xs0="none"!==n||"display"!==g&&-1===g.indexOf("Style")?n:m):T("invalid "+g+" tween value: "+b[g]):(c=new qa(s,g,j,l-j,c,0,g,k!==!1&&("px"===p||"zIndex"===g),0,m,n),c.xs0=p))),f&&c&&!c.plugin&&(c.plugin=f);return c},j.setRatio=function(a){var b,c,d,e=this._firstPT,f=1e-6;if(1!==a||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(a||this._tween._time!==this._tween._duration&&0!==this._tween._time||this._tween._rawPrevTime===-1e-6)for(;e;){if(b=e.c*a+e.s,e.r?b=Math.round(b):f>b&&b>-f&&(b=0),e.type)if(1===e.type)if(d=e.l,2===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2;else if(3===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3;else if(4===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3+e.xn3+e.xs4;else if(5===d)e.t[e.p]=e.xs0+b+e.xs1+e.xn1+e.xs2+e.xn2+e.xs3+e.xn3+e.xs4+e.xn4+e.xs5;else{for(c=e.xs0+b+e.xs1,d=1;d<e.l;d++)c+=e["xn"+d]+e["xs"+(d+1)];e.t[e.p]=c}else-1===e.type?e.t[e.p]=e.xs0:e.setRatio&&e.setRatio(a);else e.t[e.p]=b+e.xs0;e=e._next}else for(;e;)2!==e.type?e.t[e.p]=e.b:e.setRatio(a),e=e._next;else for(;e;){if(2!==e.type)if(e.r&&-1!==e.type)if(b=Math.round(e.s+e.c),e.type){if(1===e.type){for(d=e.l,c=e.xs0+b+e.xs1,d=1;d<e.l;d++)c+=e["xn"+d]+e["xs"+(d+1)];e.t[e.p]=c}}else e.t[e.p]=b+e.xs0;else e.t[e.p]=e.e;else e.setRatio(a);e=e._next}},j._enableTransforms=function(a){this._transform=this._transform||Na(this._target,e,!0),this._transformType=this._transform.svg&&xa||!a&&3!==this._transformType?2:3};var Ua=function(a){this.t[this.p]=this.e,this.data._linkCSSP(this,this._next,null,!0)};j._addLazySet=function(a,b,c){var d=this._firstPT=new qa(a,b,0,0,this._firstPT,2);d.e=c,d.setRatio=Ua,d.data=this},j._linkCSSP=function(a,b,c,d){return a&&(b&&(b._prev=a),a._next&&(a._next._prev=a._prev),a._prev?a._prev._next=a._next:this._firstPT===a&&(this._firstPT=a._next,d=!0),c?c._next=a:d||null!==this._firstPT||(this._firstPT=a),a._next=b,a._prev=c),a},j._kill=function(b){var c,d,e,f=b;if(b.autoAlpha||b.alpha){f={};for(d in b)f[d]=b[d];f.opacity=1,f.autoAlpha&&(f.visibility=1)}return b.className&&(c=this._classNamePT)&&(e=c.xfirst,e&&e._prev?this._linkCSSP(e._prev,c._next,e._prev._prev):e===this._firstPT&&(this._firstPT=c._next),c._next&&this._linkCSSP(c._next,c._next._next,e._prev),this._classNamePT=null),a.prototype._kill.call(this,f)};var Va=function(a,b,c){var d,e,f,g;if(a.slice)for(e=a.length;--e>-1;)Va(a[e],b,c);else for(d=a.childNodes,e=d.length;--e>-1;)f=d[e],g=f.type,f.style&&(b.push(_(f)),c&&c.push(f)),1!==g&&9!==g&&11!==g||!f.childNodes.length||Va(f,b,c)};return g.cascadeTo=function(a,c,d){var e,f,g,h,i=b.to(a,c,d),j=[i],k=[],l=[],m=[],n=b._internals.reservedProps;for(a=i._targets||i.target,Va(a,k,m),i.render(c,!0,!0),Va(a,l),i.render(0,!0,!0),i._enabled(!0),e=m.length;--e>-1;)if(f=aa(m[e],k[e],l[e]),f.firstMPT){f=f.difs;for(g in d)n[g]&&(f[g]=d[g]);h={};for(g in f)h[g]=k[e][g];j.push(b.fromTo(m[e],c,h,f))}return j},a.activate([g]),g},!0),function(){var a=_gsScope._gsDefine.plugin({propName:"roundProps",version:"1.5",priority:-1,API:2,init:function(a,b,c){return this._tween=c,!0}}),b=function(a){for(;a;)a.f||a.blob||(a.r=1),a=a._next},c=a.prototype;c._onInitAllProps=function(){for(var a,c,d,e=this._tween,f=e.vars.roundProps.join?e.vars.roundProps:e.vars.roundProps.split(","),g=f.length,h={},i=e._propLookup.roundProps;--g>-1;)h[f[g]]=1;for(g=f.length;--g>-1;)for(a=f[g],c=e._firstPT;c;)d=c._next,c.pg?c.t._roundProps(h,!0):c.n===a&&(2===c.f&&c.t?b(c.t._firstPT):(this._add(c.t,a,c.s,c.c),d&&(d._prev=c._prev),c._prev?c._prev._next=d:e._firstPT===c&&(e._firstPT=d),c._next=c._prev=null,e._propLookup[a]=i)),c=d;return!1},c._add=function(a,b,c,d){this._addTween(a,b,c,c+d,b,!0),this._overwriteProps.push(b)}}(),function(){_gsScope._gsDefine.plugin({propName:"attr",API:2,version:"0.5.0",init:function(a,b,c){var d;if("function"!=typeof a.setAttribute)return!1;for(d in b)this._addTween(a,"setAttribute",a.getAttribute(d)+"",b[d]+"",d,!1,d),this._overwriteProps.push(d);return!0}})}(),_gsScope._gsDefine.plugin({propName:"directionalRotation",version:"0.2.1",API:2,init:function(a,b,c){"object"!=typeof b&&(b={rotation:b}),this.finals={};var d,e,f,g,h,i,j=b.useRadians===!0?2*Math.PI:360,k=1e-6;for(d in b)"useRadians"!==d&&(i=(b[d]+"").split("_"),e=i[0],f=parseFloat("function"!=typeof a[d]?a[d]:a[d.indexOf("set")||"function"!=typeof a["get"+d.substr(3)]?d:"get"+d.substr(3)]()),g=this.finals[d]="string"==typeof e&&"="===e.charAt(1)?f+parseInt(e.charAt(0)+"1",10)*Number(e.substr(2)):Number(e)||0,h=g-f,i.length&&(e=i.join("_"),-1!==e.indexOf("short")&&(h%=j,h!==h%(j/2)&&(h=0>h?h+j:h-j)),-1!==e.indexOf("_cw")&&0>h?h=(h+9999999999*j)%j-(h/j|0)*j:-1!==e.indexOf("ccw")&&h>0&&(h=(h-9999999999*j)%j-(h/j|0)*j)),(h>k||-k>h)&&(this._addTween(a,d,f,f+h,d),this._overwriteProps.push(d)));return!0},set:function(a){var b;if(1!==a)this._super.setRatio.call(this,a);else for(b=this._firstPT;b;)b.f?b.t[b.p](this.finals[b.p]):b.t[b.p]=this.finals[b.p],b=b._next}})._autoCSS=!0,_gsScope._gsDefine("easing.Back",["easing.Ease"],function(a){var b,c,d,e=_gsScope.GreenSockGlobals||_gsScope,f=e.com.greensock,g=2*Math.PI,h=Math.PI/2,i=f._class,j=function(b,c){var d=i("easing."+b,function(){},!0),e=d.prototype=new a;return e.constructor=d,e.getRatio=c,d},k=a.register||function(){},l=function(a,b,c,d,e){var f=i("easing."+a,{easeOut:new b,easeIn:new c,easeInOut:new d},!0);return k(f,a),f},m=function(a,b,c){this.t=a,this.v=b,c&&(this.next=c,c.prev=this,this.c=c.v-b,this.gap=c.t-a)},n=function(b,c){var d=i("easing."+b,function(a){this._p1=a||0===a?a:1.70158,this._p2=1.525*this._p1},!0),e=d.prototype=new a;return e.constructor=d,e.getRatio=c,e.config=function(a){return new d(a)},d},o=l("Back",n("BackOut",function(a){return(a-=1)*a*((this._p1+1)*a+this._p1)+1}),n("BackIn",function(a){return a*a*((this._p1+1)*a-this._p1)}),n("BackInOut",function(a){return(a*=2)<1?.5*a*a*((this._p2+1)*a-this._p2):.5*((a-=2)*a*((this._p2+1)*a+this._p2)+2)})),p=i("easing.SlowMo",function(a,b,c){b=b||0===b?b:.7,null==a?a=.7:a>1&&(a=1),this._p=1!==a?b:0,this._p1=(1-a)/2,this._p2=a,this._p3=this._p1+this._p2,this._calcEnd=c===!0},!0),q=p.prototype=new a;return q.constructor=p,q.getRatio=function(a){var b=a+(.5-a)*this._p;return a<this._p1?this._calcEnd?1-(a=1-a/this._p1)*a:b-(a=1-a/this._p1)*a*a*a*b:a>this._p3?this._calcEnd?1-(a=(a-this._p3)/this._p1)*a:b+(a-b)*(a=(a-this._p3)/this._p1)*a*a*a:this._calcEnd?1:b},p.ease=new p(.7,.7),q.config=p.config=function(a,b,c){return new p(a,b,c)},b=i("easing.SteppedEase",function(a){a=a||1,this._p1=1/a,this._p2=a+1},!0),q=b.prototype=new a,q.constructor=b,q.getRatio=function(a){return 0>a?a=0:a>=1&&(a=.999999999),(this._p2*a>>0)*this._p1},q.config=b.config=function(a){return new b(a)},c=i("easing.RoughEase",function(b){b=b||{};for(var c,d,e,f,g,h,i=b.taper||"none",j=[],k=0,l=0|(b.points||20),n=l,o=b.randomize!==!1,p=b.clamp===!0,q=b.template instanceof a?b.template:null,r="number"==typeof b.strength?.4*b.strength:.4;--n>-1;)c=o?Math.random():1/l*n,d=q?q.getRatio(c):c,"none"===i?e=r:"out"===i?(f=1-c,e=f*f*r):"in"===i?e=c*c*r:.5>c?(f=2*c,e=f*f*.5*r):(f=2*(1-c),e=f*f*.5*r),o?d+=Math.random()*e-.5*e:n%2?d+=.5*e:d-=.5*e,p&&(d>1?d=1:0>d&&(d=0)),j[k++]={x:c,y:d};for(j.sort(function(a,b){return a.x-b.x}),h=new m(1,1,null),n=l;--n>-1;)g=j[n],h=new m(g.x,g.y,h);this._prev=new m(0,0,0!==h.t?h:h.next)},!0),q=c.prototype=new a,q.constructor=c,q.getRatio=function(a){var b=this._prev;if(a>b.t){for(;b.next&&a>=b.t;)b=b.next;b=b.prev}else for(;b.prev&&a<=b.t;)b=b.prev;return this._prev=b,b.v+(a-b.t)/b.gap*b.c},q.config=function(a){return new c(a)},c.ease=new c,l("Bounce",j("BounceOut",function(a){return 1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375}),j("BounceIn",function(a){return(a=1-a)<1/2.75?1-7.5625*a*a:2/2.75>a?1-(7.5625*(a-=1.5/2.75)*a+.75):2.5/2.75>a?1-(7.5625*(a-=2.25/2.75)*a+.9375):1-(7.5625*(a-=2.625/2.75)*a+.984375)}),j("BounceInOut",function(a){var b=.5>a;return a=b?1-2*a:2*a-1,a=1/2.75>a?7.5625*a*a:2/2.75>a?7.5625*(a-=1.5/2.75)*a+.75:2.5/2.75>a?7.5625*(a-=2.25/2.75)*a+.9375:7.5625*(a-=2.625/2.75)*a+.984375,b?.5*(1-a):.5*a+.5})),l("Circ",j("CircOut",function(a){return Math.sqrt(1-(a-=1)*a)}),j("CircIn",function(a){return-(Math.sqrt(1-a*a)-1)}),j("CircInOut",function(a){return(a*=2)<1?-.5*(Math.sqrt(1-a*a)-1):.5*(Math.sqrt(1-(a-=2)*a)+1)})),d=function(b,c,d){var e=i("easing."+b,function(a,b){this._p1=a>=1?a:1,this._p2=(b||d)/(1>a?a:1),this._p3=this._p2/g*(Math.asin(1/this._p1)||0),this._p2=g/this._p2},!0),f=e.prototype=new a;return f.constructor=e,f.getRatio=c,f.config=function(a,b){return new e(a,b)},e},l("Elastic",d("ElasticOut",function(a){return this._p1*Math.pow(2,-10*a)*Math.sin((a-this._p3)*this._p2)+1},.3),d("ElasticIn",function(a){return-(this._p1*Math.pow(2,10*(a-=1))*Math.sin((a-this._p3)*this._p2))},.3),d("ElasticInOut",function(a){return(a*=2)<1?-.5*(this._p1*Math.pow(2,10*(a-=1))*Math.sin((a-this._p3)*this._p2)):this._p1*Math.pow(2,-10*(a-=1))*Math.sin((a-this._p3)*this._p2)*.5+1},.45)),l("Expo",j("ExpoOut",function(a){return 1-Math.pow(2,-10*a)}),j("ExpoIn",function(a){return Math.pow(2,10*(a-1))-.001}),j("ExpoInOut",function(a){return(a*=2)<1?.5*Math.pow(2,10*(a-1)):.5*(2-Math.pow(2,-10*(a-1)))})),l("Sine",j("SineOut",function(a){return Math.sin(a*h)}),j("SineIn",function(a){return-Math.cos(a*h)+1}),j("SineInOut",function(a){return-.5*(Math.cos(Math.PI*a)-1)})),i("easing.EaseLookup",{find:function(b){return a.map[b]}},!0),k(e.SlowMo,"SlowMo","ease,"),k(c,"RoughEase","ease,"),k(b,"SteppedEase","ease,"),o},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(a,b){"use strict";var c={},d=a.GreenSockGlobals=a.GreenSockGlobals||a;if(!d.TweenLite){var e,f,g,h,i,j=function(a){var b,c=a.split("."),e=d;for(b=0;b<c.length;b++)e[c[b]]=e=e[c[b]]||{};return e},k=j("com.greensock"),l=1e-10,m=function(a){var b,c=[],d=a.length;for(b=0;b!==d;c.push(a[b++]));return c},n=function(){},o=function(){var a=Object.prototype.toString,b=a.call([]);return function(c){return null!=c&&(c instanceof Array||"object"==typeof c&&!!c.push&&a.call(c)===b)}}(),p={},q=function(e,f,g,h){this.sc=p[e]?p[e].sc:[],p[e]=this,this.gsClass=null,this.func=g;var i=[];this.check=function(k){for(var l,m,n,o,r,s=f.length,t=s;--s>-1;)(l=p[f[s]]||new q(f[s],[])).gsClass?(i[s]=l.gsClass,t--):k&&l.sc.push(this);if(0===t&&g){if(m=("com.greensock."+e).split("."),n=m.pop(),o=j(m.join("."))[n]=this.gsClass=g.apply(g,i),h)if(d[n]=o,r="undefined"!=typeof module&&module.exports,!r&&"function"==typeof define&&define.amd)define((a.GreenSockAMDPath?a.GreenSockAMDPath+"/":"")+e.split(".").pop(),[],function(){return o});else if(r)if(e===b){module.exports=c[b]=o;for(s in c)o[s]=c[s]}else c[b]&&(c[b][n]=o);for(s=0;s<this.sc.length;s++)this.sc[s].check()}},this.check(!0)},r=a._gsDefine=function(a,b,c,d){return new q(a,b,c,d)},s=k._class=function(a,b,c){return b=b||function(){},r(a,[],function(){return b},c),b};r.globals=d;var t=[0,0,1,1],u=[],v=s("easing.Ease",function(a,b,c,d){this._func=a,this._type=c||0,this._power=d||0,this._params=b?t.concat(b):t},!0),w=v.map={},x=v.register=function(a,b,c,d){for(var e,f,g,h,i=b.split(","),j=i.length,l=(c||"easeIn,easeOut,easeInOut").split(",");--j>-1;)for(f=i[j],e=d?s("easing."+f,null,!0):k.easing[f]||{},g=l.length;--g>-1;)h=l[g],w[f+"."+h]=w[h+f]=e[h]=a.getRatio?a:a[h]||new a};for(g=v.prototype,g._calcEnd=!1,g.getRatio=function(a){if(this._func)return this._params[0]=a,this._func.apply(null,this._params);var b=this._type,c=this._power,d=1===b?1-a:2===b?a:.5>a?2*a:2*(1-a);return 1===c?d*=d:2===c?d*=d*d:3===c?d*=d*d*d:4===c&&(d*=d*d*d*d),1===b?1-d:2===b?d:.5>a?d/2:1-d/2},e=["Linear","Quad","Cubic","Quart","Quint,Strong"],f=e.length;--f>-1;)g=e[f]+",Power"+f,x(new v(null,null,1,f),g,"easeOut",!0),x(new v(null,null,2,f),g,"easeIn"+(0===f?",easeNone":"")),x(new v(null,null,3,f),g,"easeInOut");w.linear=k.easing.Linear.easeIn,w.swing=k.easing.Quad.easeInOut;var y=s("events.EventDispatcher",function(a){this._listeners={},this._eventTarget=a||this});g=y.prototype,g.addEventListener=function(a,b,c,d,e){e=e||0;var f,g,j=this._listeners[a],k=0;for(this!==h||i||h.wake(),null==j&&(this._listeners[a]=j=[]),g=j.length;--g>-1;)f=j[g],f.c===b&&f.s===c?j.splice(g,1):0===k&&f.pr<e&&(k=g+1);j.splice(k,0,{c:b,s:c,up:d,pr:e})},g.removeEventListener=function(a,b){var c,d=this._listeners[a];if(d)for(c=d.length;--c>-1;)if(d[c].c===b)return void d.splice(c,1)},g.dispatchEvent=function(a){var b,c,d,e=this._listeners[a];if(e)for(b=e.length,c=this._eventTarget;--b>-1;)d=e[b],d&&(d.up?d.c.call(d.s||c,{type:a,target:c}):d.c.call(d.s||c))};var z=a.requestAnimationFrame,A=a.cancelAnimationFrame,B=Date.now||function(){return(new Date).getTime()},C=B();for(e=["ms","moz","webkit","o"],f=e.length;--f>-1&&!z;)z=a[e[f]+"RequestAnimationFrame"],A=a[e[f]+"CancelAnimationFrame"]||a[e[f]+"CancelRequestAnimationFrame"];s("Ticker",function(a,b){var c,d,e,f,g,j=this,k=B(),m=b!==!1&&z?"auto":!1,o=500,p=33,q="tick",r=function(a){var b,h,i=B()-C;i>o&&(k+=i-p),C+=i,j.time=(C-k)/1e3,b=j.time-g,(!c||b>0||a===!0)&&(j.frame++,g+=b+(b>=f?.004:f-b),h=!0),a!==!0&&(e=d(r)),h&&j.dispatchEvent(q)};y.call(j),j.time=j.frame=0,j.tick=function(){r(!0)},j.lagSmoothing=function(a,b){o=a||1/l,p=Math.min(b,o,0)},j.sleep=function(){null!=e&&(m&&A?A(e):clearTimeout(e),d=n,e=null,j===h&&(i=!1))},j.wake=function(a){null!==e?j.sleep():a?k+=-C+(C=B()):j.frame>10&&(C=B()-o+5),d=0===c?n:m&&z?z:function(a){return setTimeout(a,1e3*(g-j.time)+1|0)},j===h&&(i=!0),r(2)},j.fps=function(a){return arguments.length?(c=a,f=1/(c||60),g=this.time+f,void j.wake()):c},j.useRAF=function(a){return arguments.length?(j.sleep(),m=a,void j.fps(c)):m},j.fps(a),setTimeout(function(){"auto"===m&&j.frame<5&&"hidden"!==document.visibilityState&&j.useRAF(!1)},1500)}),g=k.Ticker.prototype=new k.events.EventDispatcher,g.constructor=k.Ticker;var D=s("core.Animation",function(a,b){if(this.vars=b=b||{},this._duration=this._totalDuration=a||0,this._delay=Number(b.delay)||0,this._timeScale=1,this._active=b.immediateRender===!0,this.data=b.data,this._reversed=b.reversed===!0,W){i||h.wake();var c=this.vars.useFrames?V:W;c.add(this,c._time),this.vars.paused&&this.paused(!0)}});h=D.ticker=new k.Ticker,g=D.prototype,g._dirty=g._gc=g._initted=g._paused=!1,g._totalTime=g._time=0,g._rawPrevTime=-1,g._next=g._last=g._onUpdate=g._timeline=g.timeline=null,g._paused=!1;var E=function(){i&&B()-C>2e3&&h.wake(),setTimeout(E,2e3)};E(),g.play=function(a,b){return null!=a&&this.seek(a,b),this.reversed(!1).paused(!1)},g.pause=function(a,b){return null!=a&&this.seek(a,b),this.paused(!0)},g.resume=function(a,b){return null!=a&&this.seek(a,b),this.paused(!1)},g.seek=function(a,b){return this.totalTime(Number(a),b!==!1)},g.restart=function(a,b){return this.reversed(!1).paused(!1).totalTime(a?-this._delay:0,b!==!1,!0)},g.reverse=function(a,b){return null!=a&&this.seek(a||this.totalDuration(),b),this.reversed(!0).paused(!1)},g.render=function(a,b,c){},g.invalidate=function(){return this._time=this._totalTime=0,this._initted=this._gc=!1,this._rawPrevTime=-1,(this._gc||!this.timeline)&&this._enabled(!0),this},g.isActive=function(){var a,b=this._timeline,c=this._startTime;return!b||!this._gc&&!this._paused&&b.isActive()&&(a=b.rawTime())>=c&&a<c+this.totalDuration()/this._timeScale},g._enabled=function(a,b){return i||h.wake(),this._gc=!a,this._active=this.isActive(),b!==!0&&(a&&!this.timeline?this._timeline.add(this,this._startTime-this._delay):!a&&this.timeline&&this._timeline._remove(this,!0)),!1},g._kill=function(a,b){return this._enabled(!1,!1)},g.kill=function(a,b){return this._kill(a,b),this},g._uncache=function(a){for(var b=a?this:this.timeline;b;)b._dirty=!0,b=b.timeline;return this},g._swapSelfInParams=function(a){for(var b=a.length,c=a.concat();--b>-1;)"{self}"===a[b]&&(c[b]=this);return c},g._callback=function(a){var b=this.vars;b[a].apply(b[a+"Scope"]||b.callbackScope||this,b[a+"Params"]||u)},g.eventCallback=function(a,b,c,d){if("on"===(a||"").substr(0,2)){var e=this.vars;if(1===arguments.length)return e[a];null==b?delete e[a]:(e[a]=b,e[a+"Params"]=o(c)&&-1!==c.join("").indexOf("{self}")?this._swapSelfInParams(c):c,e[a+"Scope"]=d),"onUpdate"===a&&(this._onUpdate=b)}return this},g.delay=function(a){return arguments.length?(this._timeline.smoothChildTiming&&this.startTime(this._startTime+a-this._delay),this._delay=a,this):this._delay},g.duration=function(a){return arguments.length?(this._duration=this._totalDuration=a,this._uncache(!0),this._timeline.smoothChildTiming&&this._time>0&&this._time<this._duration&&0!==a&&this.totalTime(this._totalTime*(a/this._duration),!0),this):(this._dirty=!1,this._duration)},g.totalDuration=function(a){return this._dirty=!1,arguments.length?this.duration(a):this._totalDuration},g.time=function(a,b){return arguments.length?(this._dirty&&this.totalDuration(),this.totalTime(a>this._duration?this._duration:a,b)):this._time},g.totalTime=function(a,b,c){if(i||h.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(0>a&&!c&&(a+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var d=this._totalDuration,e=this._timeline;if(a>d&&!c&&(a=d),this._startTime=(this._paused?this._pauseTime:e._time)-(this._reversed?d-a:a)/this._timeScale,e._dirty||this._uncache(!1),e._timeline)for(;e._timeline;)e._timeline._time!==(e._startTime+e._totalTime)/e._timeScale&&e.totalTime(e._totalTime,!0),e=e._timeline}this._gc&&this._enabled(!0,!1),(this._totalTime!==a||0===this._duration)&&(J.length&&Y(),this.render(a,b,!1),J.length&&Y())}return this},g.progress=g.totalProgress=function(a,b){var c=this.duration();return arguments.length?this.totalTime(c*a,b):c?this._time/c:this.ratio},g.startTime=function(a){return arguments.length?(a!==this._startTime&&(this._startTime=a,this.timeline&&this.timeline._sortChildren&&this.timeline.add(this,a-this._delay)),this):this._startTime},g.endTime=function(a){return this._startTime+(0!=a?this.totalDuration():this.duration())/this._timeScale},g.timeScale=function(a){if(!arguments.length)return this._timeScale;if(a=a||l,this._timeline&&this._timeline.smoothChildTiming){var b=this._pauseTime,c=b||0===b?b:this._timeline.totalTime();this._startTime=c-(c-this._startTime)*this._timeScale/a}return this._timeScale=a,this._uncache(!1)},g.reversed=function(a){return arguments.length?(a!=this._reversed&&(this._reversed=a,this.totalTime(this._timeline&&!this._timeline.smoothChildTiming?this.totalDuration()-this._totalTime:this._totalTime,!0)),this):this._reversed},g.paused=function(a){if(!arguments.length)return this._paused;var b,c,d=this._timeline;return a!=this._paused&&d&&(i||a||h.wake(),b=d.rawTime(),c=b-this._pauseTime,!a&&d.smoothChildTiming&&(this._startTime+=c,this._uncache(!1)),this._pauseTime=a?b:null,this._paused=a,this._active=this.isActive(),!a&&0!==c&&this._initted&&this.duration()&&(b=d.smoothChildTiming?this._totalTime:(b-this._startTime)/this._timeScale,this.render(b,b===this._totalTime,!0))),this._gc&&!a&&this._enabled(!0,!1),this};var F=s("core.SimpleTimeline",function(a){D.call(this,0,a),this.autoRemoveChildren=this.smoothChildTiming=!0});g=F.prototype=new D,g.constructor=F,g.kill()._gc=!1,g._first=g._last=g._recent=null,g._sortChildren=!1,g.add=g.insert=function(a,b,c,d){var e,f;if(a._startTime=Number(b||0)+a._delay,a._paused&&this!==a._timeline&&(a._pauseTime=a._startTime+(this.rawTime()-a._startTime)/a._timeScale),a.timeline&&a.timeline._remove(a,!0),a.timeline=a._timeline=this,a._gc&&a._enabled(!0,!0),e=this._last,this._sortChildren)for(f=a._startTime;e&&e._startTime>f;)e=e._prev;return e?(a._next=e._next,e._next=a):(a._next=this._first,this._first=a),a._next?a._next._prev=a:this._last=a,a._prev=e,this._recent=a,this._timeline&&this._uncache(!0),this},g._remove=function(a,b){return a.timeline===this&&(b||a._enabled(!1,!0),a._prev?a._prev._next=a._next:this._first===a&&(this._first=a._next),a._next?a._next._prev=a._prev:this._last===a&&(this._last=a._prev),a._next=a._prev=a.timeline=null,a===this._recent&&(this._recent=this._last),this._timeline&&this._uncache(!0)),this},g.render=function(a,b,c){var d,e=this._first;for(this._totalTime=this._time=this._rawPrevTime=a;e;)d=e._next,(e._active||a>=e._startTime&&!e._paused)&&(e._reversed?e.render((e._dirty?e.totalDuration():e._totalDuration)-(a-e._startTime)*e._timeScale,b,c):e.render((a-e._startTime)*e._timeScale,b,c)),e=d},g.rawTime=function(){return i||h.wake(),this._totalTime};var G=s("TweenLite",function(b,c,d){if(D.call(this,c,d),this.render=G.prototype.render,null==b)throw"Cannot tween a null target.";this.target=b="string"!=typeof b?b:G.selector(b)||b;var e,f,g,h=b.jquery||b.length&&b!==a&&b[0]&&(b[0]===a||b[0].nodeType&&b[0].style&&!b.nodeType),i=this.vars.overwrite;if(this._overwrite=i=null==i?U[G.defaultOverwrite]:"number"==typeof i?i>>0:U[i],(h||b instanceof Array||b.push&&o(b))&&"number"!=typeof b[0])for(this._targets=g=m(b),this._propLookup=[],this._siblings=[],e=0;e<g.length;e++)f=g[e],f?"string"!=typeof f?f.length&&f!==a&&f[0]&&(f[0]===a||f[0].nodeType&&f[0].style&&!f.nodeType)?(g.splice(e--,1),this._targets=g=g.concat(m(f))):(this._siblings[e]=Z(f,this,!1),1===i&&this._siblings[e].length>1&&_(f,this,null,1,this._siblings[e])):(f=g[e--]=G.selector(f),"string"==typeof f&&g.splice(e+1,1)):g.splice(e--,1);else this._propLookup={},this._siblings=Z(b,this,!1),1===i&&this._siblings.length>1&&_(b,this,null,1,this._siblings);(this.vars.immediateRender||0===c&&0===this._delay&&this.vars.immediateRender!==!1)&&(this._time=-l,this.render(Math.min(0,-this._delay)))},!0),H=function(b){return b&&b.length&&b!==a&&b[0]&&(b[0]===a||b[0].nodeType&&b[0].style&&!b.nodeType)},I=function(a,b){var c,d={};for(c in a)T[c]||c in b&&"transform"!==c&&"x"!==c&&"y"!==c&&"width"!==c&&"height"!==c&&"className"!==c&&"border"!==c||!(!Q[c]||Q[c]&&Q[c]._autoCSS)||(d[c]=a[c],delete a[c]);a.css=d};g=G.prototype=new D,g.constructor=G,g.kill()._gc=!1,g.ratio=0,g._firstPT=g._targets=g._overwrittenProps=g._startAt=null,g._notifyPluginsOfEnabled=g._lazy=!1,G.version="1.18.5",G.defaultEase=g._ease=new v(null,null,1,1),G.defaultOverwrite="auto",G.ticker=h,G.autoSleep=120,G.lagSmoothing=function(a,b){h.lagSmoothing(a,b)},G.selector=a.$||a.jQuery||function(b){var c=a.$||a.jQuery;return c?(G.selector=c,c(b)):"undefined"==typeof document?b:document.querySelectorAll?document.querySelectorAll(b):document.getElementById("#"===b.charAt(0)?b.substr(1):b)};var J=[],K={},L=/(?:(-|-=|\+=)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/gi,M=function(a){for(var b,c=this._firstPT,d=1e-6;c;)b=c.blob?a?this.join(""):this.start:c.c*a+c.s,c.r?b=Math.round(b):d>b&&b>-d&&(b=0),c.f?c.fp?c.t[c.p](c.fp,b):c.t[c.p](b):c.t[c.p]=b,c=c._next},N=function(a,b,c,d){var e,f,g,h,i,j,k,l=[a,b],m=0,n="",o=0;for(l.start=a,c&&(c(l),a=l[0],b=l[1]),l.length=0,e=a.match(L)||[],f=b.match(L)||[],d&&(d._next=null, d.blob=1,l._firstPT=d),i=f.length,h=0;i>h;h++)k=f[h],j=b.substr(m,b.indexOf(k,m)-m),n+=j||!h?j:",",m+=j.length,o?o=(o+1)%5:"rgba("===j.substr(-5)&&(o=1),k===e[h]||e.length<=h?n+=k:(n&&(l.push(n),n=""),g=parseFloat(e[h]),l.push(g),l._firstPT={_next:l._firstPT,t:l,p:l.length-1,s:g,c:("="===k.charAt(1)?parseInt(k.charAt(0)+"1",10)*parseFloat(k.substr(2)):parseFloat(k)-g)||0,f:0,r:o&&4>o}),m+=k.length;return n+=b.substr(m),n&&l.push(n),l.setRatio=M,l},O=function(a,b,c,d,e,f,g,h){var i,j,k="get"===c?a[b]:c,l=typeof a[b],m="string"==typeof d&&"="===d.charAt(1),n={t:a,p:b,s:k,f:"function"===l,pg:0,n:e||b,r:f,pr:0,c:m?parseInt(d.charAt(0)+"1",10)*parseFloat(d.substr(2)):parseFloat(d)-k||0};return"number"!==l&&("function"===l&&"get"===c&&(j=b.indexOf("set")||"function"!=typeof a["get"+b.substr(3)]?b:"get"+b.substr(3),n.s=k=g?a[j](g):a[j]()),"string"==typeof k&&(g||isNaN(k))?(n.fp=g,i=N(k,d,h||G.defaultStringFilter,n),n={t:i,p:"setRatio",s:0,c:1,f:2,pg:0,n:e||b,pr:0}):m||(n.s=parseFloat(k),n.c=parseFloat(d)-n.s||0)),n.c?((n._next=this._firstPT)&&(n._next._prev=n),this._firstPT=n,n):void 0},P=G._internals={isArray:o,isSelector:H,lazyTweens:J,blobDif:N},Q=G._plugins={},R=P.tweenLookup={},S=0,T=P.reservedProps={ease:1,delay:1,overwrite:1,onComplete:1,onCompleteParams:1,onCompleteScope:1,useFrames:1,runBackwards:1,startAt:1,onUpdate:1,onUpdateParams:1,onUpdateScope:1,onStart:1,onStartParams:1,onStartScope:1,onReverseComplete:1,onReverseCompleteParams:1,onReverseCompleteScope:1,onRepeat:1,onRepeatParams:1,onRepeatScope:1,easeParams:1,yoyo:1,immediateRender:1,repeat:1,repeatDelay:1,data:1,paused:1,reversed:1,autoCSS:1,lazy:1,onOverwrite:1,callbackScope:1,stringFilter:1,id:1},U={none:0,all:1,auto:2,concurrent:3,allOnStart:4,preexisting:5,"true":1,"false":0},V=D._rootFramesTimeline=new F,W=D._rootTimeline=new F,X=30,Y=P.lazyRender=function(){var a,b=J.length;for(K={};--b>-1;)a=J[b],a&&a._lazy!==!1&&(a.render(a._lazy[0],a._lazy[1],!0),a._lazy=!1);J.length=0};W._startTime=h.time,V._startTime=h.frame,W._active=V._active=!0,setTimeout(Y,1),D._updateRoot=G.render=function(){var a,b,c;if(J.length&&Y(),W.render((h.time-W._startTime)*W._timeScale,!1,!1),V.render((h.frame-V._startTime)*V._timeScale,!1,!1),J.length&&Y(),h.frame>=X){X=h.frame+(parseInt(G.autoSleep,10)||120);for(c in R){for(b=R[c].tweens,a=b.length;--a>-1;)b[a]._gc&&b.splice(a,1);0===b.length&&delete R[c]}if(c=W._first,(!c||c._paused)&&G.autoSleep&&!V._first&&1===h._listeners.tick.length){for(;c&&c._paused;)c=c._next;c||h.sleep()}}},h.addEventListener("tick",D._updateRoot);var Z=function(a,b,c){var d,e,f=a._gsTweenID;if(R[f||(a._gsTweenID=f="t"+S++)]||(R[f]={target:a,tweens:[]}),b&&(d=R[f].tweens,d[e=d.length]=b,c))for(;--e>-1;)d[e]===b&&d.splice(e,1);return R[f].tweens},$=function(a,b,c,d){var e,f,g=a.vars.onOverwrite;return g&&(e=g(a,b,c,d)),g=G.onOverwrite,g&&(f=g(a,b,c,d)),e!==!1&&f!==!1},_=function(a,b,c,d,e){var f,g,h,i;if(1===d||d>=4){for(i=e.length,f=0;i>f;f++)if((h=e[f])!==b)h._gc||h._kill(null,a,b)&&(g=!0);else if(5===d)break;return g}var j,k=b._startTime+l,m=[],n=0,o=0===b._duration;for(f=e.length;--f>-1;)(h=e[f])===b||h._gc||h._paused||(h._timeline!==b._timeline?(j=j||aa(b,0,o),0===aa(h,j,o)&&(m[n++]=h)):h._startTime<=k&&h._startTime+h.totalDuration()/h._timeScale>k&&((o||!h._initted)&&k-h._startTime<=2e-10||(m[n++]=h)));for(f=n;--f>-1;)if(h=m[f],2===d&&h._kill(c,a,b)&&(g=!0),2!==d||!h._firstPT&&h._initted){if(2!==d&&!$(h,b))continue;h._enabled(!1,!1)&&(g=!0)}return g},aa=function(a,b,c){for(var d=a._timeline,e=d._timeScale,f=a._startTime;d._timeline;){if(f+=d._startTime,e*=d._timeScale,d._paused)return-100;d=d._timeline}return f/=e,f>b?f-b:c&&f===b||!a._initted&&2*l>f-b?l:(f+=a.totalDuration()/a._timeScale/e)>b+l?0:f-b-l};g._init=function(){var a,b,c,d,e,f=this.vars,g=this._overwrittenProps,h=this._duration,i=!!f.immediateRender,j=f.ease;if(f.startAt){this._startAt&&(this._startAt.render(-1,!0),this._startAt.kill()),e={};for(d in f.startAt)e[d]=f.startAt[d];if(e.overwrite=!1,e.immediateRender=!0,e.lazy=i&&f.lazy!==!1,e.startAt=e.delay=null,this._startAt=G.to(this.target,0,e),i)if(this._time>0)this._startAt=null;else if(0!==h)return}else if(f.runBackwards&&0!==h)if(this._startAt)this._startAt.render(-1,!0),this._startAt.kill(),this._startAt=null;else{0!==this._time&&(i=!1),c={};for(d in f)T[d]&&"autoCSS"!==d||(c[d]=f[d]);if(c.overwrite=0,c.data="isFromStart",c.lazy=i&&f.lazy!==!1,c.immediateRender=i,this._startAt=G.to(this.target,0,c),i){if(0===this._time)return}else this._startAt._init(),this._startAt._enabled(!1),this.vars.immediateRender&&(this._startAt=null)}if(this._ease=j=j?j instanceof v?j:"function"==typeof j?new v(j,f.easeParams):w[j]||G.defaultEase:G.defaultEase,f.easeParams instanceof Array&&j.config&&(this._ease=j.config.apply(j,f.easeParams)),this._easeType=this._ease._type,this._easePower=this._ease._power,this._firstPT=null,this._targets)for(a=this._targets.length;--a>-1;)this._initProps(this._targets[a],this._propLookup[a]={},this._siblings[a],g?g[a]:null)&&(b=!0);else b=this._initProps(this.target,this._propLookup,this._siblings,g);if(b&&G._onPluginEvent("_onInitAllProps",this),g&&(this._firstPT||"function"!=typeof this.target&&this._enabled(!1,!1)),f.runBackwards)for(c=this._firstPT;c;)c.s+=c.c,c.c=-c.c,c=c._next;this._onUpdate=f.onUpdate,this._initted=!0},g._initProps=function(b,c,d,e){var f,g,h,i,j,k;if(null==b)return!1;K[b._gsTweenID]&&Y(),this.vars.css||b.style&&b!==a&&b.nodeType&&Q.css&&this.vars.autoCSS!==!1&&I(this.vars,b);for(f in this.vars)if(k=this.vars[f],T[f])k&&(k instanceof Array||k.push&&o(k))&&-1!==k.join("").indexOf("{self}")&&(this.vars[f]=k=this._swapSelfInParams(k,this));else if(Q[f]&&(i=new Q[f])._onInitTween(b,this.vars[f],this)){for(this._firstPT=j={_next:this._firstPT,t:i,p:"setRatio",s:0,c:1,f:1,n:f,pg:1,pr:i._priority},g=i._overwriteProps.length;--g>-1;)c[i._overwriteProps[g]]=this._firstPT;(i._priority||i._onInitAllProps)&&(h=!0),(i._onDisable||i._onEnable)&&(this._notifyPluginsOfEnabled=!0),j._next&&(j._next._prev=j)}else c[f]=O.call(this,b,f,"get",k,f,0,null,this.vars.stringFilter);return e&&this._kill(e,b)?this._initProps(b,c,d,e):this._overwrite>1&&this._firstPT&&d.length>1&&_(b,this,c,this._overwrite,d)?(this._kill(c,b),this._initProps(b,c,d,e)):(this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration)&&(K[b._gsTweenID]=!0),h)},g.render=function(a,b,c){var d,e,f,g,h=this._time,i=this._duration,j=this._rawPrevTime;if(a>=i-1e-7)this._totalTime=this._time=i,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1,this._reversed||(d=!0,e="onComplete",c=c||this._timeline.autoRemoveChildren),0===i&&(this._initted||!this.vars.lazy||c)&&(this._startTime===this._timeline._duration&&(a=0),(0>j||0>=a&&a>=-1e-7||j===l&&"isPause"!==this.data)&&j!==a&&(c=!0,j>l&&(e="onReverseComplete")),this._rawPrevTime=g=!b||a||j===a?a:l);else if(1e-7>a)this._totalTime=this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==h||0===i&&j>0)&&(e="onReverseComplete",d=this._reversed),0>a&&(this._active=!1,0===i&&(this._initted||!this.vars.lazy||c)&&(j>=0&&(j!==l||"isPause"!==this.data)&&(c=!0),this._rawPrevTime=g=!b||a||j===a?a:l)),this._initted||(c=!0);else if(this._totalTime=this._time=a,this._easeType){var k=a/i,m=this._easeType,n=this._easePower;(1===m||3===m&&k>=.5)&&(k=1-k),3===m&&(k*=2),1===n?k*=k:2===n?k*=k*k:3===n?k*=k*k*k:4===n&&(k*=k*k*k*k),1===m?this.ratio=1-k:2===m?this.ratio=k:.5>a/i?this.ratio=k/2:this.ratio=1-k/2}else this.ratio=this._ease.getRatio(a/i);if(this._time!==h||c){if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!c&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=this._totalTime=h,this._rawPrevTime=j,J.push(this),void(this._lazy=[a,b]);this._time&&!d?this.ratio=this._ease.getRatio(this._time/i):d&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==h&&a>=0&&(this._active=!0),0===h&&(this._startAt&&(a>=0?this._startAt.render(a,b,c):e||(e="_dummyGS")),this.vars.onStart&&(0!==this._time||0===i)&&(b||this._callback("onStart"))),f=this._firstPT;f;)f.f?f.t[f.p](f.c*this.ratio+f.s):f.t[f.p]=f.c*this.ratio+f.s,f=f._next;this._onUpdate&&(0>a&&this._startAt&&a!==-1e-4&&this._startAt.render(a,b,c),b||(this._time!==h||d||c)&&this._callback("onUpdate")),e&&(!this._gc||c)&&(0>a&&this._startAt&&!this._onUpdate&&a!==-1e-4&&this._startAt.render(a,b,c),d&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!b&&this.vars[e]&&this._callback(e),0===i&&this._rawPrevTime===l&&g!==l&&(this._rawPrevTime=0))}},g._kill=function(a,b,c){if("all"===a&&(a=null),null==a&&(null==b||b===this.target))return this._lazy=!1,this._enabled(!1,!1);b="string"!=typeof b?b||this._targets||this.target:G.selector(b)||b;var d,e,f,g,h,i,j,k,l,m=c&&this._time&&c._startTime===this._startTime&&this._timeline===c._timeline;if((o(b)||H(b))&&"number"!=typeof b[0])for(d=b.length;--d>-1;)this._kill(a,b[d],c)&&(i=!0);else{if(this._targets){for(d=this._targets.length;--d>-1;)if(b===this._targets[d]){h=this._propLookup[d]||{},this._overwrittenProps=this._overwrittenProps||[],e=this._overwrittenProps[d]=a?this._overwrittenProps[d]||{}:"all";break}}else{if(b!==this.target)return!1;h=this._propLookup,e=this._overwrittenProps=a?this._overwrittenProps||{}:"all"}if(h){if(j=a||h,k=a!==e&&"all"!==e&&a!==h&&("object"!=typeof a||!a._tempKill),c&&(G.onOverwrite||this.vars.onOverwrite)){for(f in j)h[f]&&(l||(l=[]),l.push(f));if((l||!a)&&!$(this,c,b,l))return!1}for(f in j)(g=h[f])&&(m&&(g.f?g.t[g.p](g.s):g.t[g.p]=g.s,i=!0),g.pg&&g.t._kill(j)&&(i=!0),g.pg&&0!==g.t._overwriteProps.length||(g._prev?g._prev._next=g._next:g===this._firstPT&&(this._firstPT=g._next),g._next&&(g._next._prev=g._prev),g._next=g._prev=null),delete h[f]),k&&(e[f]=1);!this._firstPT&&this._initted&&this._enabled(!1,!1)}}return i},g.invalidate=function(){return this._notifyPluginsOfEnabled&&G._onPluginEvent("_onDisable",this),this._firstPT=this._overwrittenProps=this._startAt=this._onUpdate=null,this._notifyPluginsOfEnabled=this._active=this._lazy=!1,this._propLookup=this._targets?{}:[],D.prototype.invalidate.call(this),this.vars.immediateRender&&(this._time=-l,this.render(Math.min(0,-this._delay))),this},g._enabled=function(a,b){if(i||h.wake(),a&&this._gc){var c,d=this._targets;if(d)for(c=d.length;--c>-1;)this._siblings[c]=Z(d[c],this,!0);else this._siblings=Z(this.target,this,!0)}return D.prototype._enabled.call(this,a,b),this._notifyPluginsOfEnabled&&this._firstPT?G._onPluginEvent(a?"_onEnable":"_onDisable",this):!1},G.to=function(a,b,c){return new G(a,b,c)},G.from=function(a,b,c){return c.runBackwards=!0,c.immediateRender=0!=c.immediateRender,new G(a,b,c)},G.fromTo=function(a,b,c,d){return d.startAt=c,d.immediateRender=0!=d.immediateRender&&0!=c.immediateRender,new G(a,b,d)},G.delayedCall=function(a,b,c,d,e){return new G(b,0,{delay:a,onComplete:b,onCompleteParams:c,callbackScope:d,onReverseComplete:b,onReverseCompleteParams:c,immediateRender:!1,lazy:!1,useFrames:e,overwrite:0})},G.set=function(a,b){return new G(a,0,b)},G.getTweensOf=function(a,b){if(null==a)return[];a="string"!=typeof a?a:G.selector(a)||a;var c,d,e,f;if((o(a)||H(a))&&"number"!=typeof a[0]){for(c=a.length,d=[];--c>-1;)d=d.concat(G.getTweensOf(a[c],b));for(c=d.length;--c>-1;)for(f=d[c],e=c;--e>-1;)f===d[e]&&d.splice(c,1)}else for(d=Z(a).concat(),c=d.length;--c>-1;)(d[c]._gc||b&&!d[c].isActive())&&d.splice(c,1);return d},G.killTweensOf=G.killDelayedCallsTo=function(a,b,c){"object"==typeof b&&(c=b,b=!1);for(var d=G.getTweensOf(a,b),e=d.length;--e>-1;)d[e]._kill(c,a)};var ba=s("plugins.TweenPlugin",function(a,b){this._overwriteProps=(a||"").split(","),this._propName=this._overwriteProps[0],this._priority=b||0,this._super=ba.prototype},!0);if(g=ba.prototype,ba.version="1.18.0",ba.API=2,g._firstPT=null,g._addTween=O,g.setRatio=M,g._kill=function(a){var b,c=this._overwriteProps,d=this._firstPT;if(null!=a[this._propName])this._overwriteProps=[];else for(b=c.length;--b>-1;)null!=a[c[b]]&&c.splice(b,1);for(;d;)null!=a[d.n]&&(d._next&&(d._next._prev=d._prev),d._prev?(d._prev._next=d._next,d._prev=null):this._firstPT===d&&(this._firstPT=d._next)),d=d._next;return!1},g._roundProps=function(a,b){for(var c=this._firstPT;c;)(a[this._propName]||null!=c.n&&a[c.n.split(this._propName+"_").join("")])&&(c.r=b),c=c._next},G._onPluginEvent=function(a,b){var c,d,e,f,g,h=b._firstPT;if("_onInitAllProps"===a){for(;h;){for(g=h._next,d=e;d&&d.pr>h.pr;)d=d._next;(h._prev=d?d._prev:f)?h._prev._next=h:e=h,(h._next=d)?d._prev=h:f=h,h=g}h=b._firstPT=e}for(;h;)h.pg&&"function"==typeof h.t[a]&&h.t[a]()&&(c=!0),h=h._next;return c},ba.activate=function(a){for(var b=a.length;--b>-1;)a[b].API===ba.API&&(Q[(new a[b])._propName]=a[b]);return!0},r.plugin=function(a){if(!(a&&a.propName&&a.init&&a.API))throw"illegal plugin definition.";var b,c=a.propName,d=a.priority||0,e=a.overwriteProps,f={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_roundProps",initAll:"_onInitAllProps"},g=s("plugins."+c.charAt(0).toUpperCase()+c.substr(1)+"Plugin",function(){ba.call(this,c,d),this._overwriteProps=e||[]},a.global===!0),h=g.prototype=new ba(c);h.constructor=g,g.API=a.API;for(b in f)"function"==typeof a[b]&&(h[f[b]]=a[b]);return g.version=a.version,ba.activate([g]),g},e=a._gsQueue){for(f=0;f<e.length;f++)e[f]();for(g in p)p[g].func||a.console.log("GSAP encountered missing dependency: com.greensock."+g)}i=!1}}("undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window,"TweenMax"); // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax // end tweenmax
#! /usr/bin/env node const path = require('path'); const lib = require(path.join(__dirname, '..', 'lib')); if (process.argv[2] == 'market') { lib.get_market_data((error,json) => { if (error) console.err(error); else console.log(json); }); } else { lib.do_for_symbol(process.argv[2], process.argv[3], (error, json) => { if (error) console.err(error); else console.log(json); }); }
'use strict' /** * @param {Fastify} - fastify instance */ const cors = function (fastify, settings) { fastify.register(require('fastify-cors'), settings.cors) } module.exports = cors
# Copyright 2019-2020 Spotify AB # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import logging import os import pytest @pytest.fixture def caplog(caplog): """Set global test logging levels.""" caplog.set_level(logging.DEBUG) return caplog @pytest.fixture def pipeline_config_dict(): return { "project": "test-project", "staging_location": "gs://some/stage", "temp_location": "gs://some/temp", "worker_harness_container_image": "gcr.io/sigint/foo", "streaming": True, "update": False, "experiments": ["beam_fn_api"], "region": "us-central1", "num_workers": 3, "max_num_workers": 5, "disk_size_gb": 50, "worker_machine_type": "n1-standard-4", } @pytest.fixture def patch_os_getcwd(monkeypatch, tmpdir): test_dir = str(tmpdir.mkdir("testing")) monkeypatch.setattr(os, "getcwd", lambda: test_dir) return test_dir
"""A document represents the state of an editing document.""" from .selection import Selection, Interval from .event import Event from . import commands from .userinterface import UserInterface from . import pointer from .navigation import center_around_selection import logging documentlist = [] activedocument = None class Document(): """Contains all objects of one file editing document""" OnDocumentInit = Event() create_userinterface = None _text = '' saved = True mode = None expandtab = False tabwidth = 4 autoindent = True locked_selection = None def __init__(self, filename=""): documentlist.append(self) self.OnTextChanged = Event() self.OnRead = Event() self.OnWrite = Event() self.OnQuit = Event() self.OnActivate = Event() self.OnPrompt = Event() self.filename = filename self._selection = Selection(Interval(0, 0)) self.selectmode = '' if not self.create_userinterface: raise Exception('No function specified in Document.create_userinterface.') self.ui = self.create_userinterface(self) if not isinstance(self.ui, UserInterface): raise Exception('document.ui not an instance of UserInterface.') # Load the default key map from .keymap import default self.keymap = {} self.keymap.update(default) self.OnDocumentInit.fire(self) if filename: commands.load(self) def quit(self): """Quit document.""" logging.info('Quitting document ' + str(self)) self.OnQuit.fire(self) global activedocument index = documentlist.index(self) # debug(str(documentlist)) #debug("self: " + str(self.document)) #debug("index: " + str(index)) # self.getkey() if len(documentlist) == 1: print('fate - document: close the last document by setting activedoc to None') activedocument = None return if index < len(documentlist) - 1: nextdocument = documentlist[index + 1] else: nextdocument = documentlist[index - 1] nextdocument.activate() documentlist.remove(self) @property def text(self): return self._text @text.setter def text(self, value): self._text = value self.saved = False self.OnTextChanged.fire(self) def activate(self): """Activate this document.""" global activedocument activedocument = self self.OnActivate.fire(self) @property def selection(self): return self._selection @selection.setter def selection(self, value): # Make sure only valid selections are applied assert isinstance(value, Selection) value.validate(self) self._selection = value # Update the userinterface viewport to center around first interval center_around_selection(self) def processinput(self, userinput): """This method is called when this document receives userinput.""" # If the cancel key has been pressed, convert input to Cancel if userinput == self.cancelkey: userinput = 'Cancel' logging.debug('Input: ' + str(userinput)) if self.mode: # We are not in normalmode self.mode.processinput(self, userinput) else: # We are in normalmode if isinstance(userinput, pointer.PointerInput): self.process_pointerinput(userinput) else: if type(userinput) == str: key = userinput if key in self.keymap: command = self.keymap[key] else: command = None else: command = userinput while callable(command): command = command(self) def process_pointerinput(self, userinput): assert isinstance(userinput, pointer.PointerInput) if userinput.length: logging.debug('You sweeped from position {} till {}' .format(userinput.pos, userinput.pos + userinput.length)) else: logging.debug('You clicked at position ' + str(userinput.pos)) def next_document(document): """Go to the next document.""" index = documentlist.index(document) ndocument = documentlist[(index + 1) % len(documentlist)] ndocument.activate() commands.next_document = next_document def previous_document(document): """Go to the previous document.""" index = documentlist.index(document) ndocument = documentlist[(index - 1) % len(documentlist)] ndocument.activate() commands.previous_document = previous_document def goto_document(index): """Command constructor to go to the document at given index.""" def wrapper(document): documentlist[index].activate() return wrapper
const { Reply } = require("yandex-dialogs-sdk"); const { createSession } = require("../lib/helpers"); const { SAY_DISH_AND_COST_TO_ADD } = require("../lib/texts"); const { hasOpenedReceipt } = require("../lib/utils"); module.exports = async ctx => { const { userId, sessionId } = ctx; if (hasOpenedReceipt(ctx)) { return Reply.text("Чек уже открыт"); } const now = new Date(); await createSession({ sId: sessionId, uid: userId, created_at: now, updated_at: now, is_closed: false, items: [] }); return Reply.text(`Я добавила новый чек. ${SAY_DISH_AND_COST_TO_ADD} `); };
# Online Bayesian linear regression in 1d using Kalman Filter # Based on: https://github.com/probml/pmtk3/blob/master/demos/linregOnlineDemoKalman.m # The latent state corresponds to the current estimate of the regression weights w. # The observation model has the form # p(y(t) | w(t), x(t)) = Gauss( C(t) * w(t), R(t)) # where C(t) = X(t,:) is the observation matrix for step t. # The dynamics model has the form # p(w(t) | w(t-1)) = Gauss(A * w(t-1), Q) # where Q>0 allows for parameter drift. # We show that the result is equivalent to batch (offline) Bayesian inference. import jax.numpy as jnp import matplotlib.pyplot as plt from numpy.linalg import inv from jsl.lds.kalman_filter import LDS, kalman_filter def kf_linreg(X, y, R, mu0, Sigma0, F, Q): """ Online estimation of a linear regression using Kalman Filters Parameters ---------- X: array(n_obs, dimension) Matrix of features y: array(n_obs,) Array of observations Q: float Known variance mu0: array(dimension) Prior mean Sigma0: array(dimesion, dimension) Prior covariance matrix Returns ------- * array(n_obs, dimension) Online estimation of parameters * array(n_obs, dimension, dimension) Online estimation of uncertainty """ C = lambda t: X[t][None, ...] lds = LDS(F, C, Q, R, mu0, Sigma0) mu_hist, Sigma_hist, _, _ = kalman_filter(lds, y) return mu_hist, Sigma_hist def posterior_lreg(X, y, R, mu0, Sigma0): """ Compute mean and covariance matrix of a Bayesian Linear regression Parameters ---------- X: array(n_obs, dimension) Matrix of features y: array(n_obs,) Array of observations R: float Known variance mu0: array(dimension) Prior mean Sigma0: array(dimesion, dimension) Prior covariance matrix Returns ------- * array(dimension) Posterior mean * array(n_obs, dimension, dimension) Posterior covariance matrix """ Sn_bayes_inv = inv(Sigma0) + X.T @ X / R Sn_bayes = inv(Sn_bayes_inv) mn_bayes = Sn_bayes @ (inv(Sigma0) @ mu0 + X.T @ y / R) return mn_bayes, Sn_bayes def main(): n_obs = 21 timesteps = jnp.arange(n_obs) x = jnp.linspace(0, 20, n_obs) X = jnp.c_[jnp.ones(n_obs), x] F = jnp.eye(2) mu0 = jnp.zeros(2) Sigma0 = jnp.eye(2) * 10. Q, R = 0, 1 # Data from original matlab example y = jnp.array([2.4865, -0.3033, -4.0531, -4.3359, -6.1742, -5.604, -3.5069, -2.3257, -4.6377, -0.2327, -1.9858, 1.0284, -2.264, -0.4508, 1.1672, 6.6524, 4.1452, 5.2677, 6.3403, 9.6264, 14.7842]) # Online estimation mu_hist, Sigma_hist = kf_linreg(X, y, R, mu0, Sigma0, F, Q) kf_var = Sigma_hist[-1, [0, 1], [0, 1]] w0_hist, w1_hist = mu_hist.T w0_err, w1_err = jnp.sqrt(Sigma_hist[:, [0, 1], [0, 1]].T) # Offline estimation (w0_post, w1_post), Sigma_post = posterior_lreg(X, y, R, mu0, Sigma0) w0_std, w1_std = jnp.sqrt(Sigma_post[[0, 1], [0, 1]]) dict_figures = {} fig, ax = plt.subplots() ax.errorbar(timesteps, w0_hist, w0_err, fmt="-o", label="$w_0$", color="black", fillstyle="none") ax.errorbar(timesteps, w1_hist, w1_err, fmt="-o", label="$w_1$", color="tab:red") ax.axhline(y=w0_post, c="black", label="$w_0$ batch") ax.axhline(y=w1_post, c="tab:red", linestyle="--", label="$w_1$ batch") ax.fill_between(timesteps, w0_post - w0_std, w0_post + w0_std, color="black", alpha=0.4) ax.fill_between(timesteps, w1_post - w1_std, w1_post + w1_std, color="tab:red", alpha=0.4) plt.legend() ax.set_xlabel("time") ax.set_ylabel("weights") ax.set_ylim(-8, 4) ax.set_xlim(-0.5, n_obs) dict_figures["linreg_online_kalman"] = fig plt.savefig("prev.png") return dict_figures if __name__ == "__main__": from jsl.demos.plot_utils import savefig plt.rcParams["axes.spines.right"] = False plt.rcParams["axes.spines.top"] = False dict_figures = main() savefig(dict_figures) plt.show()
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest( { id: "15.4.4.17-7-2", path: "TestCases/chapter15/15.4/15.4.4/15.4.4.17/15.4.4.17-7-2.js", description: "Array.prototype.some considers new value of elements in array after it is called", test: function testcase() { function callbackfn(val, idx, obj) { arr[4] = 6; if(val < 6) return false; else return true; } var arr = [1,2,3,4,5]; if(arr.some(callbackfn) === true) return true; }, precondition: function prereq() { return fnExists(Array.prototype.some); } });
'use strict'; const Review = require('../../models/review'); exports.readAllReviews = async ctx => { if (ctx.isAuthenticated()) { try { // found section const response = await Review.find(); if (response && response.length > 0) { ctx.status = 200; return ctx.body = response; } // not found section ctx.status = 404; return ctx.body = 'NOT found'; } catch (e) { ctx.status = 500; ctx.body = e.message; } } else { ctx.status = 401; return ctx.body = 'NOT Authenticated'; } };
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Python wrapper around the SoX library. This module requires that SoX is installed. ''' from __future__ import print_function from pathlib import Path from typing import Union, Optional, List from typing_extensions import Literal from . import core from . import file_info from .core import ENCODING_VALS, EncodingValue from .core import SoxError from .core import SoxiError from .core import VALID_FORMATS from .core import is_number from .core import play from .core import sox from .log import logger from .transform import Transformer COMBINE_VALS = [ 'concatenate', 'merge', 'mix', 'mix-power', 'multiply' ] CombineType = Literal['concatenate', 'merge', 'mix', 'mix-power', 'multiply'] class Combiner(Transformer): '''Audio file combiner. Class which allows multiple files to be combined to create an output file, saved to output_filepath. Inherits all methods from the Transformer class, thus any effects can be applied after combining. ''' def __init__(self): super(Combiner, self).__init__() def build(self, input_filepath_list: Union[str, Path], output_filepath: Union[str, Path], combine_type: CombineType, input_volumes: Optional[List[float]] = None): '''Builds the output_file by executing the current set of commands. Parameters ---------- input_filepath_list : list of str List of paths to input audio files. output_filepath : str Path to desired output file. If a file already exists at the given path, the file will be overwritten. combine_type : str Input file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. Returns ------- status : bool True on success. ''' file_info.validate_input_file_list(input_filepath_list) file_info.validate_output_file(output_filepath) _validate_combine_type(combine_type) _validate_volumes(input_volumes) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) try: _validate_file_formats(input_filepath_list, combine_type) except SoxiError: logger.warning("unable to validate file formats.") args = [] args.extend(self.globals) args.extend(['--combine', combine_type]) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self._output_format_args(self.output_format)) args.append(output_filepath) args.extend(self.effects) status, out, err = sox(args) if status != 0: raise SoxError( "Stdout: {}\nStderr: {}".format(out, err) ) else: logger.info( "Created %s with combiner %s and effects: %s", output_filepath, combine_type, " ".join(self.effects_log) ) if out is not None: logger.info("[SoX] {}".format(out)) return True def preview(self, input_filepath_list: List[Union[str, Path]], combine_type: CombineType, input_volumes: Optional[List[float]] = None): '''Play a preview of the output with the current set of effects Parameters ---------- input_filepath_list : list of str List of paths to input audio files. combine_type : str Input file combining method. One of the following values: * concatenate : combine input files by concatenating in the order given. * merge : combine input files by stacking each input file into a new channel of the output file. * mix : combine input files by summing samples in corresponding channels. * mix-power : combine input files with volume adjustments such that the output volume is roughly equivlent to one of the input signals. * multiply : combine input files by multiplying samples in corresponding samples. input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. ''' args = ["play", "--no-show-progress"] args.extend(self.globals) args.extend(['--combine', combine_type]) input_format_list = _build_input_format_list( input_filepath_list, input_volumes, self.input_format ) input_args = _build_input_args(input_filepath_list, input_format_list) args.extend(input_args) args.extend(self.effects) play(args) def set_input_format(self, file_type: Optional[List[str]] = None, rate: Optional[List[float]] = None, bits: Optional[List[int]] = None, channels: Optional[List[int]] = None, encoding: Optional[List[EncodingValue]] = None, ignore_length: Optional[List[bool]] = None): '''Sets input file format arguments. This is primarily useful when dealing with audio files without a file extension. Overwrites any previously set input file arguments. If this function is not explicity called the input format is inferred from the file extension or the file's header. Parameters ---------- file_type : list of str or None, default=None The file type of the input audio file. Should be the same as what the file extension would be, for ex. 'mp3' or 'wav'. rate : list of float or None, default=None The sample rate of the input audio file. If None the sample rate is inferred. bits : list of int or None, default=None The number of bits per sample. If None, the number of bits per sample is inferred. channels : list of int or None, default=None The number of channels in the audio file. If None the number of channels is inferred. encoding : list of str or None, default=None The audio encoding type. Sometimes needed with file-types that support more than one encoding type. One of: * signed-integer : PCM data stored as signed (‘two’s complement’) integers. Commonly used with a 16 or 24−bit encoding size. A value of 0 represents minimum signal power. * unsigned-integer : PCM data stored as unsigned integers. Commonly used with an 8-bit encoding size. A value of 0 represents maximum signal power. * floating-point : PCM data stored as IEEE 753 single precision (32-bit) or double precision (64-bit) floating-point (‘real’) numbers. A value of 0 represents minimum signal power. * a-law : International telephony standard for logarithmic encoding to 8 bits per sample. It has a precision equivalent to roughly 13-bit PCM and is sometimes encoded with reversed bit-ordering. * u-law : North American telephony standard for logarithmic encoding to 8 bits per sample. A.k.a. μ-law. It has a precision equivalent to roughly 14-bit PCM and is sometimes encoded with reversed bit-ordering. * oki-adpcm : OKI (a.k.a. VOX, Dialogic, or Intel) 4-bit ADPCM; it has a precision equivalent to roughly 12-bit PCM. ADPCM is a form of audio compression that has a good compromise between audio quality and encoding/decoding speed. * ima-adpcm : IMA (a.k.a. DVI) 4-bit ADPCM; it has a precision equivalent to roughly 13-bit PCM. * ms-adpcm : Microsoft 4-bit ADPCM; it has a precision equivalent to roughly 14-bit PCM. * gsm-full-rate : GSM is currently used for the vast majority of the world’s digital wireless telephone calls. It utilises several audio formats with different bit-rates and associated speech quality. SoX has support for GSM’s original 13kbps ‘Full Rate’ audio format. It is usually CPU-intensive to work with GSM audio. ignore_length : list of bool or None, default=None If True, overrides an (incorrect) audio length given in an audio file’s header. If this option is given then SoX will keep reading audio until it reaches the end of the input file. ''' if file_type is not None and not isinstance(file_type, list): raise ValueError("file_type must be a list or None.") if file_type is not None: if not all([f in VALID_FORMATS for f in file_type]): raise ValueError( 'file_type elements ' 'must be one of {}'.format(VALID_FORMATS) ) else: file_type = [] if rate is not None and not isinstance(rate, list): raise ValueError("rate must be a list or None.") if rate is not None: if not all([is_number(r) and r > 0 for r in rate]): raise ValueError('rate elements must be positive floats.') else: rate = [] if bits is not None and not isinstance(bits, list): raise ValueError("bits must be a list or None.") if bits is not None: if not all([isinstance(b, int) and b > 0 for b in bits]): raise ValueError('bit elements must be positive ints.') else: bits = [] if channels is not None and not isinstance(channels, list): raise ValueError("channels must be a list or None.") if channels is not None: if not all([isinstance(c, int) and c > 0 for c in channels]): raise ValueError('channel elements must be positive ints.') else: channels = [] if encoding is not None and not isinstance(encoding, list): raise ValueError("encoding must be a list or None.") if encoding is not None: if not all([e in ENCODING_VALS for e in encoding]): raise ValueError( 'elements of encoding must ' 'be one of {}'.format(ENCODING_VALS) ) else: encoding = [] if ignore_length is not None and not isinstance(ignore_length, list): raise ValueError("ignore_length must be a list or None.") if ignore_length is not None: if not all([isinstance(l, bool) for l in ignore_length]): raise ValueError("ignore_length elements must be booleans.") else: ignore_length = [] max_input_arg_len = max([ len(file_type), len(rate), len(bits), len(channels), len(encoding), len(ignore_length) ]) input_format = [] for _ in range(max_input_arg_len): input_format.append([]) for i, f in enumerate(file_type): input_format[i].extend(['-t', '{}'.format(f)]) for i, r in enumerate(rate): input_format[i].extend(['-r', '{}'.format(r)]) for i, b in enumerate(bits): input_format[i].extend(['-b', '{}'.format(b)]) for i, c in enumerate(channels): input_format[i].extend(['-c', '{}'.format(c)]) for i, e in enumerate(encoding): input_format[i].extend(['-e', '{}'.format(e)]) for i, l in enumerate(ignore_length): if l is True: input_format[i].append('--ignore-length') self.input_format = input_format return self def _validate_file_formats(input_filepath_list: List[Union[str, Path]], combine_type: CombineType): '''Validate that combine method can be performed with given files. Raises IOError if input file formats are incompatible. ''' _validate_sample_rates(input_filepath_list, combine_type) if combine_type == 'concatenate': _validate_num_channels(input_filepath_list, combine_type) def _validate_sample_rates(input_filepath_list: List[Path], combine_type: CombineType): ''' Check if files in input file list have the same sample rate ''' sample_rates = [ file_info.sample_rate(f) for f in input_filepath_list ] if not core.all_equal(sample_rates): raise IOError( "Input files do not have the same sample rate. The {} combine " "type requires that all files have the same sample rate" .format(combine_type) ) def _validate_num_channels(input_filepath_list: List[Path], combine_type: CombineType): ''' Check if files in input file list have the same number of channels ''' channels = [ file_info.channels(f) for f in input_filepath_list ] if not core.all_equal(channels): raise IOError( "Input files do not have the same number of channels. The " "{} combine type requires that all files have the same " "number of channels" .format(combine_type) ) def _build_input_format_list(input_filepath_list: List[Path], input_volumes: Optional[List[float]] = None, input_format: Optional[List[List[str]]] = None) \ -> List[str]: '''Set input formats given input_volumes. Parameters ---------- input_filepath_list : list of str List of input files input_volumes : list of float, default=None List of volumes to be applied upon combining input files. Volumes are applied to the input files in order. If None, input files will be combined at their original volumes. input_format : list of lists, default=None List of input formats to be applied to each input file. Formatting arguments are applied to the input files in order. If None, the input formats will be inferred from the file header. ''' n_inputs = len(input_filepath_list) input_format_list = [] for _ in range(n_inputs): input_format_list.append([]) # Adjust length of input_volumes list if input_volumes is None: vols = [1] * n_inputs else: n_volumes = len(input_volumes) if n_volumes < n_inputs: logger.warning( 'Volumes were only specified for %s out of %s files.' 'The last %s files will remain at their original volumes.', n_volumes, n_inputs, n_inputs - n_volumes ) vols = input_volumes + [1] * (n_inputs - n_volumes) elif n_volumes > n_inputs: logger.warning( '%s volumes were specified but only %s input files exist.' 'The last %s volumes will be ignored.', n_volumes, n_inputs, n_volumes - n_inputs ) vols = input_volumes[:n_inputs] else: vols = [v for v in input_volumes] # Adjust length of input_format list if input_format is None: fmts = [[] for _ in range(n_inputs)] else: n_fmts = len(input_format) if n_fmts < n_inputs: logger.warning( 'Input formats were only specified for %s out of %s files.' 'The last %s files will remain unformatted.', n_fmts, n_inputs, n_inputs - n_fmts ) fmts = [f for f in input_format] fmts.extend([[] for _ in range(n_inputs - n_fmts)]) elif n_fmts > n_inputs: logger.warning( '%s Input formats were specified but only %s input files exist' '. The last %s formats will be ignored.', n_fmts, n_inputs, n_fmts - n_inputs ) fmts = input_format[:n_inputs] else: fmts = [f for f in input_format] for i, (vol, fmt) in enumerate(zip(vols, fmts)): input_format_list[i].extend(['-v', '{}'.format(vol)]) input_format_list[i].extend(fmt) return input_format_list def _build_input_args(input_filepath_list: List[Path], input_format_list: List[str]) -> List[str]: ''' Builds input arguments by stitching input filepaths and input formats together. ''' # Convert pathlib.Paths to strings. input_filepath_list = [str(x) for x in input_filepath_list] if len(input_format_list) != len(input_filepath_list): raise ValueError( "input_format_list & input_filepath_list are not the same size" ) input_args = [] zipped = zip(input_filepath_list, input_format_list) for input_file, input_fmt in zipped: input_args.extend(input_fmt) input_args.append(input_file) return input_args def _validate_combine_type(combine_type: List[CombineType]): '''Check that the combine_type is valid. Parameters ---------- combine_type : str Combine type. ''' if combine_type not in COMBINE_VALS: raise ValueError( 'Invalid value for combine_type. Must be one of {}'.format( COMBINE_VALS) ) def _validate_volumes(input_volumes: List[float]): '''Check input_volumes contains a valid list of volumes. Parameters ---------- input_volumes : list list of volume values. Castable to numbers. ''' if not (input_volumes is None or isinstance(input_volumes, list)): raise TypeError("input_volumes must be None or a list.") if isinstance(input_volumes, list): for vol in input_volumes: if not core.is_number(vol): raise ValueError( "Elements of input_volumes must be numbers: found {}" .format(vol) )
//// [ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.ts] module A { export class Point { x: number; y: number; } export var Origin: Point = { x: 0, y: 0 }; export class Point3d extends Point { z: number; } export var Origin3d: Point3d = { x: 0, y: 0, z: 0 }; export class Line<TPoint extends Point>{ constructor(public start: TPoint, public end: TPoint) { } } } //// [ExportClassWithAccessibleTypesInTypeParameterConstraintsClassHeritageListMemberTypeAnnotations.js] var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var A; (function (A) { var Point = /** @class */ (function () { function Point() { } return Point; }()); A.Point = Point; A.Origin = { x: 0, y: 0 }; var Point3d = /** @class */ (function (_super) { __extends(Point3d, _super); function Point3d() { return _super !== null && _super.apply(this, arguments) || this; } return Point3d; }(Point)); A.Point3d = Point3d; A.Origin3d = { x: 0, y: 0, z: 0 }; var Line = /** @class */ (function () { function Line(start, end) { this.start = start; this.end = end; } return Line; }()); A.Line = Line; })(A || (A = {}));
import structlog from eth_utils import to_hex from gevent import joinall from gevent.pool import Pool from raiden import routing from raiden.constants import ABSENT_SECRET, BLOCK_ID_LATEST from raiden.messages.abstract import Message from raiden.messages.decode import balanceproof_from_envelope, lockedtransfersigned_from_message from raiden.messages.synchronization import Delivered, Processed from raiden.messages.transfers import ( LockedTransfer, LockExpired, RefundTransfer, RevealSecret, SecretRequest, Unlock, ) from raiden.messages.withdraw import WithdrawConfirmation, WithdrawExpired, WithdrawRequest from raiden.transfer import views from raiden.transfer.architecture import StateChange from raiden.transfer.identifiers import CanonicalIdentifier from raiden.transfer.mediated_transfer.state_change import ( ActionInitMediator, ActionInitTarget, ActionTransferReroute, BalanceProofStateChange, ReceiveLockExpired, ReceiveSecretRequest, ReceiveSecretReveal, ReceiveTransferCancelRoute, ReceiveTransferRefund, ) from raiden.transfer.state import HopState from raiden.transfer.state_change import ( ReceiveDelivered, ReceiveProcessed, ReceiveUnlock, ReceiveWithdrawConfirmation, ReceiveWithdrawExpired, ReceiveWithdrawRequest, ) from raiden.transfer.views import TransferRole from raiden.utils.transfers import random_secret from raiden.utils.typing import ( MYPY_ANNOTATION, TYPE_CHECKING, Address, List, Set, TargetAddress, Tuple, ) if TYPE_CHECKING: from raiden.raiden_service import RaidenService log = structlog.get_logger(__name__) class MessageHandler: def on_messages(self, raiden: "RaidenService", messages: List[Message]) -> None: # pylint: disable=unidiomatic-typecheck # Remove duplicated messages, this can happen because of retries done # by the sender when the receiver takes too long to acknowledge. This # is a problem since the receiver may be taking a long time to reply # because it is under high load, processing the duplicated messages # just make the problem worse. unique_messages: Set[Message] = set(messages) pool = Pool() for message in unique_messages: if type(message) == SecretRequest: assert isinstance(message, SecretRequest), MYPY_ANNOTATION pool.apply_async(self.handle_message_secretrequest, (raiden, message)) elif type(message) == RevealSecret: assert isinstance(message, RevealSecret), MYPY_ANNOTATION pool.apply_async(self.handle_message_revealsecret, (raiden, message)) elif type(message) == Unlock: assert isinstance(message, Unlock), MYPY_ANNOTATION pool.apply_async(self.handle_message_unlock, (raiden, message)) elif type(message) == LockExpired: assert isinstance(message, LockExpired), MYPY_ANNOTATION pool.apply_async(self.handle_message_lockexpired, (raiden, message)) elif type(message) == RefundTransfer: assert isinstance(message, RefundTransfer), MYPY_ANNOTATION pool.apply_async(self.handle_message_refundtransfer, (raiden, message)) elif type(message) == LockedTransfer: assert isinstance(message, LockedTransfer), MYPY_ANNOTATION pool.apply_async(self.handle_message_lockedtransfer, (raiden, message)) elif type(message) == WithdrawRequest: assert isinstance(message, WithdrawRequest), MYPY_ANNOTATION pool.apply_async(self.handle_message_withdrawrequest, (raiden, message)) elif type(message) == WithdrawConfirmation: assert isinstance(message, WithdrawConfirmation), MYPY_ANNOTATION pool.apply_async(self.handle_message_withdraw_confirmation, (raiden, message)) elif type(message) == WithdrawExpired: assert isinstance(message, WithdrawExpired), MYPY_ANNOTATION pool.apply_async(self.handle_message_withdraw_expired, (raiden, message)) elif type(message) == Delivered: assert isinstance(message, Delivered), MYPY_ANNOTATION pool.apply_async(self.handle_message_delivered, (raiden, message)) elif type(message) == Processed: assert isinstance(message, Processed), MYPY_ANNOTATION pool.apply_async(self.handle_message_processed, (raiden, message)) else: log.error(f"Unknown message cmdid {message.cmdid}") all_state_changes: List[StateChange] = list() for greenlet in joinall(set(pool), raise_error=True): all_state_changes.extend(greenlet.get()) if all_state_changes: # Order balance proof messages, based the target channel and the # nonce. Because the balance proofs messages must be processed in # order, and there is no guarantee of the order of messages # (an asynchronous network is assumed) This reduces latency when a # balance proof is considered invalid because of a race with the # blockchain view of each node. def by_canonical_identifier(state_change: StateChange) -> Tuple[int, int]: if isinstance(state_change, BalanceProofStateChange): balance_proof = state_change.balance_proof return ( balance_proof.canonical_identifier.channel_identifier, balance_proof.nonce, ) return 0, 0 all_state_changes.sort(key=by_canonical_identifier) raiden.handle_and_track_state_changes(all_state_changes) @staticmethod def handle_message_withdrawrequest( raiden: "RaidenService", message: WithdrawRequest # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" withdraw_request = ReceiveWithdrawRequest( canonical_identifier=CanonicalIdentifier( chain_identifier=message.chain_id, token_network_address=message.token_network_address, channel_identifier=message.channel_identifier, ), message_identifier=message.message_identifier, total_withdraw=message.total_withdraw, sender=message.sender, participant=message.participant, nonce=message.nonce, expiration=message.expiration, signature=message.signature, ) return [withdraw_request] @staticmethod def handle_message_withdraw_confirmation( raiden: "RaidenService", message: WithdrawConfirmation # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" withdraw = ReceiveWithdrawConfirmation( canonical_identifier=CanonicalIdentifier( chain_identifier=message.chain_id, token_network_address=message.token_network_address, channel_identifier=message.channel_identifier, ), message_identifier=message.message_identifier, total_withdraw=message.total_withdraw, sender=message.sender, participant=message.participant, nonce=message.nonce, expiration=message.expiration, signature=message.signature, ) return [withdraw] @staticmethod def handle_message_withdraw_expired( raiden: "RaidenService", message: WithdrawExpired # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" withdraw_expired = ReceiveWithdrawExpired( canonical_identifier=CanonicalIdentifier( chain_identifier=message.chain_id, token_network_address=message.token_network_address, channel_identifier=message.channel_identifier, ), message_identifier=message.message_identifier, total_withdraw=message.total_withdraw, sender=message.sender, participant=message.participant, nonce=message.nonce, expiration=message.expiration, ) return [withdraw_expired] @staticmethod def handle_message_secretrequest( raiden: "RaidenService", message: SecretRequest # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" secret_request = ReceiveSecretRequest( payment_identifier=message.payment_identifier, amount=message.amount, expiration=message.expiration, secrethash=message.secrethash, sender=message.sender, ) return [secret_request] @staticmethod def handle_message_revealsecret( raiden: "RaidenService", message: RevealSecret # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" secret_reveal = ReceiveSecretReveal(secret=message.secret, sender=message.sender) return [secret_reveal] @staticmethod def handle_message_unlock( raiden: "RaidenService", message: Unlock # pylint: disable=unused-argument ) -> List[StateChange]: balance_proof = balanceproof_from_envelope(message) unlock = ReceiveUnlock( message_identifier=message.message_identifier, secret=message.secret, balance_proof=balance_proof, sender=balance_proof.sender, ) return [unlock] @staticmethod def handle_message_lockexpired( raiden: "RaidenService", message: LockExpired # pylint: disable=unused-argument ) -> List[StateChange]: balance_proof = balanceproof_from_envelope(message) lock_expired = ReceiveLockExpired( sender=balance_proof.sender, balance_proof=balance_proof, secrethash=message.secrethash, message_identifier=message.message_identifier, ) return [lock_expired] @staticmethod def handle_message_refundtransfer( raiden: "RaidenService", message: RefundTransfer ) -> List[StateChange]: chain_state = views.state_from_raiden(raiden) from_transfer = lockedtransfersigned_from_message(message=message) role = views.get_transfer_role( chain_state=chain_state, secrethash=from_transfer.lock.secrethash ) state_changes: List[StateChange] = [] if role == TransferRole.INITIATOR: old_secret = views.get_transfer_secret(chain_state, from_transfer.lock.secrethash) is_secret_known = old_secret is not None and old_secret != ABSENT_SECRET state_changes.append( ReceiveTransferCancelRoute( transfer=from_transfer, balance_proof=from_transfer.balance_proof, sender=from_transfer.balance_proof.sender, # pylint: disable=no-member ) ) # Currently, the only case where we can be initiators and not # know the secret is if the transfer is part of an atomic swap. In # the case of an atomic swap, we will not try to re-route the # transfer. In all other cases we can try to find another route # (and generate a new secret) if is_secret_known: state_changes.append( ActionTransferReroute( transfer=from_transfer, balance_proof=from_transfer.balance_proof, # pylint: disable=no-member sender=from_transfer.balance_proof.sender, # pylint: disable=no-member secret=random_secret(), ) ) else: state_changes.append( ReceiveTransferRefund( transfer=from_transfer, balance_proof=from_transfer.balance_proof, sender=from_transfer.balance_proof.sender, # pylint: disable=no-member ) ) return state_changes @staticmethod def handle_message_lockedtransfer( raiden: "RaidenService", message: LockedTransfer # pylint: disable=unused-argument ) -> List[StateChange]: secrethash = message.lock.secrethash # We must check if the secret was registered against the latest block, # even if the block is forked away and the transaction that registers # the secret is removed from the blockchain. The rationale here is that # someone else does know the secret, regardless of the chain state, so # the node must not use it to start a payment. # # For this particular case, it's preferable to use `latest` instead of # having a specific block_hash, because it's preferable to know if the secret # was ever known, rather than having a consistent view of the blockchain. registered = raiden.default_secret_registry.is_secret_registered( secrethash=secrethash, block_identifier=BLOCK_ID_LATEST ) if registered: log.warning( f"Ignoring received locked transfer with secrethash {to_hex(secrethash)} " f"since it is already registered in the secret registry" ) return [] assert message.sender, "Invalid message dispatched, it should be signed" from_transfer = lockedtransfersigned_from_message(message) from_hop = HopState( node_address=message.sender, # pylint: disable=E1101 channel_identifier=from_transfer.balance_proof.channel_identifier, ) if message.target == TargetAddress(raiden.address): raiden.immediate_health_check_for(Address(message.initiator)) return [ ActionInitTarget( from_hop=from_hop, transfer=from_transfer, balance_proof=from_transfer.balance_proof, sender=from_transfer.balance_proof.sender, ) ] else: route_states = routing.resolve_routes( routes=message.metadata.routes, token_network_address=from_transfer.balance_proof.token_network_address, chain_state=views.state_from_raiden(raiden), ) return [ ActionInitMediator( from_hop=from_hop, route_states=route_states, from_transfer=from_transfer, balance_proof=from_transfer.balance_proof, sender=from_transfer.balance_proof.sender, ) ] @staticmethod def handle_message_processed( raiden: "RaidenService", message: Processed # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" processed = ReceiveProcessed(message.sender, message.message_identifier) return [processed] @staticmethod def handle_message_delivered( raiden: "RaidenService", message: Delivered # pylint: disable=unused-argument ) -> List[StateChange]: assert message.sender, "message must be signed" delivered = ReceiveDelivered(message.sender, message.delivered_message_identifier) return [delivered]
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import settings from '../../globals/js/settings'; import mixin from '../../globals/js/misc/mixin'; import createComponent from '../../globals/js/mixins/create-component'; import initComponentBySearch from '../../globals/js/mixins/init-component-by-search'; import handles from '../../globals/js/mixins/handles'; import on from '../../globals/js/misc/on'; var CopyButton = /*#__PURE__*/function (_mixin) { _inherits(CopyButton, _mixin); var _super = _createSuper(CopyButton); /** * CopyBtn UI. * @extends CreateComponent * @extends InitComponentBySearch * @extends Handles * @param {HTMLElement} element The element working as a copy button UI. */ function CopyButton(element, options) { var _this; _classCallCheck(this, CopyButton); _this = _super.call(this, element, options); _this.manage(on(_this.element, 'click', function () { return _this.handleClick(); })); _this.manage(on(_this.element, 'animationend', function (event) { return _this.handleAnimationEnd(event); })); return _this; } /** * Cleanup animation classes */ _createClass(CopyButton, [{ key: "handleAnimationEnd", value: function handleAnimationEnd(event) { if (event.animationName === 'hide-feedback') { this.element.classList.remove(this.options.classAnimating); this.element.classList.remove(this.options.classFadeOut); } } /** * Show the feedback tooltip on click. Hide the feedback tooltip after specified timeout value. */ }, { key: "handleClick", value: function handleClick() { var _this2 = this; var feedback = this.element.querySelector(this.options.feedbackTooltip); if (feedback) { feedback.classList.add(this.options.classShowFeedback); setTimeout(function () { feedback.classList.remove(_this2.options.classShowFeedback); }, this.options.timeoutValue); } else { this.element.classList.add(this.options.classAnimating); this.element.classList.add(this.options.classFadeIn); setTimeout(function () { _this2.element.classList.remove(_this2.options.classFadeIn); _this2.element.classList.add(_this2.options.classFadeOut); }, this.options.timeoutValue); } } /** * The map associating DOM element and copy button UI instance. * @member CopyBtn.components * @type {WeakMap} */ }], [{ key: "options", get: /** * The component options. * If `options` is specified in the constructor, {@linkcode CopyBtn.create .create()}, or {@linkcode CopyBtn.init .init()}, * properties in this object are overriden for the instance being create and how {@linkcode CopyBtn.init .init()} works. * @member CopyBtn.options * @type {object} * @property {string} selectorInit The data attribute to find copy button UIs. * @property {string} feedbackTooltip The data attribute to find feedback tooltip. * @property {string} classShowFeedback The CSS selector for showing the feedback tooltip. * @property {number} timeoutValue The specified timeout value before the feedback tooltip is hidden. */ function get() { var prefix = settings.prefix; return { selectorInit: '[data-copy-btn]', feedbackTooltip: '[data-feedback]', classShowFeedback: "".concat(prefix, "--btn--copy__feedback--displayed"), classAnimating: "".concat(prefix, "--copy-btn--animating"), classFadeIn: "".concat(prefix, "--copy-btn--fade-in"), classFadeOut: "".concat(prefix, "--copy-btn--fade-out"), timeoutValue: 2000 }; } }]); CopyButton.components = new WeakMap(); return CopyButton; }(mixin(createComponent, initComponentBySearch, handles)); export default CopyButton;
/* eslint-disable no-console */ import axios from 'axios' const findInternalRating = require('../services/findRating') const ratingPrefix = process.env.RATING_API_PREFIX const ratingSuffix = process.env.RATING_API_SUFFIX module.exports = async (professor) => { // Searches database for professor's rating const profRating = await findInternalRating(professor) if (profRating.length > 0) { return { rating: profRating[0].avgRating, ratingId: profRating[0].pkId } } // If it doesn't exist, polls API for rating const { data } = await axios({ method: 'GET', url: `${ratingPrefix}${professor}${ratingSuffix}`, mode: 'cors', credentials: 'same-origin', redirect: 'follow', referrerPolicy: 'no-referrer', }) if (data.response.numFound === 0) { return { err: true } } return { rating: data.response.docs[0].averageratingscore_rf, ratingId: data.response.docs[0].pk_id } }
import transformCss from '..' it('transforms shadow offsets', () => { expect(transformCss([['shadow-offset', '10px 5px']])).toEqual({ shadowOffset: { width: 10, height: 5 }, }) }) it('transforms text shadow offsets', () => { expect(transformCss([['text-shadow-offset', '10px 5px']])).toEqual({ textShadowOffset: { width: 10, height: 5 }, }) })
""" =============================== Extrema =============================== We detect local maxima in a galaxy image. The image is corrupted by noise, generating many local maxima. To keep only those maxima with sufficient local contrast, we use h-maxima. """ import numpy as np import matplotlib.pyplot as plt from skimage.measure import label from skimage import data from skimage import color from skimage.morphology import extrema from skimage import exposure color_image = data.hubble_deep_field() # for illustration purposes, we work on a crop of the image. x_0 = 70 y_0 = 354 width = 100 height = 100 img = color.rgb2gray(color_image)[y_0:(y_0 + height), x_0:(x_0 + width)] # the rescaling is done only for visualization purpose. # the algorithms would work identically in an unscaled version of the # image. However, the parameter h needs to be adapted to the scale. img = exposure.rescale_intensity(img) ############################################################## # MAXIMA DETECTION # Maxima in the galaxy image are detected by mathematical morphology. # There is no a priori constraint on the density. # We find all local maxima local_maxima = extrema.local_maxima(img) label_maxima = label(local_maxima) overlay = color.label2rgb(label_maxima, img, alpha=0.7, bg_label=0, bg_color=None, colors=[(1, 0, 0)]) # We observed in the previous image, that there are many local maxima # that are caused by the noise in the image. # For this, we find all local maxima with a height of h. # This height is the gray level value by which we need to descent # in order to reach a higher maximum and it can be seen as a local # contrast measurement. # The value of h scales with the dynamic range of the image, i.e. # if we multiply the image with a constant, we need to multiply # the value of h with the same constant in order to achieve the same result. h = 0.05 h_maxima = extrema.h_maxima(img, h) label_h_maxima = label(h_maxima) overlay_h = color.label2rgb(label_h_maxima, img, alpha=0.7, bg_label=0, bg_color=None, colors=[(1, 0, 0)]) ############################################################## # GRAPHICAL OUTPUT # a new figure with 3 subplots fig, ax = plt.subplots(1, 3, figsize=(15, 5)) ax[0].imshow(img, cmap='gray', interpolation='none') ax[0].set_title('Original image') ax[0].axis('off') ax[1].imshow(overlay, interpolation='none') ax[1].set_title('Local Maxima') ax[1].axis('off') ax[2].imshow(overlay_h, interpolation='none') ax[2].set_title('h maxima for h = %.2f' % h) ax[2].axis('off') plt.show()
#!/usr/bin/env python import rospy from random import randint #from time import time from geometry_msgs.msg import Twist, Vector3, Point, Quaternion, Pose2D from sensor_msgs.msg import LaserScan from std_msgs.msg import String, Int32MultiArray, Bool from nav_msgs.msg import Odometry from scipy.spatial.transform import Rotation as R from copy import deepcopy import math from std_srvs.srv import Empty ## Global Variables # mobile_base velocity publisher command_pub = None # scan data publisher scan_pub = None # publisher to request commands from the agent req_pub = None # useful entries in the lidar's range for checking validity of commands fwd_scan = None rear_scan = None l_scan = None r_scan = None off_left = None off_right = None # Twist command that will be sent to the robot cmd = Twist() # boolean for checking whether robot is still in initialization initvar = True stall_count = 0 stalled = False # Where we are and where we want to go current_position = Pose2D(0,0,0) goal_position = Pose2D(0,0,0) start_position = Pose2D(0,0,0) integral_prior_angle = 0 integral_prior_forward = 0 error_prior_forward = 0 error_prior_angle = 0 # keep track of the command currently being executed current_cmd = "halt" # 1/frequency of timer events iteration_time = .1 # list of commands (strings, not String msgs) command_list = [] def check_scan(scan_msg): global fwd_scan, rear_scan, r_scan, l_scan,off_right,off_left # scan_msg.ranges is an array of 640 elements representing # distance measurements in a full circle around the robot (0=fwd, CCW?) # update and discretize the important entries fwd_scan = scan_discrete(scan_msg.ranges[320]) # directly forward rear_scan = scan_discrete(scan_msg.ranges[0]) # directly behind r45_scan = scan_discrete(scan_msg.ranges[240]) # ~45 degrees left r_scan = scan_discrete(scan_msg.ranges[160]) # 90 degrees left l45_scan = scan_discrete(scan_msg.ranges[400]) # ~45 degrees right l_scan = scan_discrete(scan_msg.ranges[480]) # 90 degrees right off_right = scan_discrete(scan_msg.ranges[280]) off_left = scan_discrete(scan_msg.ranges[360]) # group and publish the relevant scan ranges scan_group = Int32MultiArray() scan_group.data = [fwd_scan, rear_scan, l45_scan, l_scan, r45_scan, r_scan] #print(scan_group.data) scan_pub.publish(scan_group) def check_odom(odom_msg): global current_position current_position.x = odom_msg.pose.pose.position.x current_position.y = odom_msg.pose.pose.position.y quat_orien = odom_msg.pose.pose.orientation r = R.from_quat([quat_orien.x, quat_orien.y, quat_orien.z, quat_orien.w]) #print(str(r.as_rotvec()[2] * 180/3.1)) # Theta is positive ccw of start until 180, Theta is negative cw of start until -180 current_position.theta = r.as_rotvec()[2]* 180/3.1 if(current_position.theta < 0): current_position.theta += 360 # 2D plane, we will stay at 0 on x,y def scan_discrete(scan_val): # Turns continuous scan values into either 1, 2, or 3 to # represent distance to obstacles in a discrete format. # The goal of this is to shrink the state space and make learning easier. if scan_val == 0: # a lidar reading of 0 means it doesn't see anything. # group with "far away" return 3 elif scan_val < 1.4: # close obstacle (adjacent vertex is occupied) return 1 elif scan_val < 2.4: # visible obstacle, but not at the adjacent vertex return 2 else: # far away obstacle return 3 def add_cmd(str_msg): global command_list # commands will be either "north", "south", "east", or "west". # we need to handle turning here by creating two commands for each one. # first determine the amount we need to turn to get # from current heading to the desired heading. # goal_position.theta keeps track of the heading we # currently have or are actively trying to get onto. if str_msg.data == "north" and goal_position.theta == 0 \ or str_msg.data == "east" and goal_position.theta == 270 \ or str_msg.data == "south" and goal_position.theta == 180 \ or str_msg.data == "west" and goal_position.theta == 90: # we are already facing the right way. pass elif str_msg.data == "north" and goal_position.theta == 180 \ or str_msg.data == "east" and goal_position.theta == 90 \ or str_msg.data == "south" and goal_position.theta == 0 \ or str_msg.data == "west" and goal_position.theta == 270: # we are facing the opposite way. command_list.append("turn_180") elif str_msg.data == "north" and goal_position.theta == 90 \ or str_msg.data == "west" and goal_position.theta == 180 \ or str_msg.data == "south" and goal_position.theta == 270 \ or str_msg.data == "east" and goal_position.theta == 0: # we need to turn right command_list.append("turn_right") elif str_msg.data == "north" and goal_position.theta == 270 \ or str_msg.data == "east" and goal_position.theta == 180 \ or str_msg.data == "south" and goal_position.theta == 90 \ or str_msg.data == "west" and goal_position.theta == 0: # we need to turn left command_list.append("turn_left") elif str_msg.data == "reset": print("Reset!!!!") reset_stage() return else: print("Invalid Command:" + str_msg.data) return # the robot has now been told to turn the correct way. Next, move. command_list.append("forward") def reset_stage(): global goal_position, current_position, current_cmd, start_position global command_list print("Resetting Stage") reset_positions = rospy.ServiceProxy('reset_positions', Empty) command_list = [] reset_positions() goal_position = deepcopy(start_position) current_cmd = "" def is_cmd_valid(str_cmd): global fwd_scan, rear_scan, r_scan, l_scan,off_right,off_left # check to ensure a given command (string) will not cause # the robot to move to an occupied vertex. if str_cmd == "forward": print("Trying to Move Forward", fwd_scan) print([fwd_scan, rear_scan, l_scan, r_scan]) return fwd_scan > 1.75 and off_right > 1.5 and off_left > 1.5 elif str_cmd == "turn_left" or str_cmd == "turn_right" or str_cmd == "turn_180": print("Turning in place") return True else: # not a valid command return False def set_cmd(str_cmd): # interpret the command (string) and execute the given command. if str_cmd == "forward": set_goal(1,0) elif str_cmd == "turn_right": set_goal(0,-90) elif str_cmd == "turn_left": set_goal(0,90) elif str_cmd == "turn_180": set_goal(0,180) def set_goal(forward, theta): global goal_position, current_position ## Check current heading relative to start ("forward"), # and apply the command to set a new goal position. # facing forward (north) if(goal_position.theta == 0.0): goal_position.x += forward goal_position.theta += theta # facing left (west) elif(goal_position.theta == 90.0): goal_position.y += forward goal_position.theta += theta # facing backward (south) elif(abs(goal_position.theta) == 180.0): goal_position.x -= forward goal_position.theta += theta # facing right (east) elif(goal_position.theta == 270.0): goal_position.y -= forward goal_position.theta += theta # normalize angle to be in range 0 to 360 goal_position.theta = goal_position.theta % 360 if(goal_position.theta < 0): goal_position.theta += 360 def execute_goal(event): global initvar, current_position, goal_position, integral_prior_forward,integral_prior_angle, error_prior_forward, error_prior_angle, iteration_time, command_list,current_cmd global start_position # check how far off the robot is from the goal position and heading delta_theta = goal_position.theta - current_position.theta # initialize with the current position as the goal. if(initvar): initvar = False goal_position = deepcopy(current_position) start_position = deepcopy(current_position) # if the robot is within 0.1 units of the goal in both x and y # and within 5 degrees, get the next command. # robot is facing (or is turning to face) south or north if(abs(goal_position.theta) == 180 or goal_position.theta == 0): forward = goal_position.x - current_position.x if (abs(goal_position.theta) == 180): forward *= -1 # robot is facing (or is turning to face) east or west else: forward = goal_position.y - current_position.y if (goal_position.theta == 270): # facing east forward *= -1\ # shift angles to be in the range -180 to 180 if(delta_theta < -180): delta_theta += 360 elif(delta_theta > 180): delta_theta -= 360 integral_prior_forward = integral_prior_forward + forward*iteration_time integral_prior_angle = integral_prior_angle + delta_theta*iteration_time fw_pid = forward*7+ integral_prior_forward*.15 + (forward - error_prior_forward)/iteration_time * .04 an_pid = delta_theta*.1+ integral_prior_angle*0+ (delta_theta - error_prior_angle)/iteration_time * 0 if(current_cmd == "forward"): send_cmd(fw_pid,0) else: send_cmd(0,an_pid) error_prior_forward = forward error_prior_angle = delta_theta finish_msg = Bool() finish_msg.data = False # if we are moving forward, check that we have basically arrived at the desired location. # if we are turning, check that we have basically gotten onto the desired heading. if((current_cmd == "forward" and abs(fw_pid) < .05) or (current_cmd != "forward" and abs(an_pid) < .05)): # check if we should request another command if len(command_list) < 2: request_cmd() # if current_cmd == "forward": # print("switching") # finish_msg.data = True # check if there are any commands in the queue. if(len(command_list) > 0 ): # pop the next command off the queue and if it's valid, set it to run next. #print(command_list) next_cmd = command_list.pop(0) print(current_cmd) current_cmd = next_cmd if is_cmd_valid(next_cmd): set_cmd(next_cmd) integral_prior_forward = 0 integral_prior_angle = 0 error_prior_forward = 0 error_prior_angle = 0 finish_pub.publish(finish_msg) def send_cmd(fwd_spd, turn_spd): # x-direction is forward. lin_vel = Vector3(fwd_spd, 0, 0) # turn around z-axis to stay within xy-plane. ang_vel = Vector3(0, 0, turn_spd) cmd.linear = lin_vel cmd.angular = ang_vel command_pub.publish(cmd) def request_cmd(): # request a command from the agent req_msg = Bool() req_msg.data = True req_pub.publish(req_msg) def main(): global command_pub, scan_pub, req_pub, iteration_time, finish_pub # initialize node. rospy.init_node('control_node') # publish command to the turtlebot. command_pub = rospy.Publisher("/cmd_vel", Twist, queue_size=1) # publish scan data to custom topic '/tp/scan' for agents to use as input. # format is [fwd_scan, rear_scan, l45_scan, l_scan, r45_scan, r_scan]. scan_pub = rospy.Publisher("/tp/scan", Int32MultiArray, queue_size=1) # publish to a custom topic '/tp/request' to let the agent know we are ready for another command. req_pub = rospy.Publisher('/tp/request', Bool, queue_size=1) finish_pub = rospy.Publisher('/tp/finish', Bool, queue_size=1) # subscribe to the lidar scan values. rospy.Subscriber('/scan', LaserScan, check_scan, queue_size=3) # subscribe to custom topic /tp/cmd which is used for discrete commands. rospy.Subscriber('/tp/cmd', String, add_cmd, queue_size=1) # subscrive to odometry info. rospy.Subscriber('/odom', Odometry, check_odom, queue_size=1) # execute commands at 1/iteration_time Hz. rospy.Timer(rospy.Duration(iteration_time), execute_goal) # pump callbacks. rospy.spin() if __name__ == '__main__': try: main() except rospy.ROSInterruptException: pass
/* * Copyright 2016 Red Hat Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ 'use strict'; const test = require('blue-tape'); const admin = require('./utils/realm'); const TestVector = require('./utils/helper').TestVector; const page = require('./utils/webdriver').newPage; const realmAccountPage = require('./utils/webdriver').realmAccountPage; const driver = require('./utils/webdriver').driver; const NodeApp = require('./fixtures/node-console/index').NodeApp; const session = require('express-session'); const realmManager = admin.createRealm(); const app = new NodeApp(); test('setup', t => { return realmManager.then(() => { return admin.createClient(app.publicClient()) .then((installation) => { return app.build(installation); }); }); }); // test('setup', t => { // return client = realmManager.then((realm) => { // return admin.createClient(app.publicClient()); // }); // }); test('Should be able to access public page', t => { t.plan(1); return page.get(app.port) .then(() => page.output().getText() .then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); }) ); }); test('Should login with admin credentials', t => { t.plan(3); return page.get(app.port) .then(() => page.output().getText() .then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); return page.logInButton() .then(webElement => webElement.click()) .then(() => page.login('test-admin', 'password')) .then(() => page.events().getText().then(text => { t.equal(text, 'Auth Success', 'User should be authenticated'); return page.logOutButton() .then(webElement => webElement.click()) .then(() => page.output().getText() .then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); }) ); })); }) ); }); test('Login should not change tokens when they are valid', t => { t.plan(3); return page.get(app.port).then(() => page.logInButton().click().then(() => page.login('test-admin', 'password').then(() => page.events().getText().then(text => { t.equal(text, 'Auth Success', 'User should be authenticated'); return page.output().getText().then(firstToken => page.logInButton().click().then( // Invoke login for the second time, token shouldn't be changed page.output().getText().then(secondToken => { t.equal(secondToken, firstToken, 'Token should not be changed as first session is still valid'); page.logOutButton().click(); return page.output().getText().then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); }); }) ) ); }) ) ) ); }); test('SSO should work for nodejs app and testRealmAccountPage', t => { return page.get(app.port).then(() => page.logInButton().click().then(() => page.login('test-admin', 'password').then(() => page.events().getText().then(text => { t.equal(text, 'Auth Success', 'User should be authenticated'); return realmAccountPage.get().then(() => driver.getCurrentUrl().then(currentUrl => { t.equal(currentUrl, realmAccountPage.getUrl(), 'Should be on account page'); return realmAccountPage.logout().then(() => driver.getCurrentUrl().then(currentUrl => { t.true(currentUrl.startsWith('http://127.0.0.1:8080/auth/realms/test-realm/protocol/openid-connect/auth'), 'Should be on login page after AccountPage logout, current url: ' + currentUrl); return page.get(app.port, '/login').then(() => t.true(currentUrl.startsWith('http://127.0.0.1:8080/auth/realms/test-realm/protocol/openid-connect/auth'), 'Should be on login page, current url: ' + currentUrl) ); }) ); }) ); }) ) ) ); }); test('Public client should be redirected to GitHub when idpHint is provided', t => { t.plan(1); var app = new NodeApp(); var client = admin.createClient(app.publicClient('appIdP')); return client.then((installation) => { app.build(installation, { store: new session.MemoryStore(), idpHint: 'github' }); return page.get(app.port, '/restricted') .then(() => page.h1().getText().then(text => { t.equal(text, 'Sign in to GitHub', 'Application should redirect to GitHub'); }) ).then(() => { app.destroy(); }).catch(err => { app.destroy(); throw err; }); }); }); test('User should be forbidden to access restricted page', t => { return page.get(app.port, '/restricted').then(() => page.login('alice', 'password').then(() => page.body().getText().then(text => { t.equal(text, 'Access denied', 'Message should be access denied'); return page.logout(app.port); // we need to wait a bit until the logout is fully completed }) ) ); }); test('Public client should be forbidden for invalid public key', t => { t.plan(2); var app = new NodeApp(); var client = admin.createClient(app.publicClient('app2')); return client.then((installation) => { installation['realm-public-key'] = TestVector.wrongRealmPublicKey; app.build(installation); return page.get(app.port).then(() => page.output().getText().then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); return page.logInButton().click().then(() => page.login('test-admin', 'password').then(() => page.body().getText().then(text => { t.equal(text, 'Access denied', 'Message should be access denied'); }) ) ); }) ).then(() => { app.destroy(); }).catch(err => { app.destroy(); throw err; }); }); }); test('Confidential client should be forbidden for invalid public key', t => { t.plan(3); var app = new NodeApp(); var client = admin.createClient(app.confidential('app3')); return client.then((installation) => { installation['realm-public-key'] = TestVector.wrongRealmPublicKey; app.build(installation); return page.get(app.port).then(() => page.output().getText().then(text => { t.equal(text, 'Init Success (Not Authenticated)', 'User should not be authenticated'); return page.logInButton().click().then(() => page.body().getText().then(text => { t.equal(text, 'Access denied', 'Message should be access denied'); }) .then(() => page.logout(app.port)) .then(() => page.get(app.port, '/check-sso')) .then(() => page.output().getText().then(text => t.equal(text, 'Check SSO Success (Not Authenticated)', 'User should not be authenticated'))) ); }) ).then(() => { app.destroy(); }).catch(err => { app.destroy(); throw err; }); }); }); test('Should test check SSO after logging in and logging out', t => { t.plan(3); // make sure user is logged out page.get(app.port, '/check-sso').then(() => page.output().getText().then(text => { t.equal(text, 'Check SSO Success (Not Authenticated)', 'User should not be authenticated'); page.logInButton().click().then(() => page.login('alice', 'password').then(() => page.get(app.port, '/check-sso').then(() => page.output().getText().then(text => { t.equal(text, 'Check SSO Success (Authenticated)', 'User should be authenticated'); return page.logout(app.port); }).then(() => { page.get(app.port, '/check-sso').then(() => page.output().getText().then(text => { t.equal(text, 'Check SSO Success (Not Authenticated)', 'User should not be authenticated'); }) ); }) ) ) ); }) ); }); test('teardown', t => { return realmManager.then((realm) => { app.destroy(); admin.destroy('test-realm'); page.quit(); }); });
import list from "./ordersListReducers"; import form from "./ordersFormReducers"; import { combineReducers } from "redux"; export default combineReducers({ list, form, });
import React from "react"; import ReactDOM from "react-dom"; import Header from '../components/login/header.js' import Video from '../components/login/video.js' export default function App() { return ( <div> < Header /> < Video /> </div> ); } if (document.getElementById("login")) { ReactDOM.render(<App />, document.getElementById("login")); }
# coding: utf-8 from __future__ import division, print_function, unicode_literals, absolute_import from atomate.qchem.firetasks.run_calc import RunQChemFake __author__ = "Brandon Wood" __email__ = "[email protected]" def use_fake_qchem(original_wf, ref_dirs): """ Replaces all RunQChem commands (i.e. RunQChemDirect, RunQChemCustodian) with RunQChemFake. This allows for testing without actually running QChem Args: original_wf (Workflow) ref_dirs (dict): key=firework name, value=path to the reference QChem calculation directory Returns: Workflow """ for idx_fw, fw in enumerate(original_wf.fws): for job_type in ref_dirs.keys(): if job_type in fw.name: for idx_t, t in enumerate(fw.tasks): if "RunQChemCustodian" in str( t) or "RunQChemDirect" in str(t): original_wf.fws[idx_fw].tasks[idx_t] = RunQChemFake( ref_dir=ref_dirs[job_type]) return original_wf
'use strict'; /* globals describe, it, before, after */ import app from '../..'; import CandidateQuestion from '../../model/candidatequestions'; import User from '../user/user.model'; import request from 'supertest'; describe('Candidate Question API:', function() { var user, q1, q2, q3; // Clear users before testing before(function() { return User.remove().then(function() { user = new User({ name: 'Fake User', email: '[email protected]', role: 'anystring', password: 'password' }); return user.save(); }); }); // Clear users after testing after(function() { return User.remove(); }); // Clear candidate questions before testing before(function() { return CandidateQuestion.remove() .then(function() { q1 = new CandidateQuestion({ questionText: 'What is the...?', responseChoices: ['yes', 'no', 'maybeso'] }); return q1.save(); }) .then(function() { q2 = new CandidateQuestion({ questionText: 'How would you place...?', responseChoices: ['yes', 'no', 'maybeso'] }); return q2.save(); }) .then(function() { q3 = new CandidateQuestion({ questionText: 'Do you think the candidate....?', responseChoices: ['yes', 'no', 'maybeso'] }); return q3.save(); }); }); // Clear candidate questions and user after testing after(function() { return CandidateQuestion.remove(); }); describe('GET /api/CandidateQuestions', function() { var token; before(function(done) { request(app) .post('/auth/local') .send({ email: '[email protected]', password: 'password' }) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) { throw err; } token = res.body.token; done(); }); }); it('should respond with the list of candidate questions when authenticated', function(done) { request(app) .get('/api/CandidateQuestions') .set('authorization', `Bearer ${token}`) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) throw err; res.body.length.should.equal(3); done(); }); }); it('should respond with a 401 when not authenticated', function(done) { request(app) .get('/api/CandidateQuestions') .expect(401) .end(done); }); }); describe('POST /api/CandidateQuestion', function() { var token; before(function(done) { request(app) .post('/auth/local') .send({ email: '[email protected]', password: 'password' }) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) { throw err; } token = res.body.token; done(); }); }); it('should create the candidate question when authenticated', function(done) { request(app) .post('/api/CandidateQuestion') .set('authorization', `Bearer ${token}`) .send({ questionText: 'dgqerhqeDescribe blah blah blah...', responseChoices: ['1', '2'] }) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) throw err; res.body.questionText.should.equal('dgqerhqeDescribe blah blah blah...'); res.body.responseChoices[0].should.equal('1'); res.body.responseChoices[1].should.equal('2'); done(); }); }); it('should respond with a 401 when not authenticated', function(done) { request(app) .post('/api/CandidateQuestion') .expect(401) .end(done); }); }); describe('DELETE /api/CandidateQuestion/:id', function() { var token; before(function(done) { request(app) .post('/auth/local') .send({ email: '[email protected]', password: 'password' }) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) { throw err; } token = res.body.token; done(); }); }); it('should delete the specified candidate question when authenticated', function(done) { console.log(q1); request(app) .delete(`/api/CandidateQuestion/${q1._id}`) .set('authorization', `Bearer ${token}`) .expect(200) .expect('Content-Type', /json/) .end((err, res) => { if(err) throw err; res.body.ok.should.equal(1); done(); }); }); it('should respond with a 401 when not authenticated', function(done) { request(app) .delete(`/api/CandidateQuestion/${q1._id}`) .expect(401) .end(done); }); }); });
parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"../../../moduleWrappers/powercord/global/commands.js":[function(require,module,exports) { "use strict";function e(e,n){return a(e)||o(e,n)||t(e,n)||r()}function r(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function t(e,r){if(e){if("string"==typeof e)return n(e,r);var t=Object.prototype.toString.call(e).slice(8,-1);return"Object"===t&&e.constructor&&(t=e.constructor.name),"Map"===t||"Set"===t?Array.from(e):"Arguments"===t||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t)?n(e,r):void 0}}function n(e,r){(null==r||r>e.length)&&(r=e.length);for(var t=0,n=new Array(r);t<r;t++)n[t]=e[t];return n}function o(e,r){var t=null==e?null:"undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(null!=t){var n,o,a=[],s=!0,i=!1;try{for(t=t.call(e);!(s=(n=t.next()).done)&&(a.push(n.value),!r||a.length!==r);s=!0);}catch(u){i=!0,o=u}finally{try{s||null==t.return||t.return()}finally{if(i)throw o}}return a}}function a(e){if(Array.isArray(e))return e}function s(e,r,t,n,o,a,s){try{var i=e[a](s),u=i.value}catch(c){return void t(c)}i.done?r(u):Promise.resolve(u).then(n,o)}function i(e){return function(){var r=this,t=arguments;return new Promise(function(n,o){var a=e.apply(r,t);function i(e){s(a,n,o,i,u,"next",e)}function u(e){s(a,n,o,i,u,"throw",e)}i(void 0)})}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.unregisterCommand=exports.registerCommand=void 0;var u=goosemodScope.webpackModules.findByProps("sendMessage","receiveMessage").sendMessage,c=goosemodScope.webpackModules.findByProps("getChannelId").getChannelId,l=function(r){var t=r.command,n=(r.alias,r.description),o=(r.usage,r.executor);goosemodScope.patcher.commands.add(t,n,function(){var r=i(regeneratorRuntime.mark(function r(t){var n,a,s,i;return regeneratorRuntime.wrap(function(r){for(;;)switch(r.prev=r.next){case 0:return n="",t.args&&(a=e(t.args,1),s=a[0].text,n=s),r.next=4,o(n.split(" "));case 4:if((i=r.sent).send){r.next=8;break}return goosemodScope.patcher.internalMessage(i.result),r.abrupt("return");case 8:u(c(),{content:i.result,tts:!1,invalidEmojis:[],validNonShortcutEmojis:[]});case 9:case"end":return r.stop()}},r)}));return function(e){return r.apply(this,arguments)}}(),[{type:3,required:!1,name:"args",description:"Arguments for PC command"}])};exports.registerCommand=l;var d=function(e){goosemodScope.patcher.commands.remove(e)};exports.unregisterCommand=d; },{}],"../../../moduleWrappers/powercord/global/notices.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.sendToast=void 0;var e=function(e,o){o.header;var t=o.content;o.type,o.buttons;goosemodScope.showToast(t)};exports.sendToast=e; },{}],"../../../moduleWrappers/powercord/util/settings.js":[function(require,module,exports) { "use strict";function t(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function e(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}Object.defineProperty(exports,"__esModule",{value:!0}),exports.makeStore=exports.settingStores=void 0;var r={};exports.settingStores=r;var n=function(t){r[t]=new o};exports.makeStore=n;var o=function r(){var n=this;t(this,r),e(this,"getSetting",function(t,e){var r;return null!==(r=n.store[t])&&void 0!==r?r:e}),e(this,"updateSetting",function(t,e){return void 0===e?n.toggleSetting(t):(n.store[t]=e,n.store[t])}),e(this,"toggleSetting",function(t){return n.store[t]=!n.store[t],n.store[t]}),e(this,"deleteSetting",function(t){delete n.store[t]}),e(this,"getKeys",function(){return Object.keys(n.store)}),this.store={}}; },{}],"../../../moduleWrappers/powercord/global/settings.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.unregisterSettings=exports.registerSettings=void 0;var e=r(require("../util/settings"));function t(e){if("function"!=typeof WeakMap)return null;var r=new WeakMap,n=new WeakMap;return(t=function(e){return e?n:r})(e)}function r(e,r){if(!r&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=t(r);if(n&&n.has(e))return n.get(e);var o={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var c in e)if("default"!==c&&Object.prototype.hasOwnProperty.call(e,c)){var a=i?Object.getOwnPropertyDescriptor(e,c):null;a&&(a.get||a.set)?Object.defineProperty(o,c,a):o[c]=e[c]}return o.default=e,n&&n.set(e,o),o}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach(function(t){i(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function i(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}var c=function(t,r){var n=r.label,i=r.render,c=r.category,a=goosemodScope.webpackModules.common.React,u=goosemodScope.webpackModules.findByDisplayName("SettingsView"),s=goosemodScope.webpackModules.findByDisplayName("FormTitle"),p=goosemodScope.webpackModules.findByDisplayName("FormSection");e.settingStores[c]||e.makeStore(c),goosemodScope.patcher.inject(t,u.prototype,"getPredicateSections",function(t,r){var u=r.find(function(e){return"logout"===e.section});if(!u)return r;var f="function"==typeof n?n():n;return r.splice(r.indexOf(u)-1,0,{section:f,label:f,predicate:function(){},element:function(){return a.createElement(p,{},a.createElement(s,{tag:"h2"},f),a.createElement(i,o({},e.settingStores[c])))}}),r})};exports.registerSettings=c;var a=function(e){goosemodScope.patcher.uninject(e)};exports.unregisterSettings=a; },{"../util/settings":"../../../moduleWrappers/powercord/util/settings.js"}],"../../../moduleWrappers/powercord/global/index.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=o(require("./commands.js")),t=o(require("./notices.js")),r=o(require("./settings.js"));function n(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(n=function(e){return e?r:t})(e)}function o(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=n(t);if(r&&r.has(e))return r.get(e);var o={},u=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in e)if("default"!==i&&Object.prototype.hasOwnProperty.call(e,i)){var a=u?Object.getOwnPropertyDescriptor(e,i):null;a&&(a.get||a.set)?Object.defineProperty(o,i,a):o[i]=e[i]}return o.default=e,r&&r.set(e,o),o}var u={api:{commands:e,notices:t,settings:r}};exports.default=u; },{"./commands.js":"../../../moduleWrappers/powercord/global/commands.js","./notices.js":"../../../moduleWrappers/powercord/global/notices.js","./settings.js":"../../../moduleWrappers/powercord/global/settings.js"}],"../../../moduleWrappers/powercord/entities.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.Plugin=void 0;var e=n(require("./util/settings"));function t(e){if("function"!=typeof WeakMap)return null;var n=new WeakMap,r=new WeakMap;return(t=function(e){return e?r:n})(e)}function n(e,n){if(!n&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=t(n);if(r&&r.has(e))return r.get(e);var i={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var u=o?Object.getOwnPropertyDescriptor(e,s):null;u&&(u.get||u.set)?Object.defineProperty(i,s,u):i[s]=e[s]}return i.default=e,r&&r.set(e,i),i}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function o(e,t,n){return t&&i(e.prototype,t),n&&i(e,n),e}var s=function(){function t(){r(this,t),this.stylesheets=[]}return o(t,[{key:"loadStylesheet",value:function(e){var t=document.createElement("style");t.appendChild(document.createTextNode(e)),document.head.appendChild(t),this.stylesheets.push(t)}},{key:"manifest",get:function(){return{name:this.name,description:this.description,version:this.version,author:this.authors.toString(),license:"Unknown"}}},{key:"entityID",get:function(){return this.name}},{key:"settings",get:function(){var t=e.settingStores[this.entityID];return{get:t.getSetting,set:t.updateSetting,delete:t.deleteSetting,getKeys:t.getKeys,connectStore:function(){}}}},{key:"goosemodHandlers",get:function(){var t=this;return{onImport:function(){e.makeStore(t.entityID),t.startPlugin.bind(t)()},onRemove:function(){t.stylesheets.forEach(function(e){return e.remove()}),t.pluginWillUnload.bind(t)()},getSettings:function(){return e.settingStores[t.entityID].store},loadSettings:function(n){return e.settingStores[t.entityID].store=n||{}}}}}]),t}();exports.Plugin=s; },{"./util/settings":"../../../moduleWrappers/powercord/util/settings.js"}],"../../../moduleWrappers/powercord/components/settings/divider.js":[function(require,module,exports) { "use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,t,r){return t&&o(e.prototype,t),r&&o(e,r),e}function n(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&u(e,t)}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function c(e){var t=l();return function(){var o,r=a(e);if(t){var n=a(this).constructor;o=Reflect.construct(r,arguments,n)}else o=r.apply(this,arguments);return i(this,o)}}function i(t,o){if(o&&("object"===e(o)||"function"==typeof o))return o;if(void 0!==o)throw new TypeError("Derived constructors may only return object or undefined");return f(t)}function f(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function l(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var p=goosemodScope.webpackModules.common.React,s=goosemodScope.webpackModules.findByDisplayName("FormDivider"),y=goosemodScope.webpackModules.findByProps("dividerDefault","titleDefault"),d=function(e){n(u,p.PureComponent);var o=c(u);function u(){return t(this,u),o.apply(this,arguments)}return r(u,[{key:"render",value:function(){return p.createElement(s,{className:y.dividerDefault})}}]),u}();exports.default=d; },{}],"../../../moduleWrappers/powercord/components/settings/formItem.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("./divider"));function t(e){return e&&e.__esModule?e:{default:e}}function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,o){return t&&n(e.prototype,t),o&&n(e,o),e}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&u(e,t)}function u(e,t){return(u=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function s(e){var t=a();return function(){var o,r=l(e);if(t){var n=l(this).constructor;o=Reflect.construct(r,arguments,n)}else o=r.apply(this,arguments);return f(this,o)}}function f(e,t){if(t&&("object"===o(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return p(e)}function p(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function a(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function l(e){return(l=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var y=goosemodScope.webpackModules.common.React,d=goosemodScope.webpackModules.findByDisplayName("FormItem"),m=goosemodScope.webpackModules.findByDisplayName("FormText"),b=goosemodScope.webpackModules.findByDisplayName("Flex"),h=goosemodScope.webpackModules.findByProps("marginTop20","marginBottom20"),v=goosemodScope.webpackModules.findByProps("formText","description"),g=function(t){c(n,y.PureComponent);var o=s(n);function n(){return r(this,n),o.apply(this,arguments)}return i(n,[{key:"render",value:function(){var t=this;return y.createElement(d,{title:this.props.title,required:this.props.required,className:[b.Direction.VERTICAL,b.Justify.START,b.Align.STRETCH,b.Wrap.NO_WRAP,h.marginBottom20].join(" "),onClick:function(){t.props.onClick()}},this.props.children,this.props.note&&y.createElement(m,{className:v.description+(this.props.noteHasMargin?" "+h.marginTop8:"")},this.props.note),y.createElement(e.default))}}]),n}();exports.default=g; },{"./divider":"../../../moduleWrappers/powercord/components/settings/divider.js"}],"../../../moduleWrappers/powercord/components/settings/textInput.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("./formItem"));function t(e){return e&&e.__esModule?e:{default:e}}function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function n(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function o(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?n(Object(r),!0).forEach(function(t){c(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):n(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function c(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function f(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),e}function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&l(e,t)}function l(e,t){return(l=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e){var t=b();return function(){var r,n=d(e);if(t){var o=d(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return s(this,r)}}function s(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return y(e)}function y(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function b(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function d(e){return(d=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var O=goosemodScope.webpackModules.common.React,h=goosemodScope.webpackModules.findByDisplayName("TextInput"),m=function(t){p(n,O.PureComponent);var r=a(n);function n(){return u(this,n),r.apply(this,arguments)}return f(n,[{key:"render",value:function(){var t=this.props.children;return delete this.props.children,O.createElement(e.default,{title:t,note:this.props.note,required:this.props.required,noteHasMargin:!0},O.createElement(h,o({},this.props)))}}]),n}();exports.default=m; },{"./formItem":"../../../moduleWrappers/powercord/components/settings/formItem.js"}],"../../../moduleWrappers/powercord/components/settings/sliderInput.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("./formItem"));function t(e){return e&&e.__esModule?e:{default:e}}function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);t&&(o=o.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,o)}return r}function n(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?o(Object(r),!0).forEach(function(t){c(e,t,r[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))})}return e}function c(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function f(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),e}function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&s(e,t)}function s(e,t){return(s=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e){var t=b();return function(){var r,o=d(e);if(t){var n=d(this).constructor;r=Reflect.construct(o,arguments,n)}else r=o.apply(this,arguments);return l(this,r)}}function l(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return y(e)}function y(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function b(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function d(e){return(d=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var m=goosemodScope.webpackModules.common.React,O=goosemodScope.webpackModules.findByDisplayName("Slider"),h=goosemodScope.webpackModules.findByProps("marginTop20","marginBottom20"),v=function(t){p(o,m.PureComponent);var r=a(o);function o(){return u(this,o),r.apply(this,arguments)}return f(o,[{key:"render",value:function(){var t=this.props.children;return delete this.props.children,m.createElement(e.default,{title:t,note:this.props.note,required:this.props.required},m.createElement(O,n(n({},this.props),{},{className:h.marginTop20+(this.props.className?" "+this.props.className:"")})))}}]),o}();exports.default=v; },{"./formItem":"../../../moduleWrappers/powercord/components/settings/formItem.js"}],"../../../moduleWrappers/powercord/components/settings/buttonItem.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=o(require("./divider"));function o(e){return e&&e.__esModule?e:{default:e}}function t(e){return(t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,o){if(!(e instanceof o))throw new TypeError("Cannot call a class as a function")}function n(e,o){for(var t=0;t<o.length;t++){var r=o[t];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,o,t){return o&&n(e.prototype,o),t&&n(e,t),e}function c(e,o){if("function"!=typeof o&&null!==o)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(o&&o.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),o&&s(e,o)}function s(e,o){return(s=Object.setPrototypeOf||function(e,o){return e.__proto__=o,e})(e,o)}function l(e){var o=a();return function(){var t,r=f(e);if(o){var n=f(this).constructor;t=Reflect.construct(r,arguments,n)}else t=r.apply(this,arguments);return u(this,t)}}function u(e,o){if(o&&("object"===t(o)||"function"==typeof o))return o;if(void 0!==o)throw new TypeError("Derived constructors may only return object or undefined");return p(e)}function p(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function a(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function f(e){return(f=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var d=goosemodScope.webpackModules.common.React,y=goosemodScope.webpackModules.findByProps("Sizes","Colors","Looks","DropdownSizes"),m=goosemodScope.webpackModules.findByDisplayName("FormItem"),b=goosemodScope.webpackModules.findByDisplayName("FormText"),h=goosemodScope.webpackModules.findByDisplayName("Flex"),v=goosemodScope.webpackModules.findByProps("marginTop20","marginBottom20"),w=goosemodScope.webpackModules.findByProps("title","dividerDefault"),S=goosemodScope.webpackModules.findByProps("formText","placeholder"),g=goosemodScope.webpackModules.findByDisplayName("Tooltip"),E=function(o){c(n,d.PureComponent);var t=l(n);function n(){return r(this,n),t.apply(this,arguments)}return i(n,[{key:"render",value:function(){var o=this,t=this.props.children;return delete this.props.children,d.createElement(m,{className:[h.Direction.VERTICAL,h.Justify.START,h.Align.STRETCH,h.Wrap.NO_WRAP,v.marginBottom20].join(" ")},d.createElement("div",{style:{display:"flex",justifyContent:"space-between"}},d.createElement("div",{},d.createElement("div",{className:w.labelRow,style:{marginBottom:"4px"}},d.createElement("label",{class:w.title},t)),d.createElement(b,{className:S.description},this.props.note)),d.createElement(g,{text:this.props.tooltipText,position:this.props.tooltipPosition,shouldShow:""!==this.props.tooltipText},function(){return d.createElement(y,{color:o.props.success?y.Colors.GREEN:o.props.color||y.Colors.BRAND,disabled:o.props.disabled,onClick:function(){return o.props.onClick()}},o.props.button)})),d.createElement(e.default))}}]),n}();exports.default=E; },{"./divider":"../../../moduleWrappers/powercord/components/settings/divider.js"}],"../../../moduleWrappers/powercord/components/settings/category.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("./formItem"));function t(e){return e&&e.__esModule?e:{default:e}}function r(e){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function o(e){return u(e)||c(e)||i(e)||n()}function n(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function i(e,t){if(e){if("string"==typeof e)return a(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?a(e,t):void 0}}function c(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}function u(e){if(Array.isArray(e))return a(e)}function a(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,o=new Array(t);r<t;r++)o[r]=e[r];return o}function l(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function f(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}function p(e,t,r){return t&&f(e.prototype,t),r&&f(e,r),e}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&y(e,t)}function y(e,t){return(y=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function d(e){var t=h();return function(){var r,o=v(e);if(t){var n=v(this).constructor;r=Reflect.construct(o,arguments,n)}else r=o.apply(this,arguments);return m(this,r)}}function m(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return b(e)}function b(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function v(e){return(v=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}var g=goosemodScope.webpackModules.common.React,w=goosemodScope.webpackModules.findByProps("title","dividerDefault"),S=goosemodScope.webpackModules.findByProps("formText","placeholder"),O=goosemodScope.webpackModules.findByDisplayName("FormText"),j=function(t){s(n,g.PureComponent);var r=d(n);function n(){return l(this,n),r.apply(this,arguments)}return p(n,[{key:"render",value:function(){var t=this,r=this.props.opened?this.props.children:[];return g.createElement.apply(g,[e.default,{title:g.createElement("div",{},g.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",width:"24",height:"24",style:{transform:this.props.opened?"rotate(90deg)":"",marginRight:"10px"}},g.createElement("path",{fill:"var(--header-primary)",d:"M9.29 15.88L13.17 12 9.29 8.12c-.39-.39-.39-1.02 0-1.41.39-.39 1.02-.39 1.41 0l4.59 4.59c.39.39.39 1.02 0 1.41L10.7 17.3c-.39.39-1.02.39-1.41 0-.38-.39-.39-1.03 0-1.42z"})),g.createElement("label",{class:w.title,style:{textTransform:"none",display:"inline",verticalAlign:"top"}},this.props.name,g.createElement(O,{className:S.description,style:{marginLeft:"34px"}},this.props.description))),onClick:function(){t.props.onChange(!t.props.opened)}}].concat(o(r)))}}]),n}();exports.default=j; },{"./formItem":"../../../moduleWrappers/powercord/components/settings/formItem.js"}],"../../../moduleWrappers/powercord/components/settings/switchItem.js":[function(require,module,exports) { "use strict";function e(t){return(e="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(t)}function t(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),r.push.apply(r,n)}return r}function r(e){for(var r=1;r<arguments.length;r++){var o=null!=arguments[r]?arguments[r]:{};r%2?t(Object(o),!0).forEach(function(t){n(e,t,o[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(o)):t(Object(o)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(o,t))})}return e}function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function c(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}function u(e,t,r){return t&&c(e.prototype,t),r&&c(e,r),e}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&f(e,t)}function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function a(e){var t=s();return function(){var r,n=y(e);if(t){var o=y(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return p(this,r)}}function p(t,r){if(r&&("object"===e(r)||"function"==typeof r))return r;if(void 0!==r)throw new TypeError("Derived constructors may only return object or undefined");return l(t)}function l(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function y(e){return(y=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var b=goosemodScope.webpackModules.common.React,O=goosemodScope.webpackModules.findByDisplayName("SwitchItem"),d=function(e){i(n,b.Component);var t=a(n);function n(e){var r;o(this,n);var c=e.onChange;return e.onChange=function(e){c(e),r.props.value=e,r.forceUpdate()},r=t.call(this,e)}return u(n,[{key:"render",value:function(){return b.createElement(O,r({},this.props))}}]),n}();exports.default=d; },{}],"../../../moduleWrappers/powercord/components/settings/index.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"FormItem",{enumerable:!0,get:function(){return e.default}}),Object.defineProperty(exports,"TextInput",{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(exports,"SliderInput",{enumerable:!0,get:function(){return r.default}}),Object.defineProperty(exports,"Divider",{enumerable:!0,get:function(){return u.default}}),Object.defineProperty(exports,"ButtonItem",{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(exports,"Category",{enumerable:!0,get:function(){return i.default}}),Object.defineProperty(exports,"SwitchItem",{enumerable:!0,get:function(){return o.default}});var e=f(require("./formItem")),t=f(require("./textInput")),r=f(require("./sliderInput")),u=f(require("./divider")),n=f(require("./buttonItem")),i=f(require("./category")),o=f(require("./switchItem"));function f(e){return e&&e.__esModule?e:{default:e}} },{"./formItem":"../../../moduleWrappers/powercord/components/settings/formItem.js","./textInput":"../../../moduleWrappers/powercord/components/settings/textInput.js","./sliderInput":"../../../moduleWrappers/powercord/components/settings/sliderInput.js","./divider":"../../../moduleWrappers/powercord/components/settings/divider.js","./buttonItem":"../../../moduleWrappers/powercord/components/settings/buttonItem.js","./category":"../../../moduleWrappers/powercord/components/settings/category.js","./switchItem":"../../../moduleWrappers/powercord/components/settings/switchItem.js"}],"../../../moduleWrappers/powercord/webpack.js":[function(require,module,exports) { function e(e,r){var o=Object.keys(e);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(e);r&&(t=t.filter(function(r){return Object.getOwnPropertyDescriptor(e,r).enumerable})),o.push.apply(o,t)}return o}function r(r){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?e(Object(n),!0).forEach(function(e){o(r,e,n[e])}):Object.getOwnPropertyDescriptors?Object.defineProperties(r,Object.getOwnPropertyDescriptors(n)):e(Object(n)).forEach(function(e){Object.defineProperty(r,e,Object.getOwnPropertyDescriptor(n,e))})}return r}function o(e,r,o){return r in e?Object.defineProperty(e,r,{value:o,enumerable:!0,configurable:!0,writable:!0}):e[r]=o,e}var t=function(e){if(Array.isArray(e)){var r=e;e=function(e){return r.every(function(r){return e[r]||e.__proto__&&e.__proto__[r]})}}return e};module.exports=r({getModule:function(e,r,o){e=t(e);var n=goosemodScope.webpackModules.find(e);return r?new Promise(function(e){return e(n)}):n},getAllModules:function(e){return e=t(e),goosemodScope.webpackModules.findAll(e)},getModuleByDisplayName:function(e){return goosemodScope.webpackModules.find(function(r){return r.displayName&&r.displayName.toLowerCase()===e.toLowerCase()})}},goosemodScope.webpackModules.common); },{}],"../../../moduleWrappers/powercord/injector.js":[function(require,module,exports) { module.exports=goosemodScope.patcher; },{}],"index.js":[function(require,module,exports) { "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var e=t(require("_powercord/global"));function t(e){return e&&e.__esModule?e:{default:e}}function o(e){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function n(e,t){for(var o=0;o<t.length;o++){var r=t[o];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function i(e,t,o){return t&&n(e.prototype,t),o&&n(e,o),e}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&c(e,t)}function c(e,t){return(c=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function p(e){var t=f();return function(){var o,r=a(e);if(t){var n=a(this).constructor;o=Reflect.construct(r,arguments,n)}else o=r.apply(this,arguments);return l(this,o)}}function l(e,t){if(t&&("object"===o(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return s(e)}function s(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function f(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(e){return!1}}function a(e){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}require.cache["powercord/entities"]=require("powercord/entities"),require.cache["powercord/components/settings"]=require("powercord/components/settings"),require.cache["powercord/webpack"]=require("powercord/webpack");var d=require("powercord/entities"),y=d.Plugin,v=require("powercord/webpack"),h=v.getModule,w=require("powercord/injector"),b=w.inject,m=w.uninject,g=new(function(e){u(o,y);var t=p(o);function o(){return r(this,o),t.apply(this,arguments)}return i(o,[{key:"startPlugin",value:function(){var e=h(function(e){return e.type&&"MessageContent"==e.type.displayName},!1);b("open-in-app",e,"type",this.openInApp),e.type.displayName="MessageContent"}},{key:"openInApp",value:function(e,t){return t.props.children.find(function(e){return Array.isArray(e)}).forEach(function(e){var t,o,r,n,i,u,c,p,l,s,f,a;null!==(t=e.props)&&void 0!==t&&null!==(o=t.href)&&void 0!==o&&o.toLowerCase().includes("open.spotify.com")?e.props.href="spotify:".concat(e.props.title):null!==(r=e.props)&&void 0!==r&&null!==(n=r.href)&&void 0!==n&&n.toLowerCase().includes("store.steampowered.com")||null!==(i=e.props)&&void 0!==i&&null!==(u=i.href)&&void 0!==u&&u.toLowerCase().includes("steamcommunity.com")||null!==(c=e.props)&&void 0!==c&&null!==(p=c.href)&&void 0!==p&&p.toLowerCase().includes("help.steampowered.com")?e.props.href="steam://openurl/".concat(e.props.title):(null!==(l=e.props)&&void 0!==l&&null!==(s=l.href)&&void 0!==s&&s.toLowerCase().includes("tidal.com")||null!==(f=e.props)&&void 0!==f&&null!==(a=f.href)&&void 0!==a&&a.toLowerCase().includes("listen.tidal.com"))&&(e.props.href="tidal://".concat(e.props.title))}),t}},{key:"pluginWillUnload",value:function(){m("open-in-app")}}]),o}());exports.default=g; },{"_powercord/global":"../../../moduleWrappers/powercord/global/index.js","powercord/entities":"../../../moduleWrappers/powercord/entities.js","powercord/components/settings":"../../../moduleWrappers/powercord/components/settings/index.js","powercord/webpack":"../../../moduleWrappers/powercord/webpack.js","powercord/injector":"../../../moduleWrappers/powercord/injector.js"}]},{},["index.js"], null);parcelRequire('index.js').default
import React, {useEffect, useState, useContext} from 'react'; import { Text, Image, View, ScrollView, SafeAreaView, Button, StyleSheet } from 'react-native'; import { getProduct } from '../services/ProductsService.js'; import { CartContext } from '../CartContext'; export function ProductDetails({route}) { const { productId } = route.params; const [product, setProduct] = useState({}); const { addItemToCart } = useContext(CartContext); useEffect(() => { setProduct(getProduct(productId)); }); function onAddToCart() { addItemToCart(product.id); } return ( <SafeAreaView> <ScrollView> <Image style={styles.image} source={product.image} /> <View style={styles.infoContainer}> <Text style={styles.name}>{product.name}</Text> <Text style={styles.price}>AED {product.price} / {product.unit}</Text> <Text style={styles.description}>{product.description}</Text> <Button onPress={onAddToCart} title="Add to cart" / > </View> </ScrollView> </SafeAreaView> ); } const styles = StyleSheet.create({ card: { backgroundColor: 'white', borderRadius: 16, shadowOpacity: 0.2, shadowRadius: 4, shadowColor: 'black', shadowOffset: { height: 0, width: 0, }, elevation: 1, marginVertical: 20, }, image: { height: 300, width: '100%' }, infoContainer: { padding: 16, }, name: { fontSize: 22, fontWeight: 'bold', }, price: { fontSize: 16, fontWeight: '600', marginBottom: 8, }, description: { fontSize: 16, fontWeight: '400', color: '#787878', marginBottom: 16, }, });
import React from 'react'; import Layout from '../components/layout'; import { graphql } from 'gatsby'; import { useForm } from 'react-hook-form'; import { useNetlifyForm, NetlifyFormProvider, NetlifyFormComponent, Honeypot, } from 'react-netlify-forms'; import styled from 'styled-components'; const ContactTemplate = ({ data }) => { const { html, frontmatter } = data.markdownRemark; return ( <Layout title={frontmatter.title}> <ContactWrapper> <ContactCopy dangerouslySetInnerHTML={{ __html: html }} /> <ContactForm /> </ContactWrapper> </Layout> ); }; export default ContactTemplate; const ContactForm = () => { const { register, handleSubmit, errors } = useForm(); const netlify = useNetlifyForm({ name: 'Contact', action: '/thanks', honeypotName: 'bot-field', }); const onSubmit = (data) => { netlify.handleSubmit(null, data); console.log(data); }; return ( <FormWrapper> <NetlifyFormProvider {...netlify}> <NetlifyFormComponent onSubmit={handleSubmit(onSubmit)}> <Honeypot /> <FormGroup> <label htmlFor="name">Имя</label> <input id="name" name="name" type="text" ref={register({ required: 'Без имени никуда.' })} /> {errors.name && ( <FormErrorMessage>{errors.name.message}</FormErrorMessage> )} </FormGroup> <FormGroup> <label htmlFor="email">Почта</label> <input id="email" name="email" type="text" ref={register({ required: 'Без почты никак.', pattern: { message: 'Не похоже на почту.', value: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/, }, })} /> {errors.email && ( <FormErrorMessage>{errors.email.message}</FormErrorMessage> )} </FormGroup> <FormGroup> <label htmlFor="message">Сообщение</label> <textarea id="message" name="message" rows="4" ref={register({ required: 'Без сообщения и слать нечего.' })} /> {errors.message && ( <FormErrorMessage>{errors.message.message}</FormErrorMessage> )} </FormGroup> <FormFeedbackWrapper> {netlify.success && ( <FormSucessFeedback>Message sent succesfully</FormSucessFeedback> )} {netlify.error && ( <FormErrorFeedback> Что-то не сработало. Попробуйте еще раз. </FormErrorFeedback> )} </FormFeedbackWrapper> <FormButton type="submit">Отправить</FormButton> </NetlifyFormComponent> </NetlifyFormProvider> </FormWrapper> ); }; const ContactWrapper = styled.div` display: flex; align-items: center; height: 100%; justify-content: space-around; margin-top: 1rem; padding-bottom: 1rem; & > * { flex: 1; } @media screen and (max-width: 1000px) { & { flex-direction: column; justify-content: flex-start; } & > * { margin-top: 2rem; flex: 0; width: 100%; } } `; const ContactCopy = styled.div` max-width: 45ch; & p { font-size: var(--size-400); } `; const FormWrapper = styled.div` max-width: 45ch; padding: 1rem; padding-top: 0; border-radius: 4px; border: 1px solid rgba(255, 255, 255, 0.7); background-color: rgba(255, 255, 255, 0.5); backdrop-filter: blur(10px); `; const FormGroup = styled.div` display: flex; flex-direction: column; font-family: inherit; & label { margin-top: 1rem; text-transform: capitalize; font-size: var(--size-400); } & input, textarea { resize: vertical; font-size: var(--size-400); font-family: inherit; padding: 0.25rem 0.5rem; border-radius: 4px; background-color: #e4b8c7; border: 2px solid transparent; } & textarea:focus, input:focus { outline: none; border: 2px solid #80576e; } `; const FormErrorMessage = styled.span` color: red; font-size: var(--size-300); opacity: 0.7; `; const FormFeedbackWrapper = styled.div` margin-top: 1rem; text-transform: uppercase; font-size: var(--size-300); `; const FormSucessFeedback = styled.span` color: green; `; const FormErrorFeedback = styled.span` color: red; `; const FormButton = styled.button` margin-top: 1rem; padding: 0.45rem; padding-left: 1.25rem; padding-right: 1.5rem; background-color: #37292c; color: #fafafa; border: 1px solid rgba(255, 255, 255, 0.8); text-transform: uppercase; border-radius: 4px; `; export const pageQuery = graphql` query($slug: String!) { markdownRemark(fields: { slug: { eq: $slug } }) { html frontmatter { title } } } `;
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = "/"; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 0); /******/ }) /************************************************************************/ /******/ ({ /***/ "./node_modules/axios/index.js": /*!*************************************!*\ !*** ./node_modules/axios/index.js ***! \*************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(/*! ./lib/axios */ "./node_modules/axios/lib/axios.js"); /***/ }), /***/ "./node_modules/axios/lib/adapters/xhr.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/adapters/xhr.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var settle = __webpack_require__(/*! ./../core/settle */ "./node_modules/axios/lib/core/settle.js"); var buildURL = __webpack_require__(/*! ./../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var buildFullPath = __webpack_require__(/*! ../core/buildFullPath */ "./node_modules/axios/lib/core/buildFullPath.js"); var parseHeaders = __webpack_require__(/*! ./../helpers/parseHeaders */ "./node_modules/axios/lib/helpers/parseHeaders.js"); var isURLSameOrigin = __webpack_require__(/*! ./../helpers/isURLSameOrigin */ "./node_modules/axios/lib/helpers/isURLSameOrigin.js"); var createError = __webpack_require__(/*! ../core/createError */ "./node_modules/axios/lib/core/createError.js"); module.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; if (utils.isFormData(requestData)) { delete requestHeaders['Content-Type']; // Let the browser set it } var request = new XMLHttpRequest(); // HTTP basic authentication if (config.auth) { var username = config.auth.username || ''; var password = config.auth.password || ''; requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); } var fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); // Set the request timeout in MS request.timeout = config.timeout; // Listen for ready state request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } // The request errored out and we didn't get a response, this will be // handled by onerror instead // With one exception: request that using file: protocol, most browsers // will return status as 0 even though it's a successful request if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { return; } // Prepare the response var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config: config, request: request }; settle(resolve, reject, response); // Clean up request request = null; }; // Handle browser request cancellation (as opposed to a manual cancellation) request.onabort = function handleAbort() { if (!request) { return; } reject(createError('Request aborted', config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Handle low level network errors request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error reject(createError('Network Error', config, null, request)); // Clean up request request = null; }; // Handle timeout request.ontimeout = function handleTimeout() { var timeoutErrorMessage = 'timeout of ' + config.timeout + 'ms exceeded'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError(timeoutErrorMessage, config, 'ECONNABORTED', request)); // Clean up request request = null; }; // Add xsrf header // This is only done if running in a standard browser environment. // Specifically not if we're in a web worker, or react-native. if (utils.isStandardBrowserEnv()) { var cookies = __webpack_require__(/*! ./../helpers/cookies */ "./node_modules/axios/lib/helpers/cookies.js"); // Add xsrf header var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : undefined; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } // Add headers to the request if ('setRequestHeader' in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { // Remove Content-Type if data is undefined delete requestHeaders[key]; } else { // Otherwise add header to the request request.setRequestHeader(key, val); } }); } // Add withCredentials to request if needed if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } // Add responseType to request if needed if (config.responseType) { try { request.responseType = config.responseType; } catch (e) { // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. if (config.responseType !== 'json') { throw e; } } } // Handle progress if needed if (typeof config.onDownloadProgress === 'function') { request.addEventListener('progress', config.onDownloadProgress); } // Not all browsers support upload events if (typeof config.onUploadProgress === 'function' && request.upload) { request.upload.addEventListener('progress', config.onUploadProgress); } if (config.cancelToken) { // Handle cancellation config.cancelToken.promise.then(function onCanceled(cancel) { if (!request) { return; } request.abort(); reject(cancel); // Clean up request request = null; }); } if (requestData === undefined) { requestData = null; } // Send the request request.send(requestData); }); }; /***/ }), /***/ "./node_modules/axios/lib/axios.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/axios.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); var Axios = __webpack_require__(/*! ./core/Axios */ "./node_modules/axios/lib/core/Axios.js"); var mergeConfig = __webpack_require__(/*! ./core/mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); var defaults = __webpack_require__(/*! ./defaults */ "./node_modules/axios/lib/defaults.js"); /** * Create an instance of Axios * * @param {Object} defaultConfig The default config for the instance * @return {Axios} A new instance of Axios */ function createInstance(defaultConfig) { var context = new Axios(defaultConfig); var instance = bind(Axios.prototype.request, context); // Copy axios.prototype to instance utils.extend(instance, Axios.prototype, context); // Copy context to instance utils.extend(instance, context); return instance; } // Create the default instance to be exported var axios = createInstance(defaults); // Expose Axios class to allow class inheritance axios.Axios = Axios; // Factory for creating new instances axios.create = function create(instanceConfig) { return createInstance(mergeConfig(axios.defaults, instanceConfig)); }; // Expose Cancel & CancelToken axios.Cancel = __webpack_require__(/*! ./cancel/Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); axios.CancelToken = __webpack_require__(/*! ./cancel/CancelToken */ "./node_modules/axios/lib/cancel/CancelToken.js"); axios.isCancel = __webpack_require__(/*! ./cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); // Expose all/spread axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = __webpack_require__(/*! ./helpers/spread */ "./node_modules/axios/lib/helpers/spread.js"); module.exports = axios; // Allow use of default import syntax in TypeScript module.exports.default = axios; /***/ }), /***/ "./node_modules/axios/lib/cancel/Cancel.js": /*!*************************************************!*\ !*** ./node_modules/axios/lib/cancel/Cancel.js ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * A `Cancel` is an object that is thrown when an operation is canceled. * * @class * @param {string=} message The message. */ function Cancel(message) { this.message = message; } Cancel.prototype.toString = function toString() { return 'Cancel' + (this.message ? ': ' + this.message : ''); }; Cancel.prototype.__CANCEL__ = true; module.exports = Cancel; /***/ }), /***/ "./node_modules/axios/lib/cancel/CancelToken.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/cancel/CancelToken.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var Cancel = __webpack_require__(/*! ./Cancel */ "./node_modules/axios/lib/cancel/Cancel.js"); /** * A `CancelToken` is an object that can be used to request cancellation of an operation. * * @class * @param {Function} executor The executor function. */ function CancelToken(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; executor(function cancel(message) { if (token.reason) { // Cancellation has already been requested return; } token.reason = new Cancel(message); resolvePromise(token.reason); }); } /** * Throws a `Cancel` if cancellation has been requested. */ CancelToken.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ CancelToken.source = function source() { var cancel; var token = new CancelToken(function executor(c) { cancel = c; }); return { token: token, cancel: cancel }; }; module.exports = CancelToken; /***/ }), /***/ "./node_modules/axios/lib/cancel/isCancel.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/cancel/isCancel.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function isCancel(value) { return !!(value && value.__CANCEL__); }; /***/ }), /***/ "./node_modules/axios/lib/core/Axios.js": /*!**********************************************!*\ !*** ./node_modules/axios/lib/core/Axios.js ***! \**********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var buildURL = __webpack_require__(/*! ../helpers/buildURL */ "./node_modules/axios/lib/helpers/buildURL.js"); var InterceptorManager = __webpack_require__(/*! ./InterceptorManager */ "./node_modules/axios/lib/core/InterceptorManager.js"); var dispatchRequest = __webpack_require__(/*! ./dispatchRequest */ "./node_modules/axios/lib/core/dispatchRequest.js"); var mergeConfig = __webpack_require__(/*! ./mergeConfig */ "./node_modules/axios/lib/core/mergeConfig.js"); /** * Create a new instance of Axios * * @param {Object} instanceConfig The default config for the instance */ function Axios(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager(), response: new InterceptorManager() }; } /** * Dispatch a request * * @param {Object} config The config specific for this request (merged with this.defaults) */ Axios.prototype.request = function request(config) { /*eslint no-param-reassign:0*/ // Allow for axios('example/url'[, config]) a la fetch API if (typeof config === 'string') { config = arguments[1] || {}; config.url = arguments[0]; } else { config = config || {}; } config = mergeConfig(this.defaults, config); // Set config.method if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = 'get'; } // Hook up interceptors middleware var chain = [dispatchRequest, undefined]; var promise = Promise.resolve(config); this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { chain.unshift(interceptor.fulfilled, interceptor.rejected); }); this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { chain.push(interceptor.fulfilled, interceptor.rejected); }); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; }; Axios.prototype.getUri = function getUri(config) { config = mergeConfig(this.defaults, config); return buildURL(config.url, config.params, config.paramsSerializer).replace(/^\?/, ''); }; // Provide aliases for supported request methods utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, config) { return this.request(utils.merge(config || {}, { method: method, url: url })); }; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { /*eslint func-names:0*/ Axios.prototype[method] = function(url, data, config) { return this.request(utils.merge(config || {}, { method: method, url: url, data: data })); }; }); module.exports = Axios; /***/ }), /***/ "./node_modules/axios/lib/core/InterceptorManager.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/core/InterceptorManager.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function InterceptorManager() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ InterceptorManager.prototype.use = function use(fulfilled, rejected) { this.handlers.push({ fulfilled: fulfilled, rejected: rejected }); return this.handlers.length - 1; }; /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` */ InterceptorManager.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor */ InterceptorManager.prototype.forEach = function forEach(fn) { utils.forEach(this.handlers, function forEachHandler(h) { if (h !== null) { fn(h); } }); }; module.exports = InterceptorManager; /***/ }), /***/ "./node_modules/axios/lib/core/buildFullPath.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/buildFullPath.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var isAbsoluteURL = __webpack_require__(/*! ../helpers/isAbsoluteURL */ "./node_modules/axios/lib/helpers/isAbsoluteURL.js"); var combineURLs = __webpack_require__(/*! ../helpers/combineURLs */ "./node_modules/axios/lib/helpers/combineURLs.js"); /** * Creates a new URL by combining the baseURL with the requestedURL, * only when the requestedURL is not already an absolute URL. * If the requestURL is absolute, this function returns the requestedURL untouched. * * @param {string} baseURL The base URL * @param {string} requestedURL Absolute or relative URL to combine * @returns {string} The combined full path */ module.exports = function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; }; /***/ }), /***/ "./node_modules/axios/lib/core/createError.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/createError.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var enhanceError = __webpack_require__(/*! ./enhanceError */ "./node_modules/axios/lib/core/enhanceError.js"); /** * Create an Error with the specified message, config, error code, request and response. * * @param {string} message The error message. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The created error. */ module.exports = function createError(message, config, code, request, response) { var error = new Error(message); return enhanceError(error, config, code, request, response); }; /***/ }), /***/ "./node_modules/axios/lib/core/dispatchRequest.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/core/dispatchRequest.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); var transformData = __webpack_require__(/*! ./transformData */ "./node_modules/axios/lib/core/transformData.js"); var isCancel = __webpack_require__(/*! ../cancel/isCancel */ "./node_modules/axios/lib/cancel/isCancel.js"); var defaults = __webpack_require__(/*! ../defaults */ "./node_modules/axios/lib/defaults.js"); /** * Throws a `Cancel` if cancellation has been requested. */ function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } } /** * Dispatch a request to the server using the configured adapter. * * @param {object} config The config that is to be used for the request * @returns {Promise} The Promise to be fulfilled */ module.exports = function dispatchRequest(config) { throwIfCancellationRequested(config); // Ensure headers exist config.headers = config.headers || {}; // Transform request data config.data = transformData( config.data, config.headers, config.transformRequest ); // Flatten headers config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); // Transform response data response.data = transformData( response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data if (reason && reason.response) { reason.response.data = transformData( reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; /***/ }), /***/ "./node_modules/axios/lib/core/enhanceError.js": /*!*****************************************************!*\ !*** ./node_modules/axios/lib/core/enhanceError.js ***! \*****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Update an Error with the specified config, error code, and response. * * @param {Error} error The error to update. * @param {Object} config The config. * @param {string} [code] The error code (for example, 'ECONNABORTED'). * @param {Object} [request] The request. * @param {Object} [response] The response. * @returns {Error} The error. */ module.exports = function enhanceError(error, config, code, request, response) { error.config = config; if (code) { error.code = code; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code }; }; return error; }; /***/ }), /***/ "./node_modules/axios/lib/core/mergeConfig.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/core/mergeConfig.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); /** * Config-specific merge-function which creates a new config-object * by merging two configuration objects together. * * @param {Object} config1 * @param {Object} config2 * @returns {Object} New object resulting from merging config2 to config1 */ module.exports = function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; var config = {}; var valueFromConfig2Keys = ['url', 'method', 'params', 'data']; var mergeDeepPropertiesKeys = ['headers', 'auth', 'proxy']; var defaultToConfig2Keys = [ 'baseURL', 'url', 'transformRequest', 'transformResponse', 'paramsSerializer', 'timeout', 'withCredentials', 'adapter', 'responseType', 'xsrfCookieName', 'xsrfHeaderName', 'onUploadProgress', 'onDownloadProgress', 'maxContentLength', 'validateStatus', 'maxRedirects', 'httpAgent', 'httpsAgent', 'cancelToken', 'socketPath' ]; utils.forEach(valueFromConfig2Keys, function valueFromConfig2(prop) { if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } }); utils.forEach(mergeDeepPropertiesKeys, function mergeDeepProperties(prop) { if (utils.isObject(config2[prop])) { config[prop] = utils.deepMerge(config1[prop], config2[prop]); } else if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } else if (utils.isObject(config1[prop])) { config[prop] = utils.deepMerge(config1[prop]); } else if (typeof config1[prop] !== 'undefined') { config[prop] = config1[prop]; } }); utils.forEach(defaultToConfig2Keys, function defaultToConfig2(prop) { if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } else if (typeof config1[prop] !== 'undefined') { config[prop] = config1[prop]; } }); var axiosKeys = valueFromConfig2Keys .concat(mergeDeepPropertiesKeys) .concat(defaultToConfig2Keys); var otherKeys = Object .keys(config2) .filter(function filterAxiosKeys(key) { return axiosKeys.indexOf(key) === -1; }); utils.forEach(otherKeys, function otherKeysDefaultToConfig2(prop) { if (typeof config2[prop] !== 'undefined') { config[prop] = config2[prop]; } else if (typeof config1[prop] !== 'undefined') { config[prop] = config1[prop]; } }); return config; }; /***/ }), /***/ "./node_modules/axios/lib/core/settle.js": /*!***********************************************!*\ !*** ./node_modules/axios/lib/core/settle.js ***! \***********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var createError = __webpack_require__(/*! ./createError */ "./node_modules/axios/lib/core/createError.js"); /** * Resolve or reject a Promise based on response status. * * @param {Function} resolve A function that resolves the promise. * @param {Function} reject A function that rejects the promise. * @param {object} response The response. */ module.exports = function settle(resolve, reject, response) { var validateStatus = response.config.validateStatus; if (!validateStatus || validateStatus(response.status)) { resolve(response); } else { reject(createError( 'Request failed with status code ' + response.status, response.config, null, response.request, response )); } }; /***/ }), /***/ "./node_modules/axios/lib/core/transformData.js": /*!******************************************************!*\ !*** ./node_modules/axios/lib/core/transformData.js ***! \******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); /** * Transform the data for a request or a response * * @param {Object|String} data The data to be transformed * @param {Array} headers The headers for the request or response * @param {Array|Function} fns A single function or Array of functions * @returns {*} The resulting transformed data */ module.exports = function transformData(data, headers, fns) { /*eslint no-param-reassign:0*/ utils.forEach(fns, function transform(fn) { data = fn(data, headers); }); return data; }; /***/ }), /***/ "./node_modules/axios/lib/defaults.js": /*!********************************************!*\ !*** ./node_modules/axios/lib/defaults.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(process) { var utils = __webpack_require__(/*! ./utils */ "./node_modules/axios/lib/utils.js"); var normalizeHeaderName = __webpack_require__(/*! ./helpers/normalizeHeaderName */ "./node_modules/axios/lib/helpers/normalizeHeaderName.js"); var DEFAULT_CONTENT_TYPE = { 'Content-Type': 'application/x-www-form-urlencoded' }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { headers['Content-Type'] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== 'undefined') { // For browsers use XHR adapter adapter = __webpack_require__(/*! ./adapters/xhr */ "./node_modules/axios/lib/adapters/xhr.js"); } else if (typeof process !== 'undefined' && Object.prototype.toString.call(process) === '[object process]') { // For node use HTTP adapter adapter = __webpack_require__(/*! ./adapters/http */ "./node_modules/axios/lib/adapters/xhr.js"); } return adapter; } var defaults = { adapter: getDefaultAdapter(), transformRequest: [function transformRequest(data, headers) { normalizeHeaderName(headers, 'Accept'); normalizeHeaderName(headers, 'Content-Type'); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data) ) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); return data.toString(); } if (utils.isObject(data)) { setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); return JSON.stringify(data); } return data; }], transformResponse: [function transformResponse(data) { /*eslint no-param-reassign:0*/ if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { /* Ignore */ } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: 'XSRF-TOKEN', xsrfHeaderName: 'X-XSRF-TOKEN', maxContentLength: -1, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; } }; defaults.headers = { common: { 'Accept': 'application/json, text/plain, */*' } }; utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); }); module.exports = defaults; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../../process/browser.js */ "./node_modules/process/browser.js"))) /***/ }), /***/ "./node_modules/axios/lib/helpers/bind.js": /*!************************************************!*\ !*** ./node_modules/axios/lib/helpers/bind.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; module.exports = function bind(fn, thisArg) { return function wrap() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/buildURL.js": /*!****************************************************!*\ !*** ./node_modules/axios/lib/helpers/buildURL.js ***! \****************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); function encode(val) { return encodeURIComponent(val). replace(/%40/gi, '@'). replace(/%3A/gi, ':'). replace(/%24/g, '$'). replace(/%2C/gi, ','). replace(/%20/g, '+'). replace(/%5B/gi, '['). replace(/%5D/gi, ']'); } /** * Build a URL by appending params to the end * * @param {string} url The base of the url (e.g., http://www.google.com) * @param {object} [params] The params to be appended * @returns {string} The formatted url */ module.exports = function buildURL(url, params, paramsSerializer) { /*eslint no-param-reassign:0*/ if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === 'undefined') { return; } if (utils.isArray(val)) { key = key + '[]'; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode(key) + '=' + encode(v)); }); }); serializedParams = parts.join('&'); } if (serializedParams) { var hashmarkIndex = url.indexOf('#'); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; } return url; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/combineURLs.js": /*!*******************************************************!*\ !*** ./node_modules/axios/lib/helpers/combineURLs.js ***! \*******************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Creates a new URL by combining the specified URLs * * @param {string} baseURL The base URL * @param {string} relativeURL The relative URL * @returns {string} The combined URL */ module.exports = function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') : baseURL; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/cookies.js": /*!***************************************************!*\ !*** ./node_modules/axios/lib/helpers/cookies.js ***! \***************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs support document.cookie (function standardBrowserEnv() { return { write: function write(name, value, expires, path, domain, secure) { var cookie = []; cookie.push(name + '=' + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push('expires=' + new Date(expires).toGMTString()); } if (utils.isString(path)) { cookie.push('path=' + path); } if (utils.isString(domain)) { cookie.push('domain=' + domain); } if (secure === true) { cookie.push('secure'); } document.cookie = cookie.join('; '); }, read: function read(name) { var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); return (match ? decodeURIComponent(match[3]) : null); }, remove: function remove(name) { this.write(name, '', Date.now() - 86400000); } }; })() : // Non standard browser env (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return { write: function write() {}, read: function read() { return null; }, remove: function remove() {} }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/isAbsoluteURL.js": /*!*********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isAbsoluteURL.js ***! \*********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Determines whether the specified URL is absolute * * @param {string} url The URL to test * @returns {boolean} True if the specified URL is absolute, otherwise false */ module.exports = function isAbsoluteURL(url) { // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL). // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed // by any combination of letters, digits, plus, period, or hyphen. return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/isURLSameOrigin.js": /*!***********************************************************!*\ !*** ./node_modules/axios/lib/helpers/isURLSameOrigin.js ***! \***********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); module.exports = ( utils.isStandardBrowserEnv() ? // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. (function standardBrowserEnv() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement('a'); var originURL; /** * Parse a URL to discover it's components * * @param {String} url The URL to be parsed * @returns {Object} */ function resolveURL(url) { var href = url; if (msie) { // IE needs attribute set twice to normalize properties urlParsingNode.setAttribute('href', href); href = urlParsingNode.href; } urlParsingNode.setAttribute('href', href); // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: (urlParsingNode.pathname.charAt(0) === '/') ? urlParsingNode.pathname : '/' + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); /** * Determine if a URL shares the same origin as the current location * * @param {String} requestURL The URL to test * @returns {boolean} True if URL shares the same origin, otherwise false */ return function isURLSameOrigin(requestURL) { var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; return (parsed.protocol === originURL.protocol && parsed.host === originURL.host); }; })() : // Non standard browser envs (web workers, react-native) lack needed support. (function nonStandardBrowserEnv() { return function isURLSameOrigin() { return true; }; })() ); /***/ }), /***/ "./node_modules/axios/lib/helpers/normalizeHeaderName.js": /*!***************************************************************!*\ !*** ./node_modules/axios/lib/helpers/normalizeHeaderName.js ***! \***************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ../utils */ "./node_modules/axios/lib/utils.js"); module.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; /***/ }), /***/ "./node_modules/axios/lib/helpers/parseHeaders.js": /*!********************************************************!*\ !*** ./node_modules/axios/lib/helpers/parseHeaders.js ***! \********************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var utils = __webpack_require__(/*! ./../utils */ "./node_modules/axios/lib/utils.js"); // Headers whose duplicates are ignored by node // c.f. https://nodejs.org/api/http.html#http_message_headers var ignoreDuplicateOf = [ 'age', 'authorization', 'content-length', 'content-type', 'etag', 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since', 'last-modified', 'location', 'max-forwards', 'proxy-authorization', 'referer', 'retry-after', 'user-agent' ]; /** * Parse headers into an object * * ``` * Date: Wed, 27 Aug 2014 08:58:49 GMT * Content-Type: application/json * Connection: keep-alive * Transfer-Encoding: chunked * ``` * * @param {String} headers Headers needing to be parsed * @returns {Object} Headers parsed into an object */ module.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split('\n'), function parser(line) { i = line.indexOf(':'); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { return; } if (key === 'set-cookie') { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; } } }); return parsed; }; /***/ }), /***/ "./node_modules/axios/lib/helpers/spread.js": /*!**************************************************!*\ !*** ./node_modules/axios/lib/helpers/spread.js ***! \**************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * Syntactic sugar for invoking a function and expanding an array for arguments. * * Common use case would be to use `Function.prototype.apply`. * * ```js * function f(x, y, z) {} * var args = [1, 2, 3]; * f.apply(null, args); * ``` * * With `spread` this example can be re-written. * * ```js * spread(function(x, y, z) {})([1, 2, 3]); * ``` * * @param {Function} callback * @returns {Function} */ module.exports = function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; }; /***/ }), /***/ "./node_modules/axios/lib/utils.js": /*!*****************************************!*\ !*** ./node_modules/axios/lib/utils.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var bind = __webpack_require__(/*! ./helpers/bind */ "./node_modules/axios/lib/helpers/bind.js"); /*global toString:true*/ // utils is a library of generic helper functions non-specific to axios var toString = Object.prototype.toString; /** * Determine if a value is an Array * * @param {Object} val The value to test * @returns {boolean} True if value is an Array, otherwise false */ function isArray(val) { return toString.call(val) === '[object Array]'; } /** * Determine if a value is undefined * * @param {Object} val The value to test * @returns {boolean} True if the value is undefined, otherwise false */ function isUndefined(val) { return typeof val === 'undefined'; } /** * Determine if a value is a Buffer * * @param {Object} val The value to test * @returns {boolean} True if value is a Buffer, otherwise false */ function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && typeof val.constructor.isBuffer === 'function' && val.constructor.isBuffer(val); } /** * Determine if a value is an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is an ArrayBuffer, otherwise false */ function isArrayBuffer(val) { return toString.call(val) === '[object ArrayBuffer]'; } /** * Determine if a value is a FormData * * @param {Object} val The value to test * @returns {boolean} True if value is an FormData, otherwise false */ function isFormData(val) { return (typeof FormData !== 'undefined') && (val instanceof FormData); } /** * Determine if a value is a view on an ArrayBuffer * * @param {Object} val The value to test * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false */ function isArrayBufferView(val) { var result; if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { result = ArrayBuffer.isView(val); } else { result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); } return result; } /** * Determine if a value is a String * * @param {Object} val The value to test * @returns {boolean} True if value is a String, otherwise false */ function isString(val) { return typeof val === 'string'; } /** * Determine if a value is a Number * * @param {Object} val The value to test * @returns {boolean} True if value is a Number, otherwise false */ function isNumber(val) { return typeof val === 'number'; } /** * Determine if a value is an Object * * @param {Object} val The value to test * @returns {boolean} True if value is an Object, otherwise false */ function isObject(val) { return val !== null && typeof val === 'object'; } /** * Determine if a value is a Date * * @param {Object} val The value to test * @returns {boolean} True if value is a Date, otherwise false */ function isDate(val) { return toString.call(val) === '[object Date]'; } /** * Determine if a value is a File * * @param {Object} val The value to test * @returns {boolean} True if value is a File, otherwise false */ function isFile(val) { return toString.call(val) === '[object File]'; } /** * Determine if a value is a Blob * * @param {Object} val The value to test * @returns {boolean} True if value is a Blob, otherwise false */ function isBlob(val) { return toString.call(val) === '[object Blob]'; } /** * Determine if a value is a Function * * @param {Object} val The value to test * @returns {boolean} True if value is a Function, otherwise false */ function isFunction(val) { return toString.call(val) === '[object Function]'; } /** * Determine if a value is a Stream * * @param {Object} val The value to test * @returns {boolean} True if value is a Stream, otherwise false */ function isStream(val) { return isObject(val) && isFunction(val.pipe); } /** * Determine if a value is a URLSearchParams object * * @param {Object} val The value to test * @returns {boolean} True if value is a URLSearchParams object, otherwise false */ function isURLSearchParams(val) { return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; } /** * Trim excess whitespace off the beginning and end of a string * * @param {String} str The String to trim * @returns {String} The String freed of excess whitespace */ function trim(str) { return str.replace(/^\s*/, '').replace(/\s*$/, ''); } /** * Determine if we're running in a standard browser environment * * This allows axios to run in a web worker, and react-native. * Both environments support XMLHttpRequest, but not fully standard globals. * * web workers: * typeof window -> undefined * typeof document -> undefined * * react-native: * navigator.product -> 'ReactNative' * nativescript * navigator.product -> 'NativeScript' or 'NS' */ function isStandardBrowserEnv() { if (typeof navigator !== 'undefined' && (navigator.product === 'ReactNative' || navigator.product === 'NativeScript' || navigator.product === 'NS')) { return false; } return ( typeof window !== 'undefined' && typeof document !== 'undefined' ); } /** * Iterate over an Array or an Object invoking a function for each item. * * If `obj` is an Array callback will be called passing * the value, index, and complete array for each item. * * If 'obj' is an Object callback will be called passing * the value, key, and complete object for each property. * * @param {Object|Array} obj The object to iterate * @param {Function} fn The callback to invoke for each item */ function forEach(obj, fn) { // Don't bother if no value provided if (obj === null || typeof obj === 'undefined') { return; } // Force an array if not already something iterable if (typeof obj !== 'object') { /*eslint no-param-reassign:0*/ obj = [obj]; } if (isArray(obj)) { // Iterate over array values for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { // Iterate over object keys for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } /** * Accepts varargs expecting each argument to be an object, then * immutably merges the properties of each object and returns result. * * When multiple objects contain the same key the later object in * the arguments list will take precedence. * * Example: * * ```js * var result = merge({foo: 123}, {foo: 456}); * console.log(result.foo); // outputs 456 * ``` * * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function merge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = merge(result[key], val); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Function equal to merge with the difference being that no reference * to original objects is kept. * * @see merge * @param {Object} obj1 Object to merge * @returns {Object} Result of all merge properties */ function deepMerge(/* obj1, obj2, obj3, ... */) { var result = {}; function assignValue(val, key) { if (typeof result[key] === 'object' && typeof val === 'object') { result[key] = deepMerge(result[key], val); } else if (typeof val === 'object') { result[key] = deepMerge({}, val); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach(arguments[i], assignValue); } return result; } /** * Extends object a by mutably adding to it the properties of object b. * * @param {Object} a The object to be extended * @param {Object} b The object to copy properties from * @param {Object} thisArg The object to bind function to * @return {Object} The resulting value of object a */ function extend(a, b, thisArg) { forEach(b, function assignValue(val, key) { if (thisArg && typeof val === 'function') { a[key] = bind(val, thisArg); } else { a[key] = val; } }); return a; } module.exports = { isArray: isArray, isArrayBuffer: isArrayBuffer, isBuffer: isBuffer, isFormData: isFormData, isArrayBufferView: isArrayBufferView, isString: isString, isNumber: isNumber, isObject: isObject, isUndefined: isUndefined, isDate: isDate, isFile: isFile, isBlob: isBlob, isFunction: isFunction, isStream: isStream, isURLSearchParams: isURLSearchParams, isStandardBrowserEnv: isStandardBrowserEnv, forEach: forEach, merge: merge, deepMerge: deepMerge, extend: extend, trim: trim }; /***/ }), /***/ "./node_modules/lodash/lodash.js": /*!***************************************!*\ !*** ./node_modules/lodash/lodash.js ***! \***************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, module) {var __WEBPACK_AMD_DEFINE_RESULT__;/** * @license * Lodash <https://lodash.com/> * Copyright OpenJS Foundation and other contributors <https://openjsf.org/> * Released under MIT license <https://lodash.com/license> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors */ ;(function() { /** Used as a safe reference for `undefined` in pre-ES5 environments. */ var undefined; /** Used as the semantic version number. */ var VERSION = '4.17.20'; /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** Error message constants. */ var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', FUNC_ERROR_TEXT = 'Expected a function'; /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used as default options for `_.truncate`. */ var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = '...'; /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /** Used to indicate the type of lazy iteratees. */ var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 1.7976931348623157e+308, NAN = 0 / 0; /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', asyncTag = '[object AsyncFunction]', boolTag = '[object Boolean]', dateTag = '[object Date]', domExcTag = '[object DOMException]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', nullTag = '[object Null]', objectTag = '[object Object]', promiseTag = '[object Promise]', proxyTag = '[object Proxy]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', undefinedTag = '[object Undefined]', weakMapTag = '[object WeakMap]', weakSetTag = '[object WeakSet]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to match empty string literals in compiled template source. */ var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; /** Used to match HTML entities and HTML characters. */ var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); /** Used to match template delimiters. */ var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g, reTrimStart = /^\s+/, reTrimEnd = /\s+$/; /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** Used to match words composed of alphanumeric characters. */ var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Used to match * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). */ var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** Used to match Latin Unicode letters (excluding mathematical operators). */ var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; /** Used to ensure capturing order of template delimiters. */ var reNoMatch = /($^)/; /** Used to match unescaped characters in compiled string literals. */ var reUnescapedString = /['\n\r\u2028\u2029\\]/g; /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff', rsComboMarksRange = '\\u0300-\\u036f', reComboHalfMarksRange = '\\ufe20-\\ufe2f', rsComboSymbolsRange = '\\u20d0-\\u20ff', rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = '\\u2700-\\u27bf', rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', rsPunctuationRange = '\\u2000-\\u206f', rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', rsVarRange = '\\ufe0e\\ufe0f', rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; /** Used to compose unicode capture groups. */ var rsApos = "['\u2019]", rsAstral = '[' + rsAstralRange + ']', rsBreak = '[' + rsBreakRange + ']', rsCombo = '[' + rsComboRange + ']', rsDigits = '\\d+', rsDingbat = '[' + rsDingbatRange + ']', rsLower = '[' + rsLowerRange + ']', rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', rsFitz = '\\ud83c[\\udffb-\\udfff]', rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', rsNonAstral = '[^' + rsAstralRange + ']', rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', rsUpper = '[' + rsUpperRange + ']', rsZWJ = '\\u200d'; /** Used to compose unicode regexes. */ var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', reOptMod = rsModifier + '?', rsOptVar = '[' + rsVarRange + ']?', rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; /** Used to match apostrophes. */ var reApos = RegExp(rsApos, 'g'); /** * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). */ var reComboMark = RegExp(rsCombo, 'g'); /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); /** Used to match complex or compound words. */ var reUnicodeWord = RegExp([ rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, rsUpper + '+' + rsOptContrUpper, rsOrdUpper, rsOrdLower, rsDigits, rsEmoji ].join('|'), 'g'); /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); /** Used to detect strings that need a more robust regexp to match words. */ var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; /** Used to assign default `context` object properties. */ var contextProps = [ 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' ]; /** Used to make template sourceURLs easier to identify. */ var templateCounter = -1; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** Used to map Latin Unicode letters to basic Latin letters. */ var deburredLetters = { // Latin-1 Supplement block. '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', '\xc7': 'C', '\xe7': 'c', '\xd0': 'D', '\xf0': 'd', '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', '\xd1': 'N', '\xf1': 'n', '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', '\xc6': 'Ae', '\xe6': 'ae', '\xde': 'Th', '\xfe': 'th', '\xdf': 'ss', // Latin Extended-A block. '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', '\u0134': 'J', '\u0135': 'j', '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', '\u0163': 't', '\u0165': 't', '\u0167': 't', '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', '\u0174': 'W', '\u0175': 'w', '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', '\u0132': 'IJ', '\u0133': 'ij', '\u0152': 'Oe', '\u0153': 'oe', '\u0149': "'n", '\u017f': 's' }; /** Used to map characters to HTML entities. */ var htmlEscapes = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }; /** Used to map HTML entities to characters. */ var htmlUnescapes = { '&amp;': '&', '&lt;': '<', '&gt;': '>', '&quot;': '"', '&#39;': "'" }; /** Used to escape characters for inclusion in compiled string literals. */ var stringEscapes = { '\\': '\\', "'": "'", '\n': 'n', '\r': 'r', '\u2028': 'u2028', '\u2029': 'u2029' }; /** Built-in method references without a dependency on `root`. */ var freeParseFloat = parseFloat, freeParseInt = parseInt; /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); /** Detect free variable `exports`. */ var freeExports = true && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { // Use `util.types` for Node.js 10+. var types = freeModule && freeModule.require && freeModule.require('util').types; if (types) { return types; } // Legacy `process.binding('util')` for Node.js < 10. return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); /* Node.js helper references. */ var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /*--------------------------------------------------------------------------*/ /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } /** * A specialized version of `_.forEachRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEachRight(array, iteratee) { var length = array == null ? 0 : array.length; while (length--) { if (iteratee(array[length], length, array) === false) { break; } } return array; } /** * A specialized version of `_.every` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. */ function arrayEvery(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (!predicate(array[index], index, array)) { return false; } } return true; } /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } /** * A specialized version of `_.reduceRight` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the last element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduceRight(array, iteratee, accumulator, initAccum) { var length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[--length]; } while (length--) { accumulator = iteratee(accumulator, array[length], length, array); } return accumulator; } /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } /** * Gets the size of an ASCII `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ var asciiSize = baseProperty('length'); /** * Converts an ASCII `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function asciiToArray(string) { return string.split(''); } /** * Splits an ASCII `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function asciiWords(string) { return string.match(reAsciiWord) || []; } /** * The base implementation of methods like `_.findKey` and `_.findLastKey`, * without support for iteratee shorthands, which iterates over `collection` * using `eachFunc`. * * @private * @param {Array|Object} collection The collection to inspect. * @param {Function} predicate The function invoked per iteration. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the found element or its key, else `undefined`. */ function baseFindKey(collection, predicate, eachFunc) { var result; eachFunc(collection, function(value, key, collection) { if (predicate(value, key, collection)) { result = key; return false; } }); return result; } /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } /** * This function is like `baseIndexOf` except that it accepts a comparator. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @param {Function} comparator The comparator invoked per element. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOfWith(array, value, fromIndex, comparator) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (comparator(array[index], value)) { return index; } } return -1; } /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } /** * The base implementation of `_.mean` and `_.meanBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the mean. */ function baseMean(array, iteratee) { var length = array == null ? 0 : array.length; return length ? (baseSum(array, iteratee) / length) : NAN; } /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.propertyOf` without support for deep paths. * * @private * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. */ function basePropertyOf(object) { return function(key) { return object == null ? undefined : object[key]; }; } /** * The base implementation of `_.reduce` and `_.reduceRight`, without support * for iteratee shorthands, which iterates over `collection` using `eachFunc`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} accumulator The initial value. * @param {boolean} initAccum Specify using the first or last element of * `collection` as the initial value. * @param {Function} eachFunc The function to iterate over `collection`. * @returns {*} Returns the accumulated value. */ function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { eachFunc(collection, function(value, index, collection) { accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection); }); return accumulator; } /** * The base implementation of `_.sortBy` which uses `comparer` to define the * sort order of `array` and replaces criteria objects with their corresponding * values. * * @private * @param {Array} array The array to sort. * @param {Function} comparer The function to define sort order. * @returns {Array} Returns `array`. */ function baseSortBy(array, comparer) { var length = array.length; array.sort(comparer); while (length--) { array[length] = array[length].value; } return array; } /** * The base implementation of `_.sum` and `_.sumBy` without support for * iteratee shorthands. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {number} Returns the sum. */ function baseSum(array, iteratee) { var result, index = -1, length = array.length; while (++index < length) { var current = iteratee(array[index]); if (current !== undefined) { result = result === undefined ? current : (result + current); } } return result; } /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } /** * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array * of key-value pairs for `object` corresponding to the property names of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the key-value pairs. */ function baseToPairs(object, props) { return arrayMap(props, function(key) { return [key, object[key]]; }); } /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } /** * The base implementation of `_.values` and `_.valuesIn` which creates an * array of `object` property values corresponding to the property names * of `props`. * * @private * @param {Object} object The object to query. * @param {Array} props The property names to get values for. * @returns {Object} Returns the array of property values. */ function baseValues(object, props) { return arrayMap(props, function(key) { return object[key]; }); } /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the first unmatched string symbol. */ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. * * @private * @param {Array} strSymbols The string symbols to inspect. * @param {Array} chrSymbols The character symbols to find. * @returns {number} Returns the index of the last unmatched string symbol. */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } /** * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A * letters to basic Latin letters. * * @private * @param {string} letter The matched letter to deburr. * @returns {string} Returns the deburred letter. */ var deburrLetter = basePropertyOf(deburredLetters); /** * Used by `_.escape` to convert characters to HTML entities. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ var escapeHtmlChar = basePropertyOf(htmlEscapes); /** * Used by `_.template` to escape characters for inclusion in compiled string literals. * * @private * @param {string} chr The matched character to escape. * @returns {string} Returns the escaped character. */ function escapeStringChar(chr) { return '\\' + stringEscapes[chr]; } /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } /** * Checks if `string` contains Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a symbol is found, else `false`. */ function hasUnicode(string) { return reHasUnicode.test(string); } /** * Checks if `string` contains a word composed of Unicode symbols. * * @private * @param {string} string The string to inspect. * @returns {boolean} Returns `true` if a word is found, else `false`. */ function hasUnicodeWord(string) { return reHasUnicodeWord.test(string); } /** * Converts `iterator` to an array. * * @private * @param {Object} iterator The iterator to convert. * @returns {Array} Returns the converted array. */ function iteratorToArray(iterator) { var data, result = []; while (!(data = iterator.next()).done) { result.push(data.value); } return result; } /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } /** * Converts `set` to its value-value pairs. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the value-value pairs. */ function setToPairs(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = [value, value]; }); return result; } /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } /** * A specialized version of `_.lastIndexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictLastIndexOf(array, value, fromIndex) { var index = fromIndex + 1; while (index--) { if (array[index] === value) { return index; } } return index; } /** * Gets the number of symbols in `string`. * * @private * @param {string} string The string to inspect. * @returns {number} Returns the string size. */ function stringSize(string) { return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); } /** * Converts `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function stringToArray(string) { return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); } /** * Used by `_.unescape` to convert HTML entities to characters. * * @private * @param {string} chr The matched character to unescape. * @returns {string} Returns the unescaped character. */ var unescapeHtmlChar = basePropertyOf(htmlUnescapes); /** * Gets the size of a Unicode `string`. * * @private * @param {string} string The string inspect. * @returns {number} Returns the string size. */ function unicodeSize(string) { var result = reUnicode.lastIndex = 0; while (reUnicode.test(string)) { ++result; } return result; } /** * Converts a Unicode `string` to an array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the converted array. */ function unicodeToArray(string) { return string.match(reUnicode) || []; } /** * Splits a Unicode `string` into an array of its words. * * @private * @param {string} The string to inspect. * @returns {Array} Returns the words of `string`. */ function unicodeWords(string) { return string.match(reUnicodeWord) || []; } /*--------------------------------------------------------------------------*/ /** * Create a new pristine `lodash` function using the `context` object. * * @static * @memberOf _ * @since 1.1.0 * @category Util * @param {Object} [context=root] The context object. * @returns {Function} Returns a new `lodash` function. * @example * * _.mixin({ 'foo': _.constant('foo') }); * * var lodash = _.runInContext(); * lodash.mixin({ 'bar': lodash.constant('bar') }); * * _.isFunction(_.foo); * // => true * _.isFunction(_.bar); * // => false * * lodash.isFunction(lodash.foo); * // => false * lodash.isFunction(lodash.bar); * // => true * * // Create a suped-up `defer` in Node.js. * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; */ var runInContext = (function runInContext(context) { context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); /** Built-in constructor references. */ var Array = context.Array, Date = context.Date, Error = context.Error, Function = context.Function, Math = context.Math, Object = context.Object, RegExp = context.RegExp, String = context.String, TypeError = context.TypeError; /** Used for built-in method references. */ var arrayProto = Array.prototype, funcProto = Function.prototype, objectProto = Object.prototype; /** Used to detect overreaching core-js shims. */ var coreJsData = context['__core-js_shared__']; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to generate unique IDs. */ var idCounter = 0; /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** Used to restore the original `_` reference in `_.noConflict`. */ var oldDash = root._; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** Built-in value references. */ var Buffer = moduleExports ? context.Buffer : undefined, Symbol = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, getPrototype = overArg(Object.getPrototypeOf, Object), objectCreate = Object.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, symIterator = Symbol ? Symbol.iterator : undefined, symToStringTag = Symbol ? Symbol.toStringTag : undefined; var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); /** Mocked built-ins. */ var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date && Date.now !== root.Date.now && Date.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil, nativeFloor = Math.floor, nativeGetSymbols = Object.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object.keys, Object), nativeMax = Math.max, nativeMin = Math.min, nativeNow = Date.now, nativeParseInt = context.parseInt, nativeRandom = Math.random, nativeReverse = arrayProto.reverse; /* Built-in method references that are verified to be native. */ var DataView = getNative(context, 'DataView'), Map = getNative(context, 'Map'), Promise = getNative(context, 'Promise'), Set = getNative(context, 'Set'), WeakMap = getNative(context, 'WeakMap'), nativeCreate = getNative(Object, 'create'); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; /** Used to lookup unminified function names. */ var realNames = {}; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /*------------------------------------------------------------------------*/ /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } /** * By default, the template delimiters used by lodash are like those in * embedded Ruby (ERB) as well as ES2015 template strings. Change the * following template settings to use alternative delimiters. * * @static * @memberOf _ * @type {Object} */ lodash.templateSettings = { /** * Used to detect `data` property values to be HTML-escaped. * * @memberOf _.templateSettings * @type {RegExp} */ 'escape': reEscape, /** * Used to detect code to be evaluated. * * @memberOf _.templateSettings * @type {RegExp} */ 'evaluate': reEvaluate, /** * Used to detect `data` property values to inject. * * @memberOf _.templateSettings * @type {RegExp} */ 'interpolate': reInterpolate, /** * Used to reference the data object in the template text. * * @memberOf _.templateSettings * @type {string} */ 'variable': '', /** * Used to import variables into the compiled template. * * @memberOf _.templateSettings * @type {Object} */ 'imports': { /** * A reference to the `lodash` function. * * @memberOf _.templateSettings.imports * @type {Function} */ '_': lodash } }; // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; /*------------------------------------------------------------------------*/ /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } /** * Creates a clone of the lazy wrapper object. * * @private * @name clone * @memberOf LazyWrapper * @returns {Object} Returns the cloned `LazyWrapper` object. */ function lazyClone() { var result = new LazyWrapper(this.__wrapped__); result.__actions__ = copyArray(this.__actions__); result.__dir__ = this.__dir__; result.__filtered__ = this.__filtered__; result.__iteratees__ = copyArray(this.__iteratees__); result.__takeCount__ = this.__takeCount__; result.__views__ = copyArray(this.__views__); return result; } /** * Reverses the direction of lazy iteration. * * @private * @name reverse * @memberOf LazyWrapper * @returns {Object} Returns the new reversed `LazyWrapper` object. */ function lazyReverse() { if (this.__filtered__) { var result = new LazyWrapper(this); result.__dir__ = -1; result.__filtered__ = true; } else { result = this.clone(); result.__dir__ *= -1; } return result; } /** * Extracts the unwrapped value from its lazy wrapper. * * @private * @name value * @memberOf LazyWrapper * @returns {*} Returns the unwrapped value. */ function lazyValue() { var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : (start - 1), iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); if (!isArr || (!isRight && arrLength == length && takeCount == length)) { return baseWrapperValue(array, this.__actions__); } var result = []; outer: while (length-- && resIndex < takeCount) { index += dir; var iterIndex = -1, value = array[index]; while (++iterIndex < iterLength) { var data = iteratees[iterIndex], iteratee = data.iteratee, type = data.type, computed = iteratee(value); if (type == LAZY_MAP_FLAG) { value = computed; } else if (!computed) { if (type == LAZY_FILTER_FLAG) { continue outer; } else { break outer; } } } result[resIndex++] = value; } return result; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; /*------------------------------------------------------------------------*/ /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; /*------------------------------------------------------------------------*/ /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; /*------------------------------------------------------------------------*/ /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; /*------------------------------------------------------------------------*/ /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; /*------------------------------------------------------------------------*/ /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; /*------------------------------------------------------------------------*/ /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } /** * A specialized version of `_.sample` for arrays. * * @private * @param {Array} array The array to sample. * @returns {*} Returns the random element. */ function arraySample(array) { var length = array.length; return length ? array[baseRandom(0, length - 1)] : undefined; } /** * A specialized version of `_.sampleSize` for arrays. * * @private * @param {Array} array The array to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function arraySampleSize(array, n) { return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** * A specialized version of `_.shuffle` for arrays. * * @private * @param {Array} array The array to shuffle. * @returns {Array} Returns the new shuffled array. */ function arrayShuffle(array) { return shuffleSelf(copyArray(array)); } /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } /** * The base implementation of `_.at` without support for individual paths. * * @private * @param {Object} object The object to iterate over. * @param {string[]} paths The property paths to pick. * @returns {Array} Returns the picked elements. */ function baseAt(object, paths) { var index = -1, length = paths.length, result = Array(length), skip = object == null; while (++index < length) { result[index] = skip ? undefined : get(object, paths[index]); } return result; } /** * The base implementation of `_.clamp` which doesn't coerce arguments. * * @private * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. */ function baseClamp(number, lower, upper) { if (number === number) { if (upper !== undefined) { number = number <= upper ? number : upper; } if (lower !== undefined) { number = number >= lower ? number : lower; } } return number; } /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); if (isSet(value)) { value.forEach(function(subValue) { result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); }); } else if (isMap(value)) { value.forEach(function(subValue, key) { result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); } var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } /** * The base implementation of `_.conforms` which doesn't clone `source`. * * @private * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. */ function baseConforms(source) { var props = keys(source); return function(object) { return baseConformsTo(object, source, props); }; } /** * The base implementation of `_.conformsTo` which accepts `props` to check. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ function baseConformsTo(object, source, props) { var length = props.length; if (object == null) { return !length; } object = Object(object); while (length--) { var key = props[length], predicate = source[key], value = object[key]; if ((value === undefined && !(key in object)) || !predicate(value)) { return false; } } return true; } /** * The base implementation of `_.delay` and `_.defer` which accepts `args` * to provide to `func`. * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {Array} args The arguments to provide to `func`. * @returns {number|Object} Returns the timer id or timeout object. */ function baseDelay(func, wait, args) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return setTimeout(function() { func.apply(undefined, args); }, wait); } /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); /** * The base implementation of `_.forEachRight` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEachRight = createBaseEach(baseForOwnRight, true); /** * The base implementation of `_.every` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false` */ function baseEvery(collection, predicate) { var result = true; baseEach(collection, function(value, index, collection) { result = !!predicate(value, index, collection); return result; }); return result; } /** * The base implementation of methods like `_.max` and `_.min` which accepts a * `comparator` to determine the extremum value. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The iteratee invoked per iteration. * @param {Function} comparator The comparator used to compare values. * @returns {*} Returns the extremum value. */ function baseExtremum(array, iteratee, comparator) { var index = -1, length = array.length; while (++index < length) { var value = array[index], current = iteratee(value); if (current != null && (computed === undefined ? (current === current && !isSymbol(current)) : comparator(current, computed) )) { var computed = current, result = value; } } return result; } /** * The base implementation of `_.fill` without an iteratee call guard. * * @private * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. */ function baseFill(array, value, start, end) { var length = array.length; start = toInteger(start); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : toInteger(end); if (end < 0) { end += length; } end = start > end ? 0 : toLength(end); while (start < end) { array[start++] = value; } return array; } /** * The base implementation of `_.filter` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); /** * This function is like `baseFor` except that it iterates over properties * in the opposite order. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseForRight = createBaseFor(true); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } /** * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwnRight(object, iteratee) { return object && baseForRight(object, iteratee, keys); } /** * The base implementation of `_.functions` which creates an array of * `object` function property names filtered from `props`. * * @private * @param {Object} object The object to inspect. * @param {Array} props The property names to filter. * @returns {Array} Returns the function names. */ function baseFunctions(object, props) { return arrayFilter(props, function(key) { return isFunction(object[key]); }); } /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } /** * The base implementation of `_.gt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. */ function baseGt(value, other) { return value > other; } /** * The base implementation of `_.has` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHas(object, key) { return object != null && hasOwnProperty.call(object, key); } /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } /** * The base implementation of `_.inRange` which doesn't coerce arguments. * * @private * @param {number} number The number to check. * @param {number} start The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. */ function baseInRange(number, start, end) { return number >= nativeMin(start, end) && number < nativeMax(start, end); } /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.invert` and `_.invertBy` which inverts * `object` with values transformed by `iteratee` and set by `setter`. * * @private * @param {Object} object The object to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform values. * @param {Object} accumulator The initial inverted object. * @returns {Function} Returns `accumulator`. */ function baseInverter(object, setter, iteratee, accumulator) { baseForOwn(object, function(value, key, object) { setter(accumulator, iteratee(value), key, object); }); return accumulator; } /** * The base implementation of `_.invoke` without support for individual * method arguments. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {Array} args The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. */ function baseInvoke(object, path, args) { path = castPath(path, object); object = parent(object, path); var func = object == null ? object : object[toKey(last(path))]; return func == null ? undefined : apply(func, object, args); } /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } /** * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ function baseIsArrayBuffer(value) { return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** * The base implementation of `_.isDate` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ function baseIsDate(value) { return isObjectLike(value) && baseGetTag(value) == dateTag; } /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** * The base implementation of `_.isMap` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ function baseIsMap(value) { return isObjectLike(value) && getTag(value) == mapTag; } /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } /** * The base implementation of `_.isRegExp` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ function baseIsRegExp(value) { return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** * The base implementation of `_.isSet` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ function baseIsSet(value) { return isObjectLike(value) && getTag(value) == setTag; } /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } /** * The base implementation of `_.lt` which doesn't coerce arguments. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. */ function baseLt(value, other) { return value < other; } /** * The base implementation of `_.map` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function baseMap(collection, iteratee) { var index = -1, result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value, key, collection) { result[++index] = iteratee(value, key, collection); }); return result; } /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { stack || (stack = new Stack); if (isObject(srcValue)) { baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || isFunction(objValue)) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } /** * The base implementation of `_.nth` which doesn't coerce arguments. * * @private * @param {Array} array The array to query. * @param {number} n The index of the element to return. * @returns {*} Returns the nth element of `array`. */ function baseNth(array, n) { var length = array.length; if (!length) { return; } n += n < 0 ? length : 0; return isIndex(n, length) ? array[n] : undefined; } /** * The base implementation of `_.orderBy` without param guards. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. * @param {string[]} orders The sort orders of `iteratees`. * @returns {Array} Returns the new sorted array. */ function baseOrderBy(collection, iteratees, orders) { if (iteratees.length) { iteratees = arrayMap(iteratees, function(iteratee) { if (isArray(iteratee)) { return function(value) { return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); } } return iteratee; }); } else { iteratees = [identity]; } var index = -1; iteratees = arrayMap(iteratees, baseUnary(getIteratee())); var result = baseMap(collection, function(value, key, collection) { var criteria = arrayMap(iteratees, function(iteratee) { return iteratee(value); }); return { 'criteria': criteria, 'index': ++index, 'value': value }; }); return baseSortBy(result, function(object, other) { return compareMultiple(object, other, orders); }); } /** * The base implementation of `_.pick` without support for individual * property identifiers. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @returns {Object} Returns the new object. */ function basePick(object, paths) { return basePickBy(object, paths, function(value, path) { return hasIn(object, path); }); } /** * The base implementation of `_.pickBy` without support for iteratee shorthands. * * @private * @param {Object} object The source object. * @param {string[]} paths The property paths to pick. * @param {Function} predicate The function invoked per property. * @returns {Object} Returns the new object. */ function basePickBy(object, paths, predicate) { var index = -1, length = paths.length, result = {}; while (++index < length) { var path = paths[index], value = baseGet(object, path); if (predicate(value, path)) { baseSet(result, castPath(path, object), value); } } return result; } /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } /** * The base implementation of `_.pullAllBy` without support for iteratee * shorthands. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. */ function basePullAll(array, values, iteratee, comparator) { var indexOf = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values.length, seen = array; if (array === values) { values = copyArray(values); } if (iteratee) { seen = arrayMap(array, baseUnary(iteratee)); } while (++index < length) { var fromIndex = 0, value = values[index], computed = iteratee ? iteratee(value) : value; while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { if (seen !== array) { splice.call(seen, fromIndex, 1); } splice.call(array, fromIndex, 1); } } return array; } /** * The base implementation of `_.pullAt` without support for individual * indexes or capturing the removed elements. * * @private * @param {Array} array The array to modify. * @param {number[]} indexes The indexes of elements to remove. * @returns {Array} Returns `array`. */ function basePullAt(array, indexes) { var length = array ? indexes.length : 0, lastIndex = length - 1; while (length--) { var index = indexes[length]; if (length == lastIndex || index !== previous) { var previous = index; if (isIndex(index)) { splice.call(array, index, 1); } else { baseUnset(array, index); } } } return array; } /** * The base implementation of `_.random` without support for returning * floating-point numbers. * * @private * @param {number} lower The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the random number. */ function baseRandom(lower, upper) { return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. * * @private * @param {number} start The start of the range. * @param {number} end The end of the range. * @param {number} step The value to increment or decrement by. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the range of numbers. */ function baseRange(start, end, step, fromRight) { var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } /** * The base implementation of `_.repeat` which doesn't coerce arguments. * * @private * @param {string} string The string to repeat. * @param {number} n The number of times to repeat the string. * @returns {string} Returns the repeated string. */ function baseRepeat(string, n) { var result = ''; if (!string || n < 1 || n > MAX_SAFE_INTEGER) { return result; } // Leverage the exponentiation by squaring algorithm for a faster repeat. // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. do { if (n % 2) { result += string; } n = nativeFloor(n / 2); if (n) { string += string; } } while (n); return result; } /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } /** * The base implementation of `_.sample`. * * @private * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. */ function baseSample(collection) { return arraySample(values(collection)); } /** * The base implementation of `_.sampleSize` without param guards. * * @private * @param {Array|Object} collection The collection to sample. * @param {number} n The number of elements to sample. * @returns {Array} Returns the random elements. */ function baseSampleSize(collection, n) { var array = values(collection); return shuffleSelf(array, baseClamp(n, 0, array.length)); } /** * The base implementation of `_.set`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseSet(object, path, value, customizer) { if (!isObject(object)) { return object; } path = castPath(path, object); var index = -1, length = path.length, lastIndex = length - 1, nested = object; while (nested != null && ++index < length) { var key = toKey(path[index]), newValue = value; if (key === '__proto__' || key === 'constructor' || key === 'prototype') { return object; } if (index != lastIndex) { var objValue = nested[key]; newValue = customizer ? customizer(objValue, key, nested) : undefined; if (newValue === undefined) { newValue = isObject(objValue) ? objValue : (isIndex(path[index + 1]) ? [] : {}); } } assignValue(nested, key, newValue); nested = nested[key]; } return object; } /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; /** * The base implementation of `_.shuffle`. * * @private * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. */ function baseShuffle(collection) { return shuffleSelf(values(collection)); } /** * The base implementation of `_.slice` without an iteratee call guard. * * @private * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function baseSlice(array, start, end) { var index = -1, length = array.length; if (start < 0) { start = -start > length ? 0 : (length + start); } end = end > length ? length : end; if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } /** * The base implementation of `_.some` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } /** * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which * performs a binary search of `array` to determine the index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndex(array, value, retHighest) { var low = 0, high = array == null ? low : array.length; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (computed !== null && !isSymbol(computed) && (retHighest ? (computed <= value) : (computed < value))) { low = mid + 1; } else { high = mid; } } return high; } return baseSortedIndexBy(array, value, identity, retHighest); } /** * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` * which invokes `iteratee` for `value` and each element of `array` to compute * their sort ranking. The iteratee is invoked with one argument; (value). * * @private * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} iteratee The iteratee invoked per element. * @param {boolean} [retHighest] Specify returning the highest qualified index. * @returns {number} Returns the index at which `value` should be inserted * into `array`. */ function baseSortedIndexBy(array, value, iteratee, retHighest) { var low = 0, high = array == null ? 0 : array.length; if (high === 0) { return 0; } value = iteratee(value); var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined; while (low < high) { var mid = nativeFloor((low + high) / 2), computed = iteratee(array[mid]), othIsDefined = computed !== undefined, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed); if (valIsNaN) { var setLow = retHighest || othIsReflexive; } else if (valIsUndefined) { setLow = othIsReflexive && (retHighest || othIsDefined); } else if (valIsNull) { setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); } else if (valIsSymbol) { setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); } else if (othIsNull || othIsSymbol) { setLow = false; } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } /** * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseSortedUniq(array, iteratee) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; if (!index || !eq(computed, seen)) { var seen = computed; result[resIndex++] = value === 0 ? 0 : value; } } return result; } /** * The base implementation of `_.toNumber` which doesn't ensure correct * conversions of binary, hexadecimal, or octal string values. * * @private * @param {*} value The value to process. * @returns {number} Returns the number. */ function baseToNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } return +value; } /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } /** * The base implementation of `_.unset`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The property path to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ function baseUnset(object, path) { path = castPath(path, object); object = parent(object, path); return object == null || delete object[toKey(last(path))]; } /** * The base implementation of `_.update`. * * @private * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to update. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize path creation. * @returns {Object} Returns `object`. */ function baseUpdate(object, path, updater, customizer) { return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** * The base implementation of methods like `_.dropWhile` and `_.takeWhile` * without support for iteratee shorthands. * * @private * @param {Array} array The array to query. * @param {Function} predicate The function invoked per iteration. * @param {boolean} [isDrop] Specify dropping elements instead of taking them. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Array} Returns the slice of `array`. */ function baseWhile(array, predicate, isDrop, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) {} return isDrop ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); } /** * The base implementation of `wrapperValue` which returns the result of * performing a sequence of actions on the unwrapped `value`, where each * successive action is supplied the return value of the previous. * * @private * @param {*} value The unwrapped value. * @param {Array} actions Actions to perform to resolve the unwrapped value. * @returns {*} Returns the resolved value. */ function baseWrapperValue(value, actions) { var result = value; if (result instanceof LazyWrapper) { result = result.value(); } return arrayReduce(actions, function(result, action) { return action.func.apply(action.thisArg, arrayPush([result], action.args)); }, result); } /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * * @private * @param {Array} props The property identifiers. * @param {Array} values The property values. * @param {Function} assignFunc The function to assign values. * @returns {Object} Returns the new object. */ function baseZipObject(props, values, assignFunc) { var index = -1, length = props.length, valsLength = values.length, result = {}; while (++index < length) { var value = index < valsLength ? values[index] : undefined; assignFunc(result, props[index], value); } return result; } /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } /** * Casts `value` to `identity` if it's not a function. * * @private * @param {*} value The value to inspect. * @returns {Function} Returns cast function. */ function castFunction(value) { return typeof value == 'function' ? value : identity; } /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** * A `baseRest` alias which can be replaced with `identity` by module * replacement plugins. * * @private * @type {Function} * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ var castRest = baseRest; /** * Casts `array` to a slice if it's needed. * * @private * @param {Array} array The array to inspect. * @param {number} start The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the cast slice. */ function castSlice(array, start, end) { var length = array.length; end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } /** * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * * @private * @param {number|Object} id The timer id or timeout object of the timer to clear. */ var clearTimeout = ctxClearTimeout || function(id) { return root.clearTimeout(id); }; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } /** * Compares values to sort them in ascending order. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {number} Returns the sort order indicator for `value`. */ function compareAscending(value, other) { if (value !== other) { var valIsDefined = value !== undefined, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value); var othIsDefined = other !== undefined, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other); if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || (valIsNull && othIsDefined && othIsReflexive) || (!valIsDefined && othIsReflexive) || !valIsReflexive) { return 1; } if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || (othIsNull && valIsDefined && valIsReflexive) || (!othIsDefined && valIsReflexive) || !othIsReflexive) { return -1; } } return 0; } /** * Used by `_.orderBy` to compare multiple properties of a value to another * and stable sort them. * * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, * specify an order of "desc" for descending or "asc" for ascending sort order * of corresponding values. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {boolean[]|string[]} orders The order to sort by for each property. * @returns {number} Returns the sort order indicator for `object`. */ function compareMultiple(object, other, orders) { var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; while (++index < length) { var result = compareAscending(objCriteria[index], othCriteria[index]); if (result) { if (index >= ordersLength) { return result; } var order = orders[index]; return result * (order == 'desc' ? -1 : 1); } } // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications // that causes it, under certain circumstances, to provide the same value for // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 // for more details. // // This also ensures a stable sort in V8 and other engines. // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. return object.index - other.index; } /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } /** * Creates a function like `_.lowerFirst`. * * @private * @param {string} methodName The name of the `String` case method to use. * @returns {Function} Returns the new case function. */ function createCaseFirst(methodName) { return function(string) { string = toString(string); var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined; var chr = strSymbols ? strSymbols[0] : string.charAt(0); var trailing = strSymbols ? castSlice(strSymbols, 1).join('') : string.slice(1); return chr[methodName]() + trailing; }; } /** * Creates a function like `_.camelCase`. * * @private * @param {Function} callback The function to combine each word. * @returns {Function} Returns the new compounder function. */ function createCompounder(callback) { return function(string) { return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); }; } /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } /** * Creates a `_.find` or `_.findLast` function. * * @private * @param {Function} findIndexFunc The function to find the collection index. * @returns {Function} Returns the new find function. */ function createFind(findIndexFunc) { return function(collection, predicate, fromIndex) { var iterable = Object(collection); if (!isArrayLike(collection)) { var iteratee = getIteratee(predicate, 3); collection = keys(collection); predicate = function(key) { return iteratee(iterable[key], key, iterable); }; } var index = findIndexFunc(collection, predicate, fromIndex); return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; }; } /** * Creates a `_.flow` or `_.flowRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new flow function. */ function createFlow(fromRight) { return flatRest(function(funcs) { var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; if (fromRight) { funcs.reverse(); } while (index--) { var func = funcs[index]; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (prereq && !wrapper && getFuncName(func) == 'wrapper') { var wrapper = new LodashWrapper([], true); } } index = wrapper ? index : length; while (++index < length) { func = funcs[index]; var funcName = getFuncName(func), data = funcName == 'wrapper' ? getData(func) : undefined; if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1 ) { wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); } else { wrapper = (func.length == 1 && isLaziable(func)) ? wrapper[funcName]() : wrapper.thru(func); } } return function() { var args = arguments, value = args[0]; if (wrapper && args.length == 1 && isArray(value)) { return wrapper.plant(value).value(); } var index = 0, result = length ? funcs[index].apply(this, args) : value; while (++index < length) { result = funcs[index].call(this, result); } return result; }; }); } /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } /** * Creates a function that performs a mathematical operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @param {number} [defaultValue] The value used for `undefined` arguments. * @returns {Function} Returns the new mathematical operation function. */ function createMathOperation(operator, defaultValue) { return function(value, other) { var result; if (value === undefined && other === undefined) { return defaultValue; } if (value !== undefined) { result = value; } if (other !== undefined) { if (result === undefined) { return other; } if (typeof value == 'string' || typeof other == 'string') { value = baseToString(value); other = baseToString(other); } else { value = baseToNumber(value); other = baseToNumber(other); } result = operator(value, other); } return result; }; } /** * Creates a function like `_.over`. * * @private * @param {Function} arrayFunc The function to iterate over iteratees. * @returns {Function} Returns the new over function. */ function createOver(arrayFunc) { return flatRest(function(iteratees) { iteratees = arrayMap(iteratees, baseUnary(getIteratee())); return baseRest(function(args) { var thisArg = this; return arrayFunc(iteratees, function(iteratee) { return apply(iteratee, thisArg, args); }); }); }); } /** * Creates the padding for `string` based on `length`. The `chars` string * is truncated if the number of characters exceeds `length`. * * @private * @param {number} length The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padding for `string`. */ function createPadding(length, chars) { chars = chars === undefined ? ' ' : baseToString(chars); var charsLength = chars.length; if (charsLength < 2) { return charsLength ? baseRepeat(chars, length) : chars; } var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); return hasUnicode(chars) ? castSlice(stringToArray(result), 0, length).join('') : result.slice(0, length); } /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } /** * Creates a `_.range` or `_.rangeRight` function. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new range function. */ function createRange(fromRight) { return function(start, end, step) { if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { end = step = undefined; } // Ensure the sign of `-0` is preserved. start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); return baseRange(start, end, step, fromRight); }; } /** * Creates a function that performs a relational operation on two values. * * @private * @param {Function} operator The function to perform the operation. * @returns {Function} Returns the new relational operation function. */ function createRelationalOperation(operator) { return function(value, other) { if (!(typeof value == 'string' && typeof other == 'string')) { value = toNumber(value); other = toNumber(other); } return operator(value, other); }; } /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } /** * Creates a function like `_.round`. * * @private * @param {string} methodName The name of the `Math` method to use when rounding. * @returns {Function} Returns the new round function. */ function createRound(methodName) { var func = Math[methodName]; return function(number, precision) { number = toNumber(number); precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); if (precision && nativeIsFinite(number)) { // Shift with exponential notation to avoid floating-point issues. // See [MDN](https://mdn.io/round#Examples) for more details. var pair = (toString(number) + 'e').split('e'), value = func(pair[0] + 'e' + (+pair[1] + precision)); pair = (toString(value) + 'e').split('e'); return +(pair[0] + 'e' + (+pair[1] - precision)); } return func(number); }; } /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; /** * Creates a `_.toPairs` or `_.toPairsIn` function. * * @private * @param {Function} keysFunc The function to get the keys of a given object. * @returns {Function} Returns the new pairs function. */ function createToPairs(keysFunc) { return function(object) { var tag = getTag(object); if (tag == mapTag) { return mapToArray(object); } if (tag == setTag) { return setToPairs(object); } return baseToPairs(object, keysFunc(object)); }; } /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } /** * Used by `_.defaults` to customize its `_.assignIn` use to assign properties * of source objects to the destination object for all destination properties * that resolve to `undefined`. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function customDefaultsAssignIn(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } /** * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source * objects into destination objects that are passed thru. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to merge. * @param {Object} object The parent object of `objValue`. * @param {Object} source The parent object of `srcValue`. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. * @returns {*} Returns the value to assign. */ function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { if (isObject(objValue) && isObject(srcValue)) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, objValue); baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); stack['delete'](srcValue); } return objValue; } /** * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain * objects. * * @private * @param {*} value The value to inspect. * @param {string} key The key of the property to inspect. * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. */ function customOmitClone(value) { return isPlainObject(value) ? undefined : value; } /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Check that cyclic values are equal. var arrStacked = stack.get(array); var othStacked = stack.get(other); if (arrStacked && othStacked) { return arrStacked == other && othStacked == array; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Check that cyclic values are equal. var objStacked = stack.get(object); var othStacked = stack.get(other); if (objStacked && othStacked) { return objStacked == other && othStacked == object; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; return object.placeholder; } /** * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, * this function returns the custom method, otherwise it returns `baseIteratee`. * If arguments are provided, the chosen function is invoked with them and * its result is returned. * * @private * @param {*} [value] The value to convert to an iteratee. * @param {number} [arity] The arity of the created iteratee. * @returns {Function} Returns the chosen function or its result. */ function getIteratee() { var result = lodash.iteratee || iteratee; result = result === iteratee ? baseIteratee : result; return arguments.length ? result(arguments[0], arguments[1]) : result; } /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } /** * Gets the view, applying any `transforms` to the `start` and `end` positions. * * @private * @param {number} start The start of the view. * @param {number} end The end of the view. * @param {Array} transforms The transformations to apply to the view. * @returns {Object} Returns an object containing the `start` and `end` * positions of the view. */ function getView(start, end, transforms) { var index = -1, length = transforms.length; while (++index < length) { var data = transforms[index], size = data.size; switch (data.type) { case 'drop': start += size; break; case 'dropRight': end -= size; break; case 'take': end = nativeMin(end, start + size); break; case 'takeRight': start = nativeMax(start, end - size); break; } } return { 'start': start, 'end': end }; } /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = new array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return new Ctor; case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return new Ctor; case symbolTag: return cloneSymbol(object); } } /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { var type = typeof value; length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (type == 'number' || (type != 'symbol' && reIsUint.test(value))) && (value > -1 && value % 1 == 0 && value < length); } /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } /** * Checks if `func` is capable of being masked. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ var isMaskable = coreJsData ? isFunction : stubFalse; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } /** * Gets the parent value at `path` of `object`. * * @private * @param {Object} object The object to query. * @param {Array} path The path to get the parent value of. * @returns {*} Returns the parent value. */ function parent(object, path) { return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } /** * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * * @private * @param {Object} object The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function safeGet(object, key) { if (key === 'constructor' && typeof object[key] === 'function') { return; } if (key == '__proto__') { return; } return object[key]; } /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); /** * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * * @private * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @returns {number|Object} Returns the timer id or timeout object. */ var setTimeout = ctxSetTimeout || function(func, wait) { return root.setTimeout(func, wait); }; /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } /** * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * * @private * @param {Array} array The array to shuffle. * @param {number} [size=array.length] The size of `array`. * @returns {Array} Returns `array`. */ function shuffleSelf(array, size) { var index = -1, length = array.length, lastIndex = length - 1; size = size === undefined ? length : size; while (++index < size) { var rand = baseRandom(index, lastIndex), value = array[rand]; array[rand] = array[index]; array[index] = value; } array.length = size; return array; } /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (string.charCodeAt(0) === 46 /* . */) { result.push(''); } string.replace(rePropName, function(match, number, quote, subString) { result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } /*------------------------------------------------------------------------*/ /** * Creates an array of elements split into groups the length of `size`. * If `array` can't be split evenly, the final chunk will be the remaining * elements. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to process. * @param {number} [size=1] The length of each chunk * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the new array of chunks. * @example * * _.chunk(['a', 'b', 'c', 'd'], 2); * // => [['a', 'b'], ['c', 'd']] * * _.chunk(['a', 'b', 'c', 'd'], 3); * // => [['a', 'b', 'c'], ['d']] */ function chunk(array, size, guard) { if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { size = 1; } else { size = nativeMax(toInteger(size), 0); } var length = array == null ? 0 : array.length; if (!length || size < 1) { return []; } var index = 0, resIndex = 0, result = Array(nativeCeil(length / size)); while (index < length) { result[resIndex++] = baseSlice(array, index, (index += size)); } return result; } /** * Creates an array with all falsey values removed. The values `false`, `null`, * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to compact. * @returns {Array} Returns the new array of filtered values. * @example * * _.compact([0, 1, false, 2, '', 3]); * // => [1, 2, 3] */ function compact(array) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value) { result[resIndex++] = value; } } return result; } /** * Creates a new array concatenating `array` with any additional arrays * and/or values. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to concatenate. * @param {...*} [values] The values to concatenate. * @returns {Array} Returns the new concatenated array. * @example * * var array = [1]; * var other = _.concat(array, 2, [3], [[4]]); * * console.log(other); * // => [1, 2, 3, [4]] * * console.log(array); * // => [1] */ function concat() { var length = arguments.length; if (!length) { return []; } var args = Array(length - 1), array = arguments[0], index = length; while (index--) { args[index - 1] = arguments[index]; } return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); } /** * Creates an array of `array` values not included in the other given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.without, _.xor * @example * * _.difference([2, 1], [2, 3]); * // => [1] */ var difference = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) : []; }); /** * This method is like `_.difference` except that it accepts `iteratee` which * is invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2] * * // The `_.property` iteratee shorthand. * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var differenceBy = baseRest(function(array, values) { var iteratee = last(values); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.difference` except that it accepts `comparator` * which is invoked to compare elements of `array` to `values`. The order and * references of result values are determined by the first array. The comparator * is invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {...Array} [values] The values to exclude. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); * // => [{ 'x': 2, 'y': 1 }] */ var differenceWith = baseRest(function(array, values) { var comparator = last(values); if (isArrayLikeObject(comparator)) { comparator = undefined; } return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) : []; }); /** * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ * @since 0.5.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.drop([1, 2, 3]); * // => [2, 3] * * _.drop([1, 2, 3], 2); * // => [3] * * _.drop([1, 2, 3], 5); * // => [] * * _.drop([1, 2, 3], 0); * // => [1, 2, 3] */ function drop(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to drop. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.dropRight([1, 2, 3]); * // => [1, 2] * * _.dropRight([1, 2, 3], 2); * // => [1] * * _.dropRight([1, 2, 3], 5); * // => [] * * _.dropRight([1, 2, 3], 0); * // => [1, 2, 3] */ function dropRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` excluding elements dropped from the end. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.dropRightWhile(users, function(o) { return !o.active; }); * // => objects for ['barney'] * * // The `_.matches` iteratee shorthand. * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['barney', 'fred'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropRightWhile(users, ['active', false]); * // => objects for ['barney'] * * // The `_.property` iteratee shorthand. * _.dropRightWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; } /** * Creates a slice of `array` excluding elements dropped from the beginning. * Elements are dropped until `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.dropWhile(users, function(o) { return !o.active; }); * // => objects for ['pebbles'] * * // The `_.matches` iteratee shorthand. * _.dropWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['fred', 'pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.dropWhile(users, ['active', false]); * // => objects for ['pebbles'] * * // The `_.property` iteratee shorthand. * _.dropWhile(users, 'active'); * // => objects for ['barney', 'fred', 'pebbles'] */ function dropWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), true) : []; } /** * Fills elements of `array` with `value` from `start` up to, but not * including, `end`. * * **Note:** This method mutates `array`. * * @static * @memberOf _ * @since 3.2.0 * @category Array * @param {Array} array The array to fill. * @param {*} value The value to fill `array` with. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.fill(array, 'a'); * console.log(array); * // => ['a', 'a', 'a'] * * _.fill(Array(3), 2); * // => [2, 2, 2] * * _.fill([4, 6, 8, 10], '*', 1, 3); * // => [4, '*', '*', 10] */ function fill(array, value, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { start = 0; end = length; } return baseFill(array, value, start, end); } /** * This method is like `_.find` except that it returns the index of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.findIndex(users, function(o) { return o.user == 'barney'; }); * // => 0 * * // The `_.matches` iteratee shorthand. * _.findIndex(users, { 'user': 'fred', 'active': false }); * // => 1 * * // The `_.matchesProperty` iteratee shorthand. * _.findIndex(users, ['active', false]); * // => 0 * * // The `_.property` iteratee shorthand. * _.findIndex(users, 'active'); * // => 2 */ function findIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseFindIndex(array, getIteratee(predicate, 3), index); } /** * This method is like `_.findIndex` except that it iterates over elements * of `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the found element, else `-1`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); * // => 2 * * // The `_.matches` iteratee shorthand. * _.findLastIndex(users, { 'user': 'barney', 'active': true }); * // => 0 * * // The `_.matchesProperty` iteratee shorthand. * _.findLastIndex(users, ['active', false]); * // => 2 * * // The `_.property` iteratee shorthand. * _.findLastIndex(users, 'active'); * // => 0 */ function findLastIndex(array, predicate, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length - 1; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } /** * Recursively flattens `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flattenDeep([1, [2, [3, [4]], 5]]); * // => [1, 2, 3, 4, 5] */ function flattenDeep(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, INFINITY) : []; } /** * Recursively flatten `array` up to `depth` times. * * @static * @memberOf _ * @since 4.4.0 * @category Array * @param {Array} array The array to flatten. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * var array = [1, [2, [3, [4]], 5]]; * * _.flattenDepth(array, 1); * // => [1, 2, [3, [4]], 5] * * _.flattenDepth(array, 2); * // => [1, 2, 3, [4], 5] */ function flattenDepth(array, depth) { var length = array == null ? 0 : array.length; if (!length) { return []; } depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(array, depth); } /** * The inverse of `_.toPairs`; this method returns an object composed * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} pairs The key-value pairs. * @returns {Object} Returns the new object. * @example * * _.fromPairs([['a', 1], ['b', 2]]); * // => { 'a': 1, 'b': 2 } */ function fromPairs(pairs) { var index = -1, length = pairs == null ? 0 : pairs.length, result = {}; while (++index < length) { var pair = pairs[index]; result[pair[0]] = pair[1]; } return result; } /** * Gets the first element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @alias first * @category Array * @param {Array} array The array to query. * @returns {*} Returns the first element of `array`. * @example * * _.head([1, 2, 3]); * // => 1 * * _.head([]); * // => undefined */ function head(array) { return (array && array.length) ? array[0] : undefined; } /** * Gets the index at which the first occurrence of `value` is found in `array` * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. If `fromIndex` is negative, it's used as the * offset from the end of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.indexOf([1, 2, 1, 2], 2); * // => 1 * * // Search from the `fromIndex`. * _.indexOf([1, 2, 1, 2], 2, 2); * // => 3 */ function indexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = fromIndex == null ? 0 : toInteger(fromIndex); if (index < 0) { index = nativeMax(length + index, 0); } return baseIndexOf(array, value, index); } /** * Gets all but the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.initial([1, 2, 3]); * // => [1, 2] */ function initial(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 0, -1) : []; } /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); /** * This method is like `_.intersection` except that it accepts `iteratee` * which is invoked for each element of each `arrays` to generate the criterion * by which they're compared. The order and references of result values are * determined by the first array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [2.1] * * // The `_.property` iteratee shorthand. * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }] */ var intersectionBy = baseRest(function(arrays) { var iteratee = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); if (iteratee === last(mapped)) { iteratee = undefined; } else { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, getIteratee(iteratee, 2)) : []; }); /** * This method is like `_.intersection` except that it accepts `comparator` * which is invoked to compare elements of `arrays`. The order and references * of result values are determined by the first array. The comparator is * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of intersecting values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.intersectionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }] */ var intersectionWith = baseRest(function(arrays) { var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); comparator = typeof comparator == 'function' ? comparator : undefined; if (comparator) { mapped.pop(); } return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped, undefined, comparator) : []; }); /** * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to convert. * @param {string} [separator=','] The element separator. * @returns {string} Returns the joined string. * @example * * _.join(['a', 'b', 'c'], '~'); * // => 'a~b~c' */ function join(array, separator) { return array == null ? '' : nativeJoin.call(array, separator); } /** * Gets the last element of `array`. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @returns {*} Returns the last element of `array`. * @example * * _.last([1, 2, 3]); * // => 3 */ function last(array) { var length = array == null ? 0 : array.length; return length ? array[length - 1] : undefined; } /** * This method is like `_.indexOf` except that it iterates over elements of * `array` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=array.length-1] The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.lastIndexOf([1, 2, 1, 2], 2); * // => 3 * * // Search from the `fromIndex`. * _.lastIndexOf([1, 2, 1, 2], 2, 2); * // => 1 */ function lastIndexOf(array, value, fromIndex) { var length = array == null ? 0 : array.length; if (!length) { return -1; } var index = length; if (fromIndex !== undefined) { index = toInteger(fromIndex); index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); } return value === value ? strictLastIndexOf(array, value, index) : baseFindIndex(array, baseIsNaN, index, true); } /** * Gets the element at index `n` of `array`. If `n` is negative, the nth * element from the end is returned. * * @static * @memberOf _ * @since 4.11.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=0] The index of the element to return. * @returns {*} Returns the nth element of `array`. * @example * * var array = ['a', 'b', 'c', 'd']; * * _.nth(array, 1); * // => 'b' * * _.nth(array, -2); * // => 'c'; */ function nth(array, n) { return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; } /** * Removes all given values from `array` using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` * to remove elements from an array by predicate. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {...*} [values] The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pull(array, 'a', 'c'); * console.log(array); * // => ['b', 'b'] */ var pull = baseRest(pullAll); /** * This method is like `_.pull` except that it accepts an array of values to remove. * * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @returns {Array} Returns `array`. * @example * * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * * _.pullAll(array, ['a', 'c']); * console.log(array); * // => ['b', 'b'] */ function pullAll(array, values) { return (array && array.length && values && values.length) ? basePullAll(array, values) : array; } /** * This method is like `_.pullAll` except that it accepts `iteratee` which is * invoked for each element of `array` and `values` to generate the criterion * by which they're compared. The iteratee is invoked with one argument: (value). * * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); * console.log(array); * // => [{ 'x': 2 }] */ function pullAllBy(array, values, iteratee) { return (array && array.length && values && values.length) ? basePullAll(array, values, getIteratee(iteratee, 2)) : array; } /** * This method is like `_.pullAll` except that it accepts `comparator` which * is invoked to compare elements of `array` to `values`. The comparator is * invoked with two arguments: (arrVal, othVal). * * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static * @memberOf _ * @since 4.6.0 * @category Array * @param {Array} array The array to modify. * @param {Array} values The values to remove. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns `array`. * @example * * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); * console.log(array); * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ function pullAllWith(array, values, comparator) { return (array && array.length && values && values.length) ? basePullAll(array, values, undefined, comparator) : array; } /** * Removes elements from `array` corresponding to `indexes` and returns an * array of removed elements. * * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to modify. * @param {...(number|number[])} [indexes] The indexes of elements to remove. * @returns {Array} Returns the new array of removed elements. * @example * * var array = ['a', 'b', 'c', 'd']; * var pulled = _.pullAt(array, [1, 3]); * * console.log(array); * // => ['a', 'c'] * * console.log(pulled); * // => ['b', 'd'] */ var pullAt = flatRest(function(array, indexes) { var length = array == null ? 0 : array.length, result = baseAt(array, indexes); basePullAt(array, arrayMap(indexes, function(index) { return isIndex(index, length) ? +index : index; }).sort(compareAscending)); return result; }); /** * Removes all elements from `array` that `predicate` returns truthy for * and returns an array of the removed elements. The predicate is invoked * with three arguments: (value, index, array). * * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` * to pull elements from an array by value. * * @static * @memberOf _ * @since 2.0.0 * @category Array * @param {Array} array The array to modify. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new array of removed elements. * @example * * var array = [1, 2, 3, 4]; * var evens = _.remove(array, function(n) { * return n % 2 == 0; * }); * * console.log(array); * // => [1, 3] * * console.log(evens); * // => [2, 4] */ function remove(array, predicate) { var result = []; if (!(array && array.length)) { return result; } var index = -1, indexes = [], length = array.length; predicate = getIteratee(predicate, 3); while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result.push(value); indexes.push(index); } } basePullAt(array, indexes); return result; } /** * Reverses `array` so that the first element becomes the last, the second * element becomes the second to last, and so on. * * **Note:** This method mutates `array` and is based on * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to modify. * @returns {Array} Returns `array`. * @example * * var array = [1, 2, 3]; * * _.reverse(array); * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function reverse(array) { return array == null ? array : nativeReverse.call(array); } /** * Creates a slice of `array` from `start` up to, but not including, `end`. * * **Note:** This method is used instead of * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are * returned. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to slice. * @param {number} [start=0] The start position. * @param {number} [end=array.length] The end position. * @returns {Array} Returns the slice of `array`. */ function slice(array, start, end) { var length = array == null ? 0 : array.length; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } else { start = start == null ? 0 : toInteger(start); end = end === undefined ? length : toInteger(end); } return baseSlice(array, start, end); } /** * Uses a binary search to determine the lowest index at which `value` * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedIndex([30, 50], 40); * // => 1 */ function sortedIndex(array, value) { return baseSortedIndex(array, value); } /** * This method is like `_.sortedIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 0 * * // The `_.property` iteratee shorthand. * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); * // => 0 */ function sortedIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); } /** * This method is like `_.indexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedIndexOf([4, 5, 5, 5, 6], 5); * // => 1 */ function sortedIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value); if (index < length && eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.sortedIndex` except that it returns the highest * index at which `value` should be inserted into `array` in order to * maintain its sort order. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * _.sortedLastIndex([4, 5, 5, 5, 6], 5); * // => 4 */ function sortedLastIndex(array, value) { return baseSortedIndex(array, value, true); } /** * This method is like `_.sortedLastIndex` except that it accepts `iteratee` * which is invoked for `value` and each element of `array` to compute their * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The sorted array to inspect. * @param {*} value The value to evaluate. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the index at which `value` should be inserted * into `array`. * @example * * var objects = [{ 'x': 4 }, { 'x': 5 }]; * * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); * // => 1 * * // The `_.property` iteratee shorthand. * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); * // => 1 */ function sortedLastIndexBy(array, value, iteratee) { return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** * This method is like `_.lastIndexOf` except that it performs a binary * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @returns {number} Returns the index of the matched value, else `-1`. * @example * * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); * // => 3 */ function sortedLastIndexOf(array, value) { var length = array == null ? 0 : array.length; if (length) { var index = baseSortedIndex(array, value, true) - 1; if (eq(array[index], value)) { return index; } } return -1; } /** * This method is like `_.uniq` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniq([1, 1, 2]); * // => [1, 2] */ function sortedUniq(array) { return (array && array.length) ? baseSortedUniq(array) : []; } /** * This method is like `_.uniqBy` except that it's designed and optimized * for sorted arrays. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); * // => [1.1, 2.3] */ function sortedUniqBy(array, iteratee) { return (array && array.length) ? baseSortedUniq(array, getIteratee(iteratee, 2)) : []; } /** * Gets all but the first element of `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to query. * @returns {Array} Returns the slice of `array`. * @example * * _.tail([1, 2, 3]); * // => [2, 3] */ function tail(array) { var length = array == null ? 0 : array.length; return length ? baseSlice(array, 1, length) : []; } /** * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.take([1, 2, 3]); * // => [1] * * _.take([1, 2, 3], 2); * // => [1, 2] * * _.take([1, 2, 3], 5); * // => [1, 2, 3] * * _.take([1, 2, 3], 0); * // => [] */ function take(array, n, guard) { if (!(array && array.length)) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); return baseSlice(array, 0, n < 0 ? 0 : n); } /** * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {number} [n=1] The number of elements to take. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the slice of `array`. * @example * * _.takeRight([1, 2, 3]); * // => [3] * * _.takeRight([1, 2, 3], 2); * // => [2, 3] * * _.takeRight([1, 2, 3], 5); * // => [1, 2, 3] * * _.takeRight([1, 2, 3], 0); * // => [] */ function takeRight(array, n, guard) { var length = array == null ? 0 : array.length; if (!length) { return []; } n = (guard || n === undefined) ? 1 : toInteger(n); n = length - n; return baseSlice(array, n < 0 ? 0 : n, length); } /** * Creates a slice of `array` with elements taken from the end. Elements are * taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': false } * ]; * * _.takeRightWhile(users, function(o) { return !o.active; }); * // => objects for ['fred', 'pebbles'] * * // The `_.matches` iteratee shorthand. * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); * // => objects for ['pebbles'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeRightWhile(users, ['active', false]); * // => objects for ['fred', 'pebbles'] * * // The `_.property` iteratee shorthand. * _.takeRightWhile(users, 'active'); * // => [] */ function takeRightWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; } /** * Creates a slice of `array` with elements taken from the beginning. Elements * are taken until `predicate` returns falsey. The predicate is invoked with * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 * @category Array * @param {Array} array The array to query. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the slice of `array`. * @example * * var users = [ * { 'user': 'barney', 'active': false }, * { 'user': 'fred', 'active': false }, * { 'user': 'pebbles', 'active': true } * ]; * * _.takeWhile(users, function(o) { return !o.active; }); * // => objects for ['barney', 'fred'] * * // The `_.matches` iteratee shorthand. * _.takeWhile(users, { 'user': 'barney', 'active': false }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.takeWhile(users, ['active', false]); * // => objects for ['barney', 'fred'] * * // The `_.property` iteratee shorthand. * _.takeWhile(users, 'active'); * // => [] */ function takeWhile(array, predicate) { return (array && array.length) ? baseWhile(array, getIteratee(predicate, 3)) : []; } /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); /** * This method is like `_.union` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which uniqueness is computed. Result values are chosen from the first * array in which the value occurs. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * _.unionBy([2.1], [1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ var unionBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); }); /** * This method is like `_.union` except that it accepts `comparator` which * is invoked to compare elements of `arrays`. Result values are chosen from * the first array in which the value occurs. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of combined values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.unionWith(objects, others, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var unionWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); }); /** * Creates a duplicate-free version of an array, using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons, in which only the first occurrence of each element * is kept. The order of result values is determined by the order they occur * in the array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniq([2, 1, 2]); * // => [2, 1] */ function uniq(array) { return (array && array.length) ? baseUniq(array) : []; } /** * This method is like `_.uniq` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * uniqueness is computed. The order of result values is determined by the * order they occur in the array. The iteratee is invoked with one argument: * (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * _.uniqBy([2.1, 1.2, 2.3], Math.floor); * // => [2.1, 1.2] * * // The `_.property` iteratee shorthand. * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 1 }, { 'x': 2 }] */ function uniqBy(array, iteratee) { return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** * This method is like `_.uniq` except that it accepts `comparator` which * is invoked to compare elements of `array`. The order of result values is * determined by the order they occur in the array.The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {Array} array The array to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.uniqWith(objects, _.isEqual); * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ function uniqWith(array, comparator) { comparator = typeof comparator == 'function' ? comparator : undefined; return (array && array.length) ? baseUniq(array, undefined, comparator) : []; } /** * This method is like `_.zip` except that it accepts an array of grouped * elements and creates an array regrouping the elements to their pre-zip * configuration. * * @static * @memberOf _ * @since 1.2.0 * @category Array * @param {Array} array The array of grouped elements to process. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] * * _.unzip(zipped); * // => [['a', 'b'], [1, 2], [true, false]] */ function unzip(array) { if (!(array && array.length)) { return []; } var length = 0; array = arrayFilter(array, function(group) { if (isArrayLikeObject(group)) { length = nativeMax(group.length, length); return true; } }); return baseTimes(length, function(index) { return arrayMap(array, baseProperty(index)); }); } /** * This method is like `_.unzip` except that it accepts `iteratee` to specify * how regrouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {Array} array The array of grouped elements to process. * @param {Function} [iteratee=_.identity] The function to combine * regrouped values. * @returns {Array} Returns the new array of regrouped elements. * @example * * var zipped = _.zip([1, 2], [10, 20], [100, 200]); * // => [[1, 10, 100], [2, 20, 200]] * * _.unzipWith(zipped, _.add); * // => [3, 30, 300] */ function unzipWith(array, iteratee) { if (!(array && array.length)) { return []; } var result = unzip(array); if (iteratee == null) { return result; } return arrayMap(result, function(group) { return apply(iteratee, undefined, group); }); } /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); /** * This method is like `_.xor` except that it accepts `iteratee` which is * invoked for each element of each `arrays` to generate the criterion by * which by which they're compared. The order of result values is determined * by the order they occur in the arrays. The iteratee is invoked with one * argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); * // => [1.2, 3.4] * * // The `_.property` iteratee shorthand. * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); * // => [{ 'x': 2 }] */ var xorBy = baseRest(function(arrays) { var iteratee = last(arrays); if (isArrayLikeObject(iteratee)) { iteratee = undefined; } return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); }); /** * This method is like `_.xor` except that it accepts `comparator` which is * invoked to compare elements of `arrays`. The order of result values is * determined by the order they occur in the arrays. The comparator is invoked * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. * @example * * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * * _.xorWith(objects, others, _.isEqual); * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ var xorWith = baseRest(function(arrays) { var comparator = last(arrays); comparator = typeof comparator == 'function' ? comparator : undefined; return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); }); /** * Creates an array of grouped elements, the first of which contains the * first elements of the given arrays, the second of which contains the * second elements of the given arrays, and so on. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zip(['a', 'b'], [1, 2], [true, false]); * // => [['a', 1, true], ['b', 2, false]] */ var zip = baseRest(unzip); /** * This method is like `_.fromPairs` except that it accepts two arrays, * one of property identifiers and one of corresponding values. * * @static * @memberOf _ * @since 0.4.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObject(['a', 'b'], [1, 2]); * // => { 'a': 1, 'b': 2 } */ function zipObject(props, values) { return baseZipObject(props || [], values || [], assignValue); } /** * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ * @since 4.1.0 * @category Array * @param {Array} [props=[]] The property identifiers. * @param {Array} [values=[]] The property values. * @returns {Object} Returns the new object. * @example * * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ function zipObjectDeep(props, values) { return baseZipObject(props || [], values || [], baseSet); } /** * This method is like `_.zip` except that it accepts `iteratee` to specify * how grouped values should be combined. The iteratee is invoked with the * elements of each group: (...group). * * @static * @memberOf _ * @since 3.8.0 * @category Array * @param {...Array} [arrays] The arrays to process. * @param {Function} [iteratee=_.identity] The function to combine * grouped values. * @returns {Array} Returns the new array of grouped elements. * @example * * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { * return a + b + c; * }); * // => [111, 222] */ var zipWith = baseRest(function(arrays) { var length = arrays.length, iteratee = length > 1 ? arrays[length - 1] : undefined; iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; return unzipWith(arrays, iteratee); }); /*------------------------------------------------------------------------*/ /** * Creates a `lodash` wrapper instance that wraps `value` with explicit method * chain sequences enabled. The result of such sequences must be unwrapped * with `_#value`. * * @static * @memberOf _ * @since 1.3.0 * @category Seq * @param {*} value The value to wrap. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'pebbles', 'age': 1 } * ]; * * var youngest = _ * .chain(users) * .sortBy('age') * .map(function(o) { * return o.user + ' is ' + o.age; * }) * .head() * .value(); * // => 'pebbles is 1' */ function chain(value) { var result = lodash(value); result.__chain__ = true; return result; } /** * This method invokes `interceptor` and returns `value`. The interceptor * is invoked with one argument; (value). The purpose of this method is to * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ * @since 0.1.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns `value`. * @example * * _([1, 2, 3]) * .tap(function(array) { * // Mutate input array. * array.pop(); * }) * .reverse() * .value(); * // => [2, 1] */ function tap(value, interceptor) { interceptor(value); return value; } /** * This method is like `_.tap` except that it returns the result of `interceptor`. * The purpose of this method is to "pass thru" values replacing intermediate * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 * @category Seq * @param {*} value The value to provide to `interceptor`. * @param {Function} interceptor The function to invoke. * @returns {*} Returns the result of `interceptor`. * @example * * _(' abc ') * .chain() * .trim() * .thru(function(value) { * return [value]; * }) * .value(); * // => ['abc'] */ function thru(value, interceptor) { return interceptor(value); } /** * This method is the wrapper version of `_.at`. * * @name at * @memberOf _ * @since 1.0.0 * @category Seq * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _(object).at(['a[0].b.c', 'a[1]']).value(); * // => [3, 4] */ var wrapperAt = flatRest(function(paths) { var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) { return baseAt(object, paths); }; if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) { return this.thru(interceptor); } value = value.slice(start, +start + (length ? 1 : 0)); value.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(value, this.__chain__).thru(function(array) { if (length && !array.length) { array.push(undefined); } return array; }); }); /** * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. * * @name chain * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var users = [ * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 40 } * ]; * * // A sequence without explicit chaining. * _(users).head(); * // => { 'user': 'barney', 'age': 36 } * * // A sequence with explicit chaining. * _(users) * .chain() * .head() * .pick('user') * .value(); * // => { 'user': 'barney' } */ function wrapperChain() { return chain(this); } /** * Executes the chain sequence and returns the wrapped result. * * @name commit * @memberOf _ * @since 3.2.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2]; * var wrapped = _(array).push(3); * * console.log(array); * // => [1, 2] * * wrapped = wrapped.commit(); * console.log(array); * // => [1, 2, 3] * * wrapped.last(); * // => 3 * * console.log(array); * // => [1, 2, 3] */ function wrapperCommit() { return new LodashWrapper(this.value(), this.__chain__); } /** * Gets the next value on a wrapped object following the * [iterator protocol](https://mdn.io/iteration_protocols#iterator). * * @name next * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the next iterator value. * @example * * var wrapped = _([1, 2]); * * wrapped.next(); * // => { 'done': false, 'value': 1 } * * wrapped.next(); * // => { 'done': false, 'value': 2 } * * wrapped.next(); * // => { 'done': true, 'value': undefined } */ function wrapperNext() { if (this.__values__ === undefined) { this.__values__ = toArray(this.value()); } var done = this.__index__ >= this.__values__.length, value = done ? undefined : this.__values__[this.__index__++]; return { 'done': done, 'value': value }; } /** * Enables the wrapper to be iterable. * * @name Symbol.iterator * @memberOf _ * @since 4.0.0 * @category Seq * @returns {Object} Returns the wrapper object. * @example * * var wrapped = _([1, 2]); * * wrapped[Symbol.iterator]() === wrapped; * // => true * * Array.from(wrapped); * // => [1, 2] */ function wrapperToIterator() { return this; } /** * Creates a clone of the chain sequence planting `value` as the wrapped value. * * @name plant * @memberOf _ * @since 3.2.0 * @category Seq * @param {*} value The value to plant. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2]).map(square); * var other = wrapped.plant([3, 4]); * * other.value(); * // => [9, 16] * * wrapped.value(); * // => [1, 4] */ function wrapperPlant(value) { var result, parent = this; while (parent instanceof baseLodash) { var clone = wrapperClone(parent); clone.__index__ = 0; clone.__values__ = undefined; if (result) { previous.__wrapped__ = clone; } else { result = clone; } var previous = clone; parent = parent.__wrapped__; } previous.__wrapped__ = value; return result; } /** * This method is the wrapper version of `_.reverse`. * * **Note:** This method mutates the wrapped array. * * @name reverse * @memberOf _ * @since 0.1.0 * @category Seq * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var array = [1, 2, 3]; * * _(array).reverse().value() * // => [3, 2, 1] * * console.log(array); * // => [3, 2, 1] */ function wrapperReverse() { var value = this.__wrapped__; if (value instanceof LazyWrapper) { var wrapped = value; if (this.__actions__.length) { wrapped = new LazyWrapper(this); } wrapped = wrapped.reverse(); wrapped.__actions__.push({ 'func': thru, 'args': [reverse], 'thisArg': undefined }); return new LodashWrapper(wrapped, this.__chain__); } return this.thru(reverse); } /** * Executes the chain sequence to resolve the unwrapped value. * * @name value * @memberOf _ * @since 0.1.0 * @alias toJSON, valueOf * @category Seq * @returns {*} Returns the resolved unwrapped value. * @example * * _([1, 2, 3]).value(); * // => [1, 2, 3] */ function wrapperValue() { return baseWrapperValue(this.__wrapped__, this.__actions__); } /*------------------------------------------------------------------------*/ /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the number of times the key was returned by `iteratee`. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.5.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.countBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': 1, '6': 2 } * * // The `_.property` iteratee shorthand. * _.countBy(['one', 'two', 'three'], 'length'); * // => { '3': 2, '5': 1 } */ var countBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { ++result[key]; } else { baseAssignValue(result, key, 1); } }); /** * Checks if `predicate` returns truthy for **all** elements of `collection`. * Iteration is stopped once `predicate` returns falsey. The predicate is * invoked with three arguments: (value, index|key, collection). * * **Note:** This method returns `true` for * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of * elements of empty collections. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if all elements pass the predicate check, * else `false`. * @example * * _.every([true, 1, null, 'yes'], Boolean); * // => false * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.every(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.every(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.every(users, 'active'); * // => false */ function every(collection, predicate, guard) { var func = isArray(collection) ? arrayEvery : baseEvery; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning an array of all elements * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * **Note:** Unlike `_.remove`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.reject * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * _.filter(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.filter(users, { 'age': 36, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.filter(users, 'active'); * // => objects for ['barney'] * * // Combining several predicates using `_.overEvery` or `_.overSome`. * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); * // => objects for ['fred', 'barney'] */ function filter(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, getIteratee(predicate, 3)); } /** * Iterates over elements of `collection`, returning the first element * `predicate` returns truthy for. The predicate is invoked with three * arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=0] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false }, * { 'user': 'pebbles', 'age': 1, 'active': true } * ]; * * _.find(users, function(o) { return o.age < 40; }); * // => object for 'barney' * * // The `_.matches` iteratee shorthand. * _.find(users, { 'age': 1, 'active': true }); * // => object for 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.find(users, ['active', false]); * // => object for 'fred' * * // The `_.property` iteratee shorthand. * _.find(users, 'active'); * // => object for 'barney' */ var find = createFind(findIndex); /** * This method is like `_.find` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param {number} [fromIndex=collection.length-1] The index to search from. * @returns {*} Returns the matched element, else `undefined`. * @example * * _.findLast([1, 2, 3, 4], function(n) { * return n % 2 == 1; * }); * // => 3 */ var findLast = createFind(findLastIndex); /** * Creates a flattened array of values by running each element in `collection` * thru `iteratee` and flattening the mapped results. The iteratee is invoked * with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [n, n]; * } * * _.flatMap([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMap(collection, iteratee) { return baseFlatten(map(collection, iteratee), 1); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDeep([1, 2], duplicate); * // => [1, 1, 2, 2] */ function flatMapDeep(collection, iteratee) { return baseFlatten(map(collection, iteratee), INFINITY); } /** * This method is like `_.flatMap` except that it recursively flattens the * mapped results up to `depth` times. * * @static * @memberOf _ * @since 4.7.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {number} [depth=1] The maximum recursion depth. * @returns {Array} Returns the new flattened array. * @example * * function duplicate(n) { * return [[[n, n]]]; * } * * _.flatMapDepth([1, 2], duplicate, 2); * // => [[1, 1], [2, 2]] */ function flatMapDepth(collection, iteratee, depth) { depth = depth === undefined ? 1 : toInteger(depth); return baseFlatten(map(collection, iteratee), depth); } /** * Iterates over elements of `collection` and invokes `iteratee` for each element. * The iteratee is invoked with three arguments: (value, index|key, collection). * Iteratee functions may exit iteration early by explicitly returning `false`. * * **Note:** As with other "Collections" methods, objects with a "length" * property are iterated like arrays. To avoid this behavior use `_.forIn` * or `_.forOwn` for object iteration. * * @static * @memberOf _ * @since 0.1.0 * @alias each * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEachRight * @example * * _.forEach([1, 2], function(value) { * console.log(value); * }); * // => Logs `1` then `2`. * * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forEach(collection, iteratee) { var func = isArray(collection) ? arrayEach : baseEach; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.forEach` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 2.0.0 * @alias eachRight * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array|Object} Returns `collection`. * @see _.forEach * @example * * _.forEachRight([1, 2], function(value) { * console.log(value); * }); * // => Logs `2` then `1`. */ function forEachRight(collection, iteratee) { var func = isArray(collection) ? arrayEachRight : baseEachRight; return func(collection, getIteratee(iteratee, 3)); } /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); /** * Checks if `value` is in `collection`. If `collection` is a string, it's * checked for a substring of `value`, otherwise * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * is used for equality comparisons. If `fromIndex` is negative, it's used as * the offset from the end of `collection`. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @param {*} value The value to search for. * @param {number} [fromIndex=0] The index to search from. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {boolean} Returns `true` if `value` is found, else `false`. * @example * * _.includes([1, 2, 3], 1); * // => true * * _.includes([1, 2, 3], 1, 2); * // => false * * _.includes({ 'a': 1, 'b': 2 }, 1); * // => true * * _.includes('abcd', 'bc'); * // => true */ function includes(collection, value, fromIndex, guard) { collection = isArrayLike(collection) ? collection : values(collection); fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; var length = collection.length; if (fromIndex < 0) { fromIndex = nativeMax(length + fromIndex, 0); } return isString(collection) ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) : (!!length && baseIndexOf(collection, value, fromIndex) > -1); } /** * Invokes the method at `path` of each element in `collection`, returning * an array of the results of each invoked method. Any additional arguments * are provided to each invoked method. If `path` is a function, it's invoked * for, and `this` bound to, each element in `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array|Function|string} path The path of the method to invoke or * the function invoked per iteration. * @param {...*} [args] The arguments to invoke each method with. * @returns {Array} Returns the array of results. * @example * * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); * // => [[1, 5, 7], [1, 2, 3]] * * _.invokeMap([123, 456], String.prototype.split, ''); * // => [['1', '2', '3'], ['4', '5', '6']] */ var invokeMap = baseRest(function(collection, path, args) { var index = -1, isFunc = typeof path == 'function', result = isArrayLike(collection) ? Array(collection.length) : []; baseEach(collection, function(value) { result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); }); return result; }); /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The corresponding value of * each key is the last element responsible for generating the key. The * iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * var array = [ * { 'dir': 'left', 'code': 97 }, * { 'dir': 'right', 'code': 100 } * ]; * * _.keyBy(array, function(o) { * return String.fromCharCode(o.code); * }); * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } * * _.keyBy(array, 'dir'); * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } */ var keyBy = createAggregator(function(result, value, key) { baseAssignValue(result, key, value); }); /** * Creates an array of values by running each element in `collection` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. * * The guarded methods are: * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, * `template`, `trim`, `trimEnd`, `trimStart`, and `words` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the new mapped array. * @example * * function square(n) { * return n * n; * } * * _.map([4, 8], square); * // => [16, 64] * * _.map({ 'a': 4, 'b': 8 }, square); * // => [16, 64] (iteration order is not guaranteed) * * var users = [ * { 'user': 'barney' }, * { 'user': 'fred' } * ]; * * // The `_.property` iteratee shorthand. * _.map(users, 'user'); * // => ['barney', 'fred'] */ function map(collection, iteratee) { var func = isArray(collection) ? arrayMap : baseMap; return func(collection, getIteratee(iteratee, 3)); } /** * This method is like `_.sortBy` except that it allows specifying the sort * orders of the iteratees to sort by. If `orders` is unspecified, all values * are sorted in ascending order. Otherwise, specify an order of "desc" for * descending or "asc" for ascending sort order of corresponding values. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] * The iteratees to sort by. * @param {string[]} [orders] The sort orders of `iteratees`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 34 }, * { 'user': 'fred', 'age': 40 }, * { 'user': 'barney', 'age': 36 } * ]; * * // Sort by `user` in ascending order and by `age` in descending order. * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] */ function orderBy(collection, iteratees, orders, guard) { if (collection == null) { return []; } if (!isArray(iteratees)) { iteratees = iteratees == null ? [] : [iteratees]; } orders = guard ? undefined : orders; if (!isArray(orders)) { orders = orders == null ? [] : [orders]; } return baseOrderBy(collection, iteratees, orders); } /** * Creates an array of elements split into two groups, the first of which * contains elements `predicate` returns truthy for, the second of which * contains elements `predicate` returns falsey for. The predicate is * invoked with one argument: (value). * * @static * @memberOf _ * @since 3.0.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of grouped elements. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true }, * { 'user': 'pebbles', 'age': 1, 'active': false } * ]; * * _.partition(users, function(o) { return o.active; }); * // => objects for [['fred'], ['barney', 'pebbles']] * * // The `_.matches` iteratee shorthand. * _.partition(users, { 'age': 1, 'active': false }); * // => objects for [['pebbles'], ['barney', 'fred']] * * // The `_.matchesProperty` iteratee shorthand. * _.partition(users, ['active', false]); * // => objects for [['barney', 'pebbles'], ['fred']] * * // The `_.property` iteratee shorthand. * _.partition(users, 'active'); * // => objects for [['fred'], ['barney', 'pebbles']] */ var partition = createAggregator(function(result, value, key) { result[key ? 0 : 1].push(value); }, function() { return [[], []]; }); /** * Reduces `collection` to a value which is the accumulated result of running * each element in `collection` thru `iteratee`, where each successive * invocation is supplied the return value of the previous. If `accumulator` * is not given, the first element of `collection` is used as the initial * value. The iteratee is invoked with four arguments: * (accumulator, value, index|key, collection). * * Many lodash methods are guarded to work as iteratees for methods like * `_.reduce`, `_.reduceRight`, and `_.transform`. * * The guarded methods are: * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, * and `sortBy` * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduceRight * @example * * _.reduce([1, 2], function(sum, n) { * return sum + n; * }, 0); * // => 3 * * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * return result; * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) */ function reduce(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); } /** * This method is like `_.reduce` except that it iterates over elements of * `collection` from right to left. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The initial value. * @returns {*} Returns the accumulated value. * @see _.reduce * @example * * var array = [[0, 1], [2, 3], [4, 5]]; * * _.reduceRight(array, function(flattened, other) { * return flattened.concat(other); * }, []); * // => [4, 5, 2, 3, 0, 1] */ function reduceRight(collection, iteratee, accumulator) { var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); } /** * The opposite of `_.filter`; this method returns the elements of `collection` * that `predicate` does **not** return truthy for. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {Array} Returns the new filtered array. * @see _.filter * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': false }, * { 'user': 'fred', 'age': 40, 'active': true } * ]; * * _.reject(users, function(o) { return !o.active; }); * // => objects for ['fred'] * * // The `_.matches` iteratee shorthand. * _.reject(users, { 'age': 40, 'active': true }); * // => objects for ['barney'] * * // The `_.matchesProperty` iteratee shorthand. * _.reject(users, ['active', false]); * // => objects for ['fred'] * * // The `_.property` iteratee shorthand. * _.reject(users, 'active'); * // => objects for ['barney'] */ function reject(collection, predicate) { var func = isArray(collection) ? arrayFilter : baseFilter; return func(collection, negate(getIteratee(predicate, 3))); } /** * Gets a random element from `collection`. * * @static * @memberOf _ * @since 2.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @returns {*} Returns the random element. * @example * * _.sample([1, 2, 3, 4]); * // => 2 */ function sample(collection) { var func = isArray(collection) ? arraySample : baseSample; return func(collection); } /** * Gets `n` random elements at unique keys from `collection` up to the * size of `collection`. * * @static * @memberOf _ * @since 4.0.0 * @category Collection * @param {Array|Object} collection The collection to sample. * @param {number} [n=1] The number of elements to sample. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the random elements. * @example * * _.sampleSize([1, 2, 3], 2); * // => [3, 1] * * _.sampleSize([1, 2, 3], 4); * // => [2, 3, 1] */ function sampleSize(collection, n, guard) { if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } var func = isArray(collection) ? arraySampleSize : baseSampleSize; return func(collection, n); } /** * Creates an array of shuffled values, using a version of the * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to shuffle. * @returns {Array} Returns the new shuffled array. * @example * * _.shuffle([1, 2, 3, 4]); * // => [4, 1, 3, 2] */ function shuffle(collection) { var func = isArray(collection) ? arrayShuffle : baseShuffle; return func(collection); } /** * Gets the size of `collection` by returning its length for array-like * values or the number of own enumerable string keyed properties for objects. * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object|string} collection The collection to inspect. * @returns {number} Returns the collection size. * @example * * _.size([1, 2, 3]); * // => 3 * * _.size({ 'a': 1, 'b': 2 }); * // => 2 * * _.size('pebbles'); * // => 7 */ function size(collection) { if (collection == null) { return 0; } if (isArrayLike(collection)) { return isString(collection) ? stringSize(collection) : collection.length; } var tag = getTag(collection); if (tag == mapTag || tag == setTag) { return collection.size; } return baseKeys(collection).length; } /** * Checks if `predicate` returns truthy for **any** element of `collection`. * Iteration is stopped once `predicate` returns truthy. The predicate is * invoked with three arguments: (value, index|key, collection). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. * @example * * _.some([null, 0, 'yes', false], Boolean); * // => true * * var users = [ * { 'user': 'barney', 'active': true }, * { 'user': 'fred', 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.some(users, { 'user': 'barney', 'active': false }); * // => false * * // The `_.matchesProperty` iteratee shorthand. * _.some(users, ['active', false]); * // => true * * // The `_.property` iteratee shorthand. * _.some(users, 'active'); * // => true */ function some(collection, predicate, guard) { var func = isArray(collection) ? arraySome : baseSome; if (guard && isIterateeCall(collection, predicate, guard)) { predicate = undefined; } return func(collection, getIteratee(predicate, 3)); } /** * Creates an array of elements, sorted in ascending order by the results of * running each element in a collection thru each iteratee. This method * performs a stable sort, that is, it preserves the original sort order of * equal elements. The iteratees are invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to sort by. * @returns {Array} Returns the new sorted array. * @example * * var users = [ * { 'user': 'fred', 'age': 48 }, * { 'user': 'barney', 'age': 36 }, * { 'user': 'fred', 'age': 30 }, * { 'user': 'barney', 'age': 34 } * ]; * * _.sortBy(users, [function(o) { return o.user; }]); * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] * * _.sortBy(users, ['user', 'age']); * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] */ var sortBy = baseRest(function(collection, iteratees) { if (collection == null) { return []; } var length = iteratees.length; if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { iteratees = []; } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { iteratees = [iteratees[0]]; } return baseOrderBy(collection, baseFlatten(iteratees, 1), []); }); /*------------------------------------------------------------------------*/ /** * Gets the timestamp of the number of milliseconds that have elapsed since * the Unix epoch (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @since 2.4.0 * @category Date * @returns {number} Returns the timestamp. * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => Logs the number of milliseconds it took for the deferred invocation. */ var now = ctxNow || function() { return root.Date.now(); }; /*------------------------------------------------------------------------*/ /** * The opposite of `_.before`; this method creates a function that invokes * `func` once it's called `n` or more times. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {number} n The number of calls before `func` is invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var saves = ['profile', 'settings']; * * var done = _.after(saves.length, function() { * console.log('done saving!'); * }); * * _.forEach(saves, function(type) { * asyncSave({ 'type': type, 'complete': done }); * }); * // => Logs 'done saving!' after the two async saves have completed. */ function after(n, func) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n < 1) { return func.apply(this, arguments); } }; } /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } /** * Creates a function that invokes `func`, with the `this` binding and arguments * of the created function, while it's called less than `n` times. Subsequent * calls to the created function return the result of the last `func` invocation. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {number} n The number of calls at which `func` is no longer invoked. * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * jQuery(element).on('click', _.before(5, addContactToList)); * // => Allows adding up to 4 contacts to the list. */ function before(n, func) { var result; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } n = toInteger(n); return function() { if (--n > 0) { result = func.apply(this, arguments); } if (n <= 1) { func = undefined; } return result; }; } /** * Creates a function that invokes `func` with the `this` binding of `thisArg` * and `partials` prepended to the arguments it receives. * * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for partially applied arguments. * * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" * property of bound functions. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * function greet(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * * var object = { 'user': 'fred' }; * * var bound = _.bind(greet, object, 'hi'); * bound('!'); * // => 'hi fred!' * * // Bound with placeholders. * var bound = _.bind(greet, object, _, '!'); * bound('hi'); * // => 'hi fred!' */ var bind = baseRest(function(func, thisArg, partials) { var bitmask = WRAP_BIND_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bind)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(func, bitmask, thisArg, partials, holders); }); /** * Creates a function that invokes the method at `object[key]` with `partials` * prepended to the arguments it receives. * * This method differs from `_.bind` by allowing bound functions to reference * methods that may be redefined or don't yet exist. See * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) * for more details. * * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * @static * @memberOf _ * @since 0.10.0 * @category Function * @param {Object} object The object to invoke the method on. * @param {string} key The key of the method. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new bound function. * @example * * var object = { * 'user': 'fred', * 'greet': function(greeting, punctuation) { * return greeting + ' ' + this.user + punctuation; * } * }; * * var bound = _.bindKey(object, 'greet', 'hi'); * bound('!'); * // => 'hi fred!' * * object.greet = function(greeting, punctuation) { * return greeting + 'ya ' + this.user + punctuation; * }; * * bound('!'); * // => 'hiya fred!' * * // Bound with placeholders. * var bound = _.bindKey(object, 'greet', _, '!'); * bound('hi'); * // => 'hiya fred!' */ var bindKey = baseRest(function(object, key, partials) { var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; if (partials.length) { var holders = replaceHolders(partials, getHolder(bindKey)); bitmask |= WRAP_PARTIAL_FLAG; } return createWrap(key, bitmask, object, partials, holders); }); /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } /** * This method is like `_.curry` except that arguments are applied to `func` * in the manner of `_.partialRight` instead of `_.partial`. * * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curryRight(abc); * * curried(3)(2)(1); * // => [1, 2, 3] * * curried(2, 3)(1); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(3)(1, _)(2); * // => [1, 2, 3] */ function curryRight(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curryRight.placeholder; return result; } /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed `func` invocations and a `flush` method to immediately invoke them. * Provide `options` to indicate whether `func` should be invoked on the * leading and/or trailing edge of the `wait` timeout. The `func` is invoked * with the last arguments provided to the debounced function. Subsequent * calls to the debounced function return the result of the last `func` * invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the debounced function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=false] * Specify invoking on the leading edge of the timeout. * @param {number} [options.maxWait] * The maximum time `func` is allowed to be delayed before it's invoked. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // Avoid costly calculations while the window size is in flux. * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // Invoke `sendMail` when clicked, debouncing subsequent calls. * jQuery(element).on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // Ensure `batchLog` is invoked once after 1 second of debounced calls. * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); * var source = new EventSource('/stream'); * jQuery(source).on('message', debounced); * * // Cancel the trailing debounced invocation. * jQuery(window).on('popstate', debounced.cancel); */ function debounce(func, wait, options) { var lastArgs, lastThis, maxWait, result, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = toNumber(wait) || 0; if (isObject(options)) { leading = !!options.leading; maxing = 'maxWait' in options; maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; trailing = 'trailing' in options ? !!options.trailing : trailing; } function invokeFunc(time) { var args = lastArgs, thisArg = lastThis; lastArgs = lastThis = undefined; lastInvokeTime = time; result = func.apply(thisArg, args); return result; } function leadingEdge(time) { // Reset any `maxWait` timer. lastInvokeTime = time; // Start the timer for the trailing edge. timerId = setTimeout(timerExpired, wait); // Invoke the leading edge. return leading ? invokeFunc(time) : result; } function remainingWait(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; } function shouldInvoke(time) { var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; // Either this is the first call, activity has stopped and we're at the // trailing edge, the system time has gone backwards and we're treating // it as the trailing edge, or we've hit the `maxWait` limit. return (lastCallTime === undefined || (timeSinceLastCall >= wait) || (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); } function timerExpired() { var time = now(); if (shouldInvoke(time)) { return trailingEdge(time); } // Restart the timer. timerId = setTimeout(timerExpired, remainingWait(time)); } function trailingEdge(time) { timerId = undefined; // Only invoke if we have `lastArgs` which means `func` has been // debounced at least once. if (trailing && lastArgs) { return invokeFunc(time); } lastArgs = lastThis = undefined; return result; } function cancel() { if (timerId !== undefined) { clearTimeout(timerId); } lastInvokeTime = 0; lastArgs = lastCallTime = lastThis = timerId = undefined; } function flush() { return timerId === undefined ? result : trailingEdge(now()); } function debounced() { var time = now(), isInvoking = shouldInvoke(time); lastArgs = arguments; lastThis = this; lastCallTime = time; if (isInvoking) { if (timerId === undefined) { return leadingEdge(lastCallTime); } if (maxing) { // Handle invocations in a tight loop. clearTimeout(timerId); timerId = setTimeout(timerExpired, wait); return invokeFunc(lastCallTime); } } if (timerId === undefined) { timerId = setTimeout(timerExpired, wait); } return result; } debounced.cancel = cancel; debounced.flush = flush; return debounced; } /** * Defers invoking the `func` until the current call stack has cleared. Any * additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to defer. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.defer(function(text) { * console.log(text); * }, 'deferred'); * // => Logs 'deferred' after one millisecond. */ var defer = baseRest(function(func, args) { return baseDelay(func, 1, args); }); /** * Invokes `func` after `wait` milliseconds. Any additional arguments are * provided to `func` when it's invoked. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to delay. * @param {number} wait The number of milliseconds to delay invocation. * @param {...*} [args] The arguments to invoke `func` with. * @returns {number} Returns the timer id. * @example * * _.delay(function(text) { * console.log(text); * }, 1000, 'later'); * // => Logs 'later' after one second. */ var delay = baseRest(function(func, wait, args) { return baseDelay(func, toNumber(wait) || 0, args); }); /** * Creates a function that invokes `func` with arguments reversed. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to flip arguments for. * @returns {Function} Returns the new flipped function. * @example * * var flipped = _.flip(function() { * return _.toArray(arguments); * }); * * flipped('a', 'b', 'c', 'd'); * // => ['d', 'c', 'b', 'a'] */ function flip(func) { return createWrap(func, WRAP_FLIP_FLAG); } /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; /** * Creates a function that negates the result of the predicate `func`. The * `func` predicate is invoked with the `this` binding and arguments of the * created function. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} predicate The predicate to negate. * @returns {Function} Returns the new negated function. * @example * * function isEven(n) { * return n % 2 == 0; * } * * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); * // => [1, 3, 5] */ function negate(predicate) { if (typeof predicate != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return function() { var args = arguments; switch (args.length) { case 0: return !predicate.call(this); case 1: return !predicate.call(this, args[0]); case 2: return !predicate.call(this, args[0], args[1]); case 3: return !predicate.call(this, args[0], args[1], args[2]); } return !predicate.apply(this, args); }; } /** * Creates a function that is restricted to invoking `func` once. Repeat calls * to the function return the value of the first invocation. The `func` is * invoked with the `this` binding and arguments of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to restrict. * @returns {Function} Returns the new restricted function. * @example * * var initialize = _.once(createApplication); * initialize(); * initialize(); * // => `createApplication` is invoked once */ function once(func) { return before(2, func); } /** * Creates a function that invokes `func` with its arguments transformed. * * @static * @since 4.0.0 * @memberOf _ * @category Function * @param {Function} func The function to wrap. * @param {...(Function|Function[])} [transforms=[_.identity]] * The argument transforms. * @returns {Function} Returns the new function. * @example * * function doubled(n) { * return n * 2; * } * * function square(n) { * return n * n; * } * * var func = _.overArgs(function(x, y) { * return [x, y]; * }, [square, doubled]); * * func(9, 3); * // => [81, 6] * * func(10, 5); * // => [100, 10] */ var overArgs = castRest(function(func, transforms) { transforms = (transforms.length == 1 && isArray(transforms[0])) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); var funcsLength = transforms.length; return baseRest(function(args) { var index = -1, length = nativeMin(args.length, funcsLength); while (++index < length) { args[index] = transforms[index].call(this, args[index]); } return apply(func, this, args); }); }); /** * Creates a function that invokes `func` with `partials` prepended to the * arguments it receives. This method is like `_.bind` except it does **not** * alter the `this` binding. * * The `_.partial.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 0.2.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var sayHelloTo = _.partial(greet, 'hello'); * sayHelloTo('fred'); * // => 'hello fred' * * // Partially applied with placeholders. * var greetFred = _.partial(greet, _, 'fred'); * greetFred('hi'); * // => 'hi fred' */ var partial = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partial)); return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); }); /** * This method is like `_.partial` except that partially applied arguments * are appended to the arguments it receives. * * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic * builds, may be used as a placeholder for partially applied arguments. * * **Note:** This method doesn't set the "length" property of partially * applied functions. * * @static * @memberOf _ * @since 1.0.0 * @category Function * @param {Function} func The function to partially apply arguments to. * @param {...*} [partials] The arguments to be partially applied. * @returns {Function} Returns the new partially applied function. * @example * * function greet(greeting, name) { * return greeting + ' ' + name; * } * * var greetFred = _.partialRight(greet, 'fred'); * greetFred('hi'); * // => 'hi fred' * * // Partially applied with placeholders. * var sayHelloTo = _.partialRight(greet, 'hello', _); * sayHelloTo('fred'); * // => 'hello fred' */ var partialRight = baseRest(function(func, partials) { var holders = replaceHolders(partials, getHolder(partialRight)); return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); }); /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as * an array. * * **Note:** This method is based on the * [rest parameter](https://mdn.io/rest_parameters). * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.rest(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function rest(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start === undefined ? start : toInteger(start); return baseRest(func, start); } /** * Creates a function that invokes `func` with the `this` binding of the * create function and an array of arguments much like * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). * * **Note:** This method is based on the * [spread operator](https://mdn.io/spread_operator). * * @static * @memberOf _ * @since 3.2.0 * @category Function * @param {Function} func The function to spread arguments over. * @param {number} [start=0] The start position of the spread. * @returns {Function} Returns the new function. * @example * * var say = _.spread(function(who, what) { * return who + ' says ' + what; * }); * * say(['fred', 'hello']); * // => 'fred says hello' * * var numbers = Promise.all([ * Promise.resolve(40), * Promise.resolve(36) * ]); * * numbers.then(_.spread(function(x, y) { * return x + y; * })); * // => a Promise of 76 */ function spread(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = start == null ? 0 : nativeMax(toInteger(start), 0); return baseRest(function(args) { var array = args[start], otherArgs = castSlice(args, 0, start); if (array) { arrayPush(otherArgs, array); } return apply(func, this, otherArgs); }); } /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed `func` invocations and a `flush` method to * immediately invoke them. Provide `options` to indicate whether `func` * should be invoked on the leading and/or trailing edge of the `wait` * timeout. The `func` is invoked with the last arguments provided to the * throttled function. Subsequent calls to the throttled function return the * result of the last `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is * invoked on the trailing edge of the timeout only if the throttled function * is invoked more than once during the `wait` timeout. * * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred * until to the next tick, similar to `setTimeout` with a timeout of `0`. * * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options={}] The options object. * @param {boolean} [options.leading=true] * Specify invoking on the leading edge of the timeout. * @param {boolean} [options.trailing=true] * Specify invoking on the trailing edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // Avoid excessively updating the position while scrolling. * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); * jQuery(element).on('click', throttled); * * // Cancel the trailing throttled invocation. * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': wait, 'trailing': trailing }); } /** * Creates a function that accepts up to one argument, ignoring any * additional arguments. * * @static * @memberOf _ * @since 4.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.unary(parseInt)); * // => [6, 8, 10] */ function unary(func) { return ary(func, 1); } /** * Creates a function that provides `value` to `wrapper` as its first * argument. Any additional arguments provided to the function are appended * to those provided to the `wrapper`. The wrapper is invoked with the `this` * binding of the created function. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {*} value The value to wrap. * @param {Function} [wrapper=identity] The wrapper function. * @returns {Function} Returns the new function. * @example * * var p = _.wrap(_.escape, function(func, text) { * return '<p>' + func(text) + '</p>'; * }); * * p('fred, barney, & pebbles'); * // => '<p>fred, barney, &amp; pebbles</p>' */ function wrap(value, wrapper) { return partial(castFunction(wrapper), value); } /*------------------------------------------------------------------------*/ /** * Casts `value` as an array if it's not one. * * @static * @memberOf _ * @since 4.4.0 * @category Lang * @param {*} value The value to inspect. * @returns {Array} Returns the cast array. * @example * * _.castArray(1); * // => [1] * * _.castArray({ 'a': 1 }); * // => [{ 'a': 1 }] * * _.castArray('abc'); * // => ['abc'] * * _.castArray(null); * // => [null] * * _.castArray(undefined); * // => [undefined] * * _.castArray(); * // => [] * * var array = [1, 2, 3]; * console.log(_.castArray(array) === array); * // => true */ function castArray() { if (!arguments.length) { return []; } var value = arguments[0]; return isArray(value) ? value : [value]; } /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } /** * This method is like `_.clone` except that it accepts `customizer` which * is invoked to produce the cloned value. If `customizer` returns `undefined`, * cloning is handled by the method instead. The `customizer` is invoked with * up to four arguments; (value [, index|key, object, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the cloned value. * @see _.cloneDeepWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(false); * } * } * * var el = _.cloneWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 0 */ function cloneWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); } /** * This method is like `_.clone` except that it recursively clones `value`. * * @static * @memberOf _ * @since 1.0.0 * @category Lang * @param {*} value The value to recursively clone. * @returns {*} Returns the deep cloned value. * @see _.clone * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var deep = _.cloneDeep(objects); * console.log(deep[0] === objects[0]); * // => false */ function cloneDeep(value) { return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); } /** * This method is like `_.cloneWith` except that it recursively clones `value`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to recursively clone. * @param {Function} [customizer] The function to customize cloning. * @returns {*} Returns the deep cloned value. * @see _.cloneWith * @example * * function customizer(value) { * if (_.isElement(value)) { * return value.cloneNode(true); * } * } * * var el = _.cloneDeepWith(document.body, customizer); * * console.log(el === document.body); * // => false * console.log(el.nodeName); * // => 'BODY' * console.log(el.childNodes.length); * // => 20 */ function cloneDeepWith(value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); } /** * Checks if `object` conforms to `source` by invoking the predicate * properties of `source` with the corresponding property values of `object`. * * **Note:** This method is equivalent to `_.conforms` when `source` is * partially applied. * * @static * @memberOf _ * @since 4.14.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property predicates to conform to. * @returns {boolean} Returns `true` if `object` conforms, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); * // => true * * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); * // => false */ function conformsTo(object, source) { return source == null || baseConformsTo(object, source, keys(source)); } /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } /** * Checks if `value` is greater than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than `other`, * else `false`. * @see _.lt * @example * * _.gt(3, 1); * // => true * * _.gt(3, 3); * // => false * * _.gt(1, 3); * // => false */ var gt = createRelationalOperation(baseGt); /** * Checks if `value` is greater than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is greater than or equal to * `other`, else `false`. * @see _.lte * @example * * _.gte(3, 1); * // => true * * _.gte(3, 3); * // => true * * _.gte(1, 3); * // => false */ var gte = createRelationalOperation(function(value, other) { return value >= other; }); /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; /** * Checks if `value` is classified as an `ArrayBuffer` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. * @example * * _.isArrayBuffer(new ArrayBuffer(2)); * // => true * * _.isArrayBuffer(new Array(2)); * // => false */ var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } /** * Checks if `value` is classified as a boolean primitive or object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. * @example * * _.isBoolean(false); * // => true * * _.isBoolean(null); * // => false */ function isBoolean(value) { return value === true || value === false || (isObjectLike(value) && baseGetTag(value) == boolTag); } /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; /** * Checks if `value` is classified as a `Date` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a date object, else `false`. * @example * * _.isDate(new Date); * // => true * * _.isDate('Mon April 23 2012'); * // => false */ var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; /** * Checks if `value` is likely a DOM element. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. * @example * * _.isElement(document.body); * // => true * * _.isElement('<body>'); * // => false */ function isElement(value) { return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); } /** * Checks if `value` is an empty object, collection, map, or set. * * Objects are considered empty if they have no own enumerable string keyed * properties. * * Array-like values such as `arguments` objects, arrays, buffers, strings, or * jQuery-like collections are considered empty if they have a `length` of `0`. * Similarly, maps and sets are considered empty if they have a `size` of `0`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is empty, else `false`. * @example * * _.isEmpty(null); * // => true * * _.isEmpty(true); * // => true * * _.isEmpty(1); * // => true * * _.isEmpty([1, 2, 3]); * // => false * * _.isEmpty({ 'a': 1 }); * // => false */ function isEmpty(value) { if (value == null) { return true; } if (isArrayLike(value) && (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || isBuffer(value) || isTypedArray(value) || isArguments(value))) { return !value.length; } var tag = getTag(value); if (tag == mapTag || tag == setTag) { return !value.size; } if (isPrototype(value)) { return !baseKeys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } /** * Performs a deep comparison between two values to determine if they are * equivalent. * * **Note:** This method supports comparing arrays, array buffers, booleans, * date objects, error objects, maps, numbers, `Object` objects, regexes, * sets, strings, symbols, and typed arrays. `Object` objects are compared * by their own, not inherited, enumerable properties. Functions and DOM * nodes are compared by strict equality, i.e. `===`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.isEqual(object, other); * // => true * * object === other; * // => false */ function isEqual(value, other) { return baseIsEqual(value, other); } /** * This method is like `_.isEqual` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with up to * six arguments: (objValue, othValue [, index|key, object, other, stack]). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * _.isEqualWith(array, other, customizer); * // => true */ function isEqualWith(value, other, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; var result = customizer ? customizer(value, other) : undefined; return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; } /** * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, * `SyntaxError`, `TypeError`, or `URIError` object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an error object, else `false`. * @example * * _.isError(new Error); * // => true * * _.isError(Error); * // => false */ function isError(value) { if (!isObjectLike(value)) { return false; } var tag = baseGetTag(value); return tag == errorTag || tag == domExcTag || (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); } /** * Checks if `value` is a finite primitive number. * * **Note:** This method is based on * [`Number.isFinite`](https://mdn.io/Number/isFinite). * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. * @example * * _.isFinite(3); * // => true * * _.isFinite(Number.MIN_VALUE); * // => true * * _.isFinite(Infinity); * // => false * * _.isFinite('3'); * // => false */ function isFinite(value) { return typeof value == 'number' && nativeIsFinite(value); } /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** * Checks if `value` is an integer. * * **Note:** This method is based on * [`Number.isInteger`](https://mdn.io/Number/isInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an integer, else `false`. * @example * * _.isInteger(3); * // => true * * _.isInteger(Number.MIN_VALUE); * // => false * * _.isInteger(Infinity); * // => false * * _.isInteger('3'); * // => false */ function isInteger(value) { return typeof value == 'number' && value == toInteger(value); } /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } /** * Checks if `value` is classified as a `Map` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a map, else `false`. * @example * * _.isMap(new Map); * // => true * * _.isMap(new WeakMap); * // => false */ var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; /** * Performs a partial deep comparison between `object` and `source` to * determine if `object` contains equivalent property values. * * **Note:** This method is equivalent to `_.matches` when `source` is * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * var object = { 'a': 1, 'b': 2 }; * * _.isMatch(object, { 'b': 2 }); * // => true * * _.isMatch(object, { 'b': 1 }); * // => false */ function isMatch(object, source) { return object === source || baseIsMatch(object, source, getMatchData(source)); } /** * This method is like `_.isMatch` except that it accepts `customizer` which * is invoked to compare values. If `customizer` returns `undefined`, comparisons * are handled by the method instead. The `customizer` is invoked with five * arguments: (objValue, srcValue, index|key, object, source). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, srcValue) { * if (isGreeting(objValue) && isGreeting(srcValue)) { * return true; * } * } * * var object = { 'greeting': 'hello' }; * var source = { 'greeting': 'hi' }; * * _.isMatchWith(object, source, customizer); * // => true */ function isMatchWith(object, source, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return baseIsMatch(object, source, getMatchData(source), customizer); } /** * Checks if `value` is `NaN`. * * **Note:** This method is based on * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for * `undefined` and other non-number values. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. * @example * * _.isNaN(NaN); * // => true * * _.isNaN(new Number(NaN)); * // => true * * isNaN(undefined); * // => true * * _.isNaN(undefined); * // => false */ function isNaN(value) { // An `NaN` primitive is the only value that is not equal to itself. // Perform the `toStringTag` check first to avoid errors with some // ActiveX objects in IE. return isNumber(value) && value != +value; } /** * Checks if `value` is a pristine native function. * * **Note:** This method can't reliably detect native functions in the presence * of the core-js package because core-js circumvents this kind of detection. * Despite multiple requests, the core-js maintainer has made it clear: any * attempt to fix the detection will be obstructed. As a result, we're left * with little choice but to throw an error. Unfortunately, this also affects * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), * which rely on core-js. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (isMaskable(value)) { throw new Error(CORE_ERROR_TEXT); } return baseIsNative(value); } /** * Checks if `value` is `null`. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } /** * Checks if `value` is `null` or `undefined`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * * _.isNil(null); * // => true * * _.isNil(void 0); * // => true * * _.isNil(NaN); * // => false */ function isNil(value) { return value == null; } /** * Checks if `value` is classified as a `Number` primitive or object. * * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are * classified as numbers, use the `_.isFinite` method. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a number, else `false`. * @example * * _.isNumber(3); * // => true * * _.isNumber(Number.MIN_VALUE); * // => true * * _.isNumber(Infinity); * // => true * * _.isNumber('3'); * // => false */ function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && baseGetTag(value) == numberTag); } /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } /** * Checks if `value` is classified as a `RegExp` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. * @example * * _.isRegExp(/abc/); * // => true * * _.isRegExp('/abc/'); * // => false */ var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; /** * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 * double precision number which isn't the result of a rounded unsafe integer. * * **Note:** This method is based on * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. * @example * * _.isSafeInteger(3); * // => true * * _.isSafeInteger(Number.MIN_VALUE); * // => false * * _.isSafeInteger(Infinity); * // => false * * _.isSafeInteger('3'); * // => false */ function isSafeInteger(value) { return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; } /** * Checks if `value` is classified as a `Set` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a set, else `false`. * @example * * _.isSet(new Set); * // => true * * _.isSet(new WeakSet); * // => false */ var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a string, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); } /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; /** * Checks if `value` is `undefined`. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. * @example * * _.isUndefined(void 0); * // => true * * _.isUndefined(null); * // => false */ function isUndefined(value) { return value === undefined; } /** * Checks if `value` is classified as a `WeakMap` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. * @example * * _.isWeakMap(new WeakMap); * // => true * * _.isWeakMap(new Map); * // => false */ function isWeakMap(value) { return isObjectLike(value) && getTag(value) == weakMapTag; } /** * Checks if `value` is classified as a `WeakSet` object. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. * @example * * _.isWeakSet(new WeakSet); * // => true * * _.isWeakSet(new Set); * // => false */ function isWeakSet(value) { return isObjectLike(value) && baseGetTag(value) == weakSetTag; } /** * Checks if `value` is less than `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than `other`, * else `false`. * @see _.gt * @example * * _.lt(1, 3); * // => true * * _.lt(3, 3); * // => false * * _.lt(3, 1); * // => false */ var lt = createRelationalOperation(baseLt); /** * Checks if `value` is less than or equal to `other`. * * @static * @memberOf _ * @since 3.9.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if `value` is less than or equal to * `other`, else `false`. * @see _.gte * @example * * _.lte(1, 3); * // => true * * _.lte(3, 3); * // => true * * _.lte(3, 1); * // => false */ var lte = createRelationalOperation(function(value, other) { return value <= other; }); /** * Converts `value` to an array. * * @static * @since 0.1.0 * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Array} Returns the converted array. * @example * * _.toArray({ 'a': 1, 'b': 2 }); * // => [1, 2] * * _.toArray('abc'); * // => ['a', 'b', 'c'] * * _.toArray(1); * // => [] * * _.toArray(null); * // => [] */ function toArray(value) { if (!value) { return []; } if (isArrayLike(value)) { return isString(value) ? stringToArray(value) : copyArray(value); } if (symIterator && value[symIterator]) { return iteratorToArray(value[symIterator]()); } var tag = getTag(value), func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); return func(value); } /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * **Note:** This method is based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toLength(3.2); * // => 3 * * _.toLength(Number.MIN_VALUE); * // => 0 * * _.toLength(Infinity); * // => 4294967295 * * _.toLength('3.2'); * // => 3 */ function toLength(value) { return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; } /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } /** * Converts `value` to a safe integer. A safe integer can be compared and * represented correctly. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toSafeInteger(3.2); * // => 3 * * _.toSafeInteger(Number.MIN_VALUE); * // => 0 * * _.toSafeInteger(Infinity); * // => 9007199254740991 * * _.toSafeInteger('3.2'); * // => 3 */ function toSafeInteger(value) { return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : (value === 0 ? value : 0); } /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } /*------------------------------------------------------------------------*/ /** * Assigns own enumerable string keyed properties of source objects to the * destination object. Source objects are applied from left to right. * Subsequent sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object` and is loosely based on * [`Object.assign`](https://mdn.io/Object/assign). * * @static * @memberOf _ * @since 0.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assignIn * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assign({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'c': 3 } */ var assign = createAssigner(function(object, source) { if (isPrototype(source) || isArrayLike(source)) { copyObject(source, keys(source), object); return; } for (var key in source) { if (hasOwnProperty.call(source, key)) { assignValue(object, key, source[key]); } } }); /** * This method is like `_.assign` except that it iterates over own and * inherited source properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extend * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.assign * @example * * function Foo() { * this.a = 1; * } * * function Bar() { * this.c = 3; * } * * Foo.prototype.b = 2; * Bar.prototype.d = 4; * * _.assignIn({ 'a': 0 }, new Foo, new Bar); * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } */ var assignIn = createAssigner(function(object, source) { copyObject(source, keysIn(source), object); }); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); /** * This method is like `_.assign` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignInWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keys(source), object, customizer); }); /** * Creates an array of values corresponding to `paths` of `object`. * * @static * @memberOf _ * @since 1.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Array} Returns the picked values. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; * * _.at(object, ['a[0].b.c', 'a[1]']); * // => [3, 4] */ var at = flatRest(baseAt); /** * Creates an object that inherits from the `prototype` object. If a * `properties` object is given, its own enumerable string keyed properties * are assigned to the created object. * * @static * @memberOf _ * @since 2.3.0 * @category Object * @param {Object} prototype The object to inherit from. * @param {Object} [properties] The properties to assign to the object. * @returns {Object} Returns the new object. * @example * * function Shape() { * this.x = 0; * this.y = 0; * } * * function Circle() { * Shape.call(this); * } * * Circle.prototype = _.create(Shape.prototype, { * 'constructor': Circle * }); * * var circle = new Circle; * circle instanceof Circle; * // => true * * circle instanceof Shape; * // => true */ function create(prototype, properties) { var result = baseCreate(prototype); return properties == null ? result : baseAssign(result, properties); } /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(object, sources) { object = Object(object); var index = -1; var length = sources.length; var guard = length > 2 ? sources[2] : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { length = 1; } while (++index < length) { var source = sources[index]; var props = keysIn(source); var propsIndex = -1; var propsLength = props.length; while (++propsIndex < propsLength) { var key = props[propsIndex]; var value = object[key]; if (value === undefined || (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { object[key] = source[key]; } } } return object; }); /** * This method is like `_.defaults` except that it recursively assigns * default properties. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.10.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaults * @example * * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); * // => { 'a': { 'b': 2, 'c': 3 } } */ var defaultsDeep = baseRest(function(args) { args.push(undefined, customDefaultsMerge); return apply(mergeWith, undefined, args); }); /** * This method is like `_.find` except that it returns the key of the first * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ * @since 1.1.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findKey(users, function(o) { return o.age < 40; }); * // => 'barney' (iteration order is not guaranteed) * * // The `_.matches` iteratee shorthand. * _.findKey(users, { 'age': 1, 'active': true }); * // => 'pebbles' * * // The `_.matchesProperty` iteratee shorthand. * _.findKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findKey(users, 'active'); * // => 'barney' */ function findKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); } /** * This method is like `_.findKey` except that it iterates over elements of * a collection in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. * @returns {string|undefined} Returns the key of the matched element, * else `undefined`. * @example * * var users = { * 'barney': { 'age': 36, 'active': true }, * 'fred': { 'age': 40, 'active': false }, * 'pebbles': { 'age': 1, 'active': true } * }; * * _.findLastKey(users, function(o) { return o.age < 40; }); * // => returns 'pebbles' assuming `_.findKey` returns 'barney' * * // The `_.matches` iteratee shorthand. * _.findLastKey(users, { 'age': 36, 'active': true }); * // => 'barney' * * // The `_.matchesProperty` iteratee shorthand. * _.findLastKey(users, ['active', false]); * // => 'fred' * * // The `_.property` iteratee shorthand. * _.findLastKey(users, 'active'); * // => 'pebbles' */ function findLastKey(object, predicate) { return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); } /** * Iterates over own and inherited enumerable string keyed properties of an * object and invokes `iteratee` for each property. The iteratee is invoked * with three arguments: (value, key, object). Iteratee functions may exit * iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forInRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forIn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). */ function forIn(object, iteratee) { return object == null ? object : baseFor(object, getIteratee(iteratee, 3), keysIn); } /** * This method is like `_.forIn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forIn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forInRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. */ function forInRight(object, iteratee) { return object == null ? object : baseForRight(object, getIteratee(iteratee, 3), keysIn); } /** * Iterates over own enumerable string keyed properties of an object and * invokes `iteratee` for each property. The iteratee is invoked with three * arguments: (value, key, object). Iteratee functions may exit iteration * early by explicitly returning `false`. * * @static * @memberOf _ * @since 0.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwnRight * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwn(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'a' then 'b' (iteration order is not guaranteed). */ function forOwn(object, iteratee) { return object && baseForOwn(object, getIteratee(iteratee, 3)); } /** * This method is like `_.forOwn` except that it iterates over properties of * `object` in the opposite order. * * @static * @memberOf _ * @since 2.0.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns `object`. * @see _.forOwn * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.forOwnRight(new Foo, function(value, key) { * console.log(key); * }); * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. */ function forOwnRight(object, iteratee) { return object && baseForOwnRight(object, getIteratee(iteratee, 3)); } /** * Creates an array of function property names from own enumerable properties * of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functionsIn * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functions(new Foo); * // => ['a', 'b'] */ function functions(object) { return object == null ? [] : baseFunctions(object, keys(object)); } /** * Creates an array of function property names from own and inherited * enumerable properties of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to inspect. * @returns {Array} Returns the function names. * @see _.functions * @example * * function Foo() { * this.a = _.constant('a'); * this.b = _.constant('b'); * } * * Foo.prototype.c = _.constant('c'); * * _.functionsIn(new Foo); * // => ['a', 'b', 'c'] */ function functionsIn(object) { return object == null ? [] : baseFunctions(object, keysIn(object)); } /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } /** * Checks if `path` is a direct property of `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = { 'a': { 'b': 2 } }; * var other = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.has(object, 'a'); * // => true * * _.has(object, 'a.b'); * // => true * * _.has(object, ['a', 'b']); * // => true * * _.has(other, 'a'); * // => false */ function has(object, path) { return object != null && hasPath(object, path, baseHas); } /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } /** * Creates an object composed of the inverted keys and values of `object`. * If `object` contains duplicate values, subsequent values overwrite * property assignments of previous values. * * @static * @memberOf _ * @since 0.7.0 * @category Object * @param {Object} object The object to invert. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invert(object); * // => { '1': 'c', '2': 'b' } */ var invert = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } result[value] = key; }, constant(identity)); /** * This method is like `_.invert` except that the inverted object is generated * from the results of running each element of `object` thru `iteratee`. The * corresponding inverted value of each inverted key is an array of keys * responsible for generating the inverted value. The iteratee is invoked * with one argument: (value). * * @static * @memberOf _ * @since 4.1.0 * @category Object * @param {Object} object The object to invert. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {Object} Returns the new inverted object. * @example * * var object = { 'a': 1, 'b': 2, 'c': 1 }; * * _.invertBy(object); * // => { '1': ['a', 'c'], '2': ['b'] } * * _.invertBy(object, function(value) { * return 'group' + value; * }); * // => { 'group1': ['a', 'c'], 'group2': ['b'] } */ var invertBy = createInverter(function(result, value, key) { if (value != null && typeof value.toString != 'function') { value = nativeObjectToString.call(value); } if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } }, getIteratee); /** * Invokes the method at `path` of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {*} Returns the result of the invoked method. * @example * * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; * * _.invoke(object, 'a[0].b.c.slice', 1, 3); * // => [2, 3] */ var invoke = baseRest(baseInvoke); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } /** * The opposite of `_.mapValues`; this method creates an object with the * same values as `object` and keys generated by running each own enumerable * string keyed property of `object` thru `iteratee`. The iteratee is invoked * with three arguments: (value, key, object). * * @static * @memberOf _ * @since 3.8.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapValues * @example * * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { * return key + value; * }); * // => { 'a1': 1, 'b2': 2 } */ function mapKeys(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, iteratee(value, key, object), value); }); return result; } /** * Creates an object with the same keys as `object` and values generated * by running each own enumerable string keyed property of `object` thru * `iteratee`. The iteratee is invoked with three arguments: * (value, key, object). * * @static * @memberOf _ * @since 2.4.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Object} Returns the new mapped object. * @see _.mapKeys * @example * * var users = { * 'fred': { 'user': 'fred', 'age': 40 }, * 'pebbles': { 'user': 'pebbles', 'age': 1 } * }; * * _.mapValues(users, function(o) { return o.age; }); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) * * // The `_.property` iteratee shorthand. * _.mapValues(users, 'age'); * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) */ function mapValues(object, iteratee) { var result = {}; iteratee = getIteratee(iteratee, 3); baseForOwn(object, function(value, key, object) { baseAssignValue(result, key, iteratee(value, key, object)); }); return result; } /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); /** * This method is like `_.merge` except that it accepts `customizer` which * is invoked to produce the merged values of the destination and source * properties. If `customizer` returns `undefined`, merging is handled by the * method instead. The `customizer` is invoked with six arguments: * (objValue, srcValue, key, object, source, stack). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * function customizer(objValue, srcValue) { * if (_.isArray(objValue)) { * return objValue.concat(srcValue); * } * } * * var object = { 'a': [1], 'b': [2] }; * var other = { 'a': [3], 'b': [4] }; * * _.mergeWith(object, other, customizer); * // => { 'a': [1, 3], 'b': [2, 4] } */ var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { baseMerge(object, source, srcIndex, customizer); }); /** * The opposite of `_.pick`; this method creates an object composed of the * own and inherited enumerable property paths of `object` that are not omitted. * * **Note:** This method is considerably slower than `_.pick`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to omit. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omit(object, ['a', 'c']); * // => { 'b': '2' } */ var omit = flatRest(function(object, paths) { var result = {}; if (object == null) { return result; } var isDeep = false; paths = arrayMap(paths, function(path) { path = castPath(path, object); isDeep || (isDeep = path.length > 1); return path; }); copyObject(object, getAllKeysIn(object), result); if (isDeep) { result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); } var length = paths.length; while (length--) { baseUnset(result, paths[length]); } return result; }); /** * The opposite of `_.pickBy`; this method creates an object composed of * the own and inherited enumerable string keyed properties of `object` that * `predicate` doesn't return truthy for. The predicate is invoked with two * arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.omitBy(object, _.isNumber); * // => { 'b': '2' } */ function omitBy(object, predicate) { return pickBy(object, negate(getIteratee(predicate))); } /** * Creates an object composed of the picked `object` properties. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pick(object, ['a', 'c']); * // => { 'a': 1, 'c': 3 } */ var pick = flatRest(function(object, paths) { return object == null ? {} : basePick(object, paths); }); /** * Creates an object composed of the `object` properties `predicate` returns * truthy for. The predicate is invoked with two arguments: (value, key). * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The source object. * @param {Function} [predicate=_.identity] The function invoked per property. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * * _.pickBy(object, _.isNumber); * // => { 'a': 1, 'c': 3 } */ function pickBy(object, predicate) { if (object == null) { return {}; } var props = arrayMap(getAllKeysIn(object), function(prop) { return [prop]; }); predicate = getIteratee(predicate); return basePickBy(object, props, function(value, path) { return predicate(value, path[0]); }); } /** * This method is like `_.get` except that if the resolved value is a * function it's invoked with the `this` binding of its parent object and * its result is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to resolve. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; * * _.result(object, 'a[0].b.c1'); * // => 3 * * _.result(object, 'a[0].b.c2'); * // => 4 * * _.result(object, 'a[0].b.c3', 'default'); * // => 'default' * * _.result(object, 'a[0].b.c3', _.constant('default')); * // => 'default' */ function result(object, path, defaultValue) { path = castPath(path, object); var index = -1, length = path.length; // Ensure the loop is entered when path is empty. if (!length) { length = 1; object = undefined; } while (++index < length) { var value = object == null ? undefined : object[toKey(path[index])]; if (value === undefined) { index = length; value = defaultValue; } object = isFunction(value) ? value.call(object) : value; } return object; } /** * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, * it's created. Arrays are created for missing index properties while objects * are created for all other missing properties. Use `_.setWith` to customize * `path` creation. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.set(object, 'a[0].b.c', 4); * console.log(object.a[0].b.c); * // => 4 * * _.set(object, ['x', '0', 'y', 'z'], 5); * console.log(object.x[0].y.z); * // => 5 */ function set(object, path, value) { return object == null ? object : baseSet(object, path, value); } /** * This method is like `_.set` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {*} value The value to set. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.setWith(object, '[0][1]', 'a', Object); * // => { '0': { '1': 'a' } } */ function setWith(object, path, value, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseSet(object, path, value, customizer); } /** * Creates an array of own enumerable string keyed-value pairs for `object` * which can be consumed by `_.fromPairs`. If `object` is a map or set, its * entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entries * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairs(new Foo); * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) */ var toPairs = createToPairs(keys); /** * Creates an array of own and inherited enumerable string keyed-value pairs * for `object` which can be consumed by `_.fromPairs`. If `object` is a map * or set, its entries are returned. * * @static * @memberOf _ * @since 4.0.0 * @alias entriesIn * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the key-value pairs. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.toPairsIn(new Foo); * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) */ var toPairsIn = createToPairs(keysIn); /** * An alternative to `_.reduce`; this method transforms `object` to a new * `accumulator` object which is the result of running each of its own * enumerable string keyed properties thru `iteratee`, with each invocation * potentially mutating the `accumulator` object. If `accumulator` is not * provided, a new object with the same `[[Prototype]]` will be used. The * iteratee is invoked with four arguments: (accumulator, value, key, object). * Iteratee functions may exit iteration early by explicitly returning `false`. * * @static * @memberOf _ * @since 1.3.0 * @category Object * @param {Object} object The object to iterate over. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @param {*} [accumulator] The custom accumulator value. * @returns {*} Returns the accumulated value. * @example * * _.transform([2, 3, 4], function(result, n) { * result.push(n *= n); * return n % 2 == 0; * }, []); * // => [4, 9] * * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { * (result[value] || (result[value] = [])).push(key); * }, {}); * // => { '1': ['a', 'c'], '2': ['b'] } */ function transform(object, iteratee, accumulator) { var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); iteratee = getIteratee(iteratee, 4); if (accumulator == null) { var Ctor = object && object.constructor; if (isArrLike) { accumulator = isArr ? new Ctor : []; } else if (isObject(object)) { accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; } else { accumulator = {}; } } (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { return iteratee(accumulator, value, index, object); }); return accumulator; } /** * Removes the property at `path` of `object`. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to unset. * @returns {boolean} Returns `true` if the property is deleted, else `false`. * @example * * var object = { 'a': [{ 'b': { 'c': 7 } }] }; * _.unset(object, 'a[0].b.c'); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; * * _.unset(object, ['a', '0', 'b', 'c']); * // => true * * console.log(object); * // => { 'a': [{ 'b': {} }] }; */ function unset(object, path) { return object == null ? true : baseUnset(object, path); } /** * This method is like `_.set` except that accepts `updater` to produce the * value to set. Use `_.updateWith` to customize `path` creation. The `updater` * is invoked with one argument: (value). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @returns {Object} Returns `object`. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.update(object, 'a[0].b.c', function(n) { return n * n; }); * console.log(object.a[0].b.c); * // => 9 * * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); * console.log(object.x[0].y.z); * // => 0 */ function update(object, path, updater) { return object == null ? object : baseUpdate(object, path, castFunction(updater)); } /** * This method is like `_.update` except that it accepts `customizer` which is * invoked to produce the objects of `path`. If `customizer` returns `undefined` * path creation is handled by the method instead. The `customizer` is invoked * with three arguments: (nsValue, key, nsObject). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.6.0 * @category Object * @param {Object} object The object to modify. * @param {Array|string} path The path of the property to set. * @param {Function} updater The function to produce the updated value. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @example * * var object = {}; * * _.updateWith(object, '[0][1]', _.constant('a'), Object); * // => { '0': { '1': 'a' } } */ function updateWith(object, path, updater, customizer) { customizer = typeof customizer == 'function' ? customizer : undefined; return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); } /** * Creates an array of the own enumerable string keyed property values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.values(new Foo); * // => [1, 2] (iteration order is not guaranteed) * * _.values('hi'); * // => ['h', 'i'] */ function values(object) { return object == null ? [] : baseValues(object, keys(object)); } /** * Creates an array of the own and inherited enumerable string keyed property * values of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property values. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.valuesIn(new Foo); * // => [1, 2, 3] (iteration order is not guaranteed) */ function valuesIn(object) { return object == null ? [] : baseValues(object, keysIn(object)); } /*------------------------------------------------------------------------*/ /** * Clamps `number` within the inclusive `lower` and `upper` bounds. * * @static * @memberOf _ * @since 4.0.0 * @category Number * @param {number} number The number to clamp. * @param {number} [lower] The lower bound. * @param {number} upper The upper bound. * @returns {number} Returns the clamped number. * @example * * _.clamp(-10, -5, 5); * // => -5 * * _.clamp(10, -5, 5); * // => 5 */ function clamp(number, lower, upper) { if (upper === undefined) { upper = lower; lower = undefined; } if (upper !== undefined) { upper = toNumber(upper); upper = upper === upper ? upper : 0; } if (lower !== undefined) { lower = toNumber(lower); lower = lower === lower ? lower : 0; } return baseClamp(toNumber(number), lower, upper); } /** * Checks if `n` is between `start` and up to, but not including, `end`. If * `end` is not specified, it's set to `start` with `start` then set to `0`. * If `start` is greater than `end` the params are swapped to support * negative ranges. * * @static * @memberOf _ * @since 3.3.0 * @category Number * @param {number} number The number to check. * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @returns {boolean} Returns `true` if `number` is in the range, else `false`. * @see _.range, _.rangeRight * @example * * _.inRange(3, 2, 4); * // => true * * _.inRange(4, 8); * // => true * * _.inRange(4, 2); * // => false * * _.inRange(2, 2); * // => false * * _.inRange(1.2, 2); * // => true * * _.inRange(5.2, 4); * // => false * * _.inRange(-3, -2, -6); * // => true */ function inRange(number, start, end) { start = toFinite(start); if (end === undefined) { end = start; start = 0; } else { end = toFinite(end); } number = toNumber(number); return baseInRange(number, start, end); } /** * Produces a random number between the inclusive `lower` and `upper` bounds. * If only one argument is provided a number between `0` and the given number * is returned. If `floating` is `true`, or either `lower` or `upper` are * floats, a floating-point number is returned instead of an integer. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @memberOf _ * @since 0.7.0 * @category Number * @param {number} [lower=0] The lower bound. * @param {number} [upper=1] The upper bound. * @param {boolean} [floating] Specify returning a floating-point number. * @returns {number} Returns the random number. * @example * * _.random(0, 5); * // => an integer between 0 and 5 * * _.random(5); * // => also an integer between 0 and 5 * * _.random(5, true); * // => a floating-point number between 0 and 5 * * _.random(1.2, 5.2); * // => a floating-point number between 1.2 and 5.2 */ function random(lower, upper, floating) { if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { upper = floating = undefined; } if (floating === undefined) { if (typeof upper == 'boolean') { floating = upper; upper = undefined; } else if (typeof lower == 'boolean') { floating = lower; lower = undefined; } } if (lower === undefined && upper === undefined) { lower = 0; upper = 1; } else { lower = toFinite(lower); if (upper === undefined) { upper = lower; lower = 0; } else { upper = toFinite(upper); } } if (lower > upper) { var temp = lower; lower = upper; upper = temp; } if (floating || lower % 1 || upper % 1) { var rand = nativeRandom(); return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); } return baseRandom(lower, upper); } /*------------------------------------------------------------------------*/ /** * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the camel cased string. * @example * * _.camelCase('Foo Bar'); * // => 'fooBar' * * _.camelCase('--foo-bar--'); * // => 'fooBar' * * _.camelCase('__FOO_BAR__'); * // => 'fooBar' */ var camelCase = createCompounder(function(result, word, index) { word = word.toLowerCase(); return result + (index ? capitalize(word) : word); }); /** * Converts the first character of `string` to upper case and the remaining * to lower case. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to capitalize. * @returns {string} Returns the capitalized string. * @example * * _.capitalize('FRED'); * // => 'Fred' */ function capitalize(string) { return upperFirst(toString(string).toLowerCase()); } /** * Deburrs `string` by converting * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) * letters to basic Latin letters and removing * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to deburr. * @returns {string} Returns the deburred string. * @example * * _.deburr('déjà vu'); * // => 'deja vu' */ function deburr(string) { string = toString(string); return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); } /** * Checks if `string` ends with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=string.length] The position to search up to. * @returns {boolean} Returns `true` if `string` ends with `target`, * else `false`. * @example * * _.endsWith('abc', 'c'); * // => true * * _.endsWith('abc', 'b'); * // => false * * _.endsWith('abc', 'b', 2); * // => true */ function endsWith(string, target, position) { string = toString(string); target = baseToString(target); var length = string.length; position = position === undefined ? length : baseClamp(toInteger(position), 0, length); var end = position; position -= target.length; return position >= 0 && string.slice(position, end) == target; } /** * Converts the characters "&", "<", ">", '"', and "'" in `string` to their * corresponding HTML entities. * * **Note:** No other characters are escaped. To escape additional * characters use a third-party library like [_he_](https://mths.be/he). * * Though the ">" character is escaped for symmetry, characters like * ">" and "/" don't need escaping in HTML and have no special meaning * unless they're part of a tag or unquoted attribute value. See * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) * (under "semi-related fun fact") for more details. * * When working with HTML you should always * [quote attribute values](http://wonko.com/post/html-escaping) to reduce * XSS vectors. * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escape('fred, barney, & pebbles'); * // => 'fred, barney, &amp; pebbles' */ function escape(string) { string = toString(string); return (string && reHasUnescapedHtml.test(string)) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; } /** * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to escape. * @returns {string} Returns the escaped string. * @example * * _.escapeRegExp('[lodash](https://lodash.com/)'); * // => '\[lodash\]\(https://lodash\.com/\)' */ function escapeRegExp(string) { string = toString(string); return (string && reHasRegExpChar.test(string)) ? string.replace(reRegExpChar, '\\$&') : string; } /** * Converts `string` to * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the kebab cased string. * @example * * _.kebabCase('Foo Bar'); * // => 'foo-bar' * * _.kebabCase('fooBar'); * // => 'foo-bar' * * _.kebabCase('__FOO_BAR__'); * // => 'foo-bar' */ var kebabCase = createCompounder(function(result, word, index) { return result + (index ? '-' : '') + word.toLowerCase(); }); /** * Converts `string`, as space separated words, to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.lowerCase('--Foo-Bar--'); * // => 'foo bar' * * _.lowerCase('fooBar'); * // => 'foo bar' * * _.lowerCase('__FOO_BAR__'); * // => 'foo bar' */ var lowerCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toLowerCase(); }); /** * Converts the first character of `string` to lower case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.lowerFirst('Fred'); * // => 'fred' * * _.lowerFirst('FRED'); * // => 'fRED' */ var lowerFirst = createCaseFirst('toLowerCase'); /** * Pads `string` on the left and right sides if it's shorter than `length`. * Padding characters are truncated if they can't be evenly divided by `length`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.pad('abc', 8); * // => ' abc ' * * _.pad('abc', 8, '_-'); * // => '_-abc_-_' * * _.pad('abc', 3); * // => 'abc' */ function pad(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; if (!length || strLength >= length) { return string; } var mid = (length - strLength) / 2; return ( createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars) ); } /** * Pads `string` on the right side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padEnd('abc', 6); * // => 'abc ' * * _.padEnd('abc', 6, '_-'); * // => 'abc_-_' * * _.padEnd('abc', 3); * // => 'abc' */ function padEnd(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (string + createPadding(length - strLength, chars)) : string; } /** * Pads `string` on the left side if it's shorter than `length`. Padding * characters are truncated if they exceed `length`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to pad. * @param {number} [length=0] The padding length. * @param {string} [chars=' '] The string used as padding. * @returns {string} Returns the padded string. * @example * * _.padStart('abc', 6); * // => ' abc' * * _.padStart('abc', 6, '_-'); * // => '_-_abc' * * _.padStart('abc', 3); * // => 'abc' */ function padStart(string, length, chars) { string = toString(string); length = toInteger(length); var strLength = length ? stringSize(string) : 0; return (length && strLength < length) ? (createPadding(length - strLength, chars) + string) : string; } /** * Converts `string` to an integer of the specified radix. If `radix` is * `undefined` or `0`, a `radix` of `10` is used unless `value` is a * hexadecimal, in which case a `radix` of `16` is used. * * **Note:** This method aligns with the * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. * * @static * @memberOf _ * @since 1.1.0 * @category String * @param {string} string The string to convert. * @param {number} [radix=10] The radix to interpret `value` by. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {number} Returns the converted integer. * @example * * _.parseInt('08'); * // => 8 * * _.map(['6', '08', '10'], _.parseInt); * // => [6, 8, 10] */ function parseInt(string, radix, guard) { if (guard || radix == null) { radix = 0; } else if (radix) { radix = +radix; } return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); } /** * Repeats the given string `n` times. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to repeat. * @param {number} [n=1] The number of times to repeat the string. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the repeated string. * @example * * _.repeat('*', 3); * // => '***' * * _.repeat('abc', 2); * // => 'abcabc' * * _.repeat('abc', 0); * // => '' */ function repeat(string, n, guard) { if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { n = 1; } else { n = toInteger(n); } return baseRepeat(toString(string), n); } /** * Replaces matches for `pattern` in `string` with `replacement`. * * **Note:** This method is based on * [`String#replace`](https://mdn.io/String/replace). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to modify. * @param {RegExp|string} pattern The pattern to replace. * @param {Function|string} replacement The match replacement. * @returns {string} Returns the modified string. * @example * * _.replace('Hi Fred', 'Fred', 'Barney'); * // => 'Hi Barney' */ function replace() { var args = arguments, string = toString(args[0]); return args.length < 3 ? string : string.replace(args[1], args[2]); } /** * Converts `string` to * [snake case](https://en.wikipedia.org/wiki/Snake_case). * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the snake cased string. * @example * * _.snakeCase('Foo Bar'); * // => 'foo_bar' * * _.snakeCase('fooBar'); * // => 'foo_bar' * * _.snakeCase('--FOO-BAR--'); * // => 'foo_bar' */ var snakeCase = createCompounder(function(result, word, index) { return result + (index ? '_' : '') + word.toLowerCase(); }); /** * Splits `string` by `separator`. * * **Note:** This method is based on * [`String#split`](https://mdn.io/String/split). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to split. * @param {RegExp|string} separator The separator pattern to split by. * @param {number} [limit] The length to truncate results to. * @returns {Array} Returns the string segments. * @example * * _.split('a-b-c', '-', 2); * // => ['a', 'b'] */ function split(string, separator, limit) { if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { separator = limit = undefined; } limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; if (!limit) { return []; } string = toString(string); if (string && ( typeof separator == 'string' || (separator != null && !isRegExp(separator)) )) { separator = baseToString(separator); if (!separator && hasUnicode(string)) { return castSlice(stringToArray(string), 0, limit); } } return string.split(separator, limit); } /** * Converts `string` to * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). * * @static * @memberOf _ * @since 3.1.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the start cased string. * @example * * _.startCase('--foo-bar--'); * // => 'Foo Bar' * * _.startCase('fooBar'); * // => 'Foo Bar' * * _.startCase('__FOO_BAR__'); * // => 'FOO BAR' */ var startCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + upperFirst(word); }); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } /** * Creates a compiled template function that can interpolate data properties * in "interpolate" delimiters, HTML-escape interpolated data properties in * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data * properties may be accessed as free variables in the template. If a setting * object is given, it takes precedence over `_.templateSettings` values. * * **Note:** In the development build `_.template` utilizes * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) * for easier debugging. * * For more information on precompiling templates see * [lodash's custom builds documentation](https://lodash.com/custom-builds). * * For more information on Chrome extension sandboxes see * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). * * @static * @since 0.1.0 * @memberOf _ * @category String * @param {string} [string=''] The template string. * @param {Object} [options={}] The options object. * @param {RegExp} [options.escape=_.templateSettings.escape] * The HTML "escape" delimiter. * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] * The "evaluate" delimiter. * @param {Object} [options.imports=_.templateSettings.imports] * An object to import into the template as free variables. * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] * The "interpolate" delimiter. * @param {string} [options.sourceURL='lodash.templateSources[n]'] * The sourceURL of the compiled template. * @param {string} [options.variable='obj'] * The data object variable name. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the compiled template function. * @example * * // Use the "interpolate" delimiter to create a compiled template. * var compiled = _.template('hello <%= user %>!'); * compiled({ 'user': 'fred' }); * // => 'hello fred!' * * // Use the HTML "escape" delimiter to escape data property values. * var compiled = _.template('<b><%- value %></b>'); * compiled({ 'value': '<script>' }); * // => '<b>&lt;script&gt;</b>' * * // Use the "evaluate" delimiter to execute JavaScript and generate HTML. * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>'); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the internal `print` function in "evaluate" delimiters. * var compiled = _.template('<% print("hello " + user); %>!'); * compiled({ 'user': 'barney' }); * // => 'hello barney!' * * // Use the ES template literal delimiter as an "interpolate" delimiter. * // Disable support by replacing the "interpolate" delimiter. * var compiled = _.template('hello ${ user }!'); * compiled({ 'user': 'pebbles' }); * // => 'hello pebbles!' * * // Use backslashes to treat delimiters as plain text. * var compiled = _.template('<%= "\\<%- value %\\>" %>'); * compiled({ 'value': 'ignored' }); * // => '<%- value %>' * * // Use the `imports` option to import `jQuery` as `jq`. * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>'; * var compiled = _.template(text, { 'imports': { 'jq': jQuery } }); * compiled({ 'users': ['fred', 'barney'] }); * // => '<li>fred</li><li>barney</li>' * * // Use the `sourceURL` option to specify a custom sourceURL for the template. * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' }); * compiled(data); * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector. * * // Use the `variable` option to ensure a with-statement isn't used in the compiled template. * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' }); * compiled.source; * // => function(data) { * // var __t, __p = ''; * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!'; * // return __p; * // } * * // Use custom template delimiters. * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g; * var compiled = _.template('hello {{ user }}!'); * compiled({ 'user': 'mustache' }); * // => 'hello mustache!' * * // Use the `source` property to inline compiled templates for meaningful * // line numbers in error messages and stack traces. * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\ * var JST = {\ * "main": ' + _.template(mainText).source + '\ * };\ * '); */ function template(string, options, guard) { // Based on John Resig's `tmpl` implementation // (http://ejohn.org/blog/javascript-micro-templating/) // and Laura Doktorova's doT.js (https://github.com/olado/doT). var settings = lodash.templateSettings; if (guard && isIterateeCall(string, options, guard)) { options = undefined; } string = toString(string); options = assignInWith({}, options, settings, customDefaultsAssignIn); var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys); var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; // Compile the regexp to match each delimiter. var reDelimiters = RegExp( (options.escape || reNoMatch).source + '|' + interpolate.source + '|' + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' + (options.evaluate || reNoMatch).source + '|$' , 'g'); // Use a sourceURL for easier debugging. // The sourceURL gets injected into the source that's eval-ed, so be careful // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in // and escape the comment, thus injecting code that gets evaled. var sourceURL = '//# sourceURL=' + (hasOwnProperty.call(options, 'sourceURL') ? (options.sourceURL + '').replace(/\s/g, ' ') : ('lodash.templateSources[' + (++templateCounter) + ']') ) + '\n'; string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { interpolateValue || (interpolateValue = esTemplateValue); // Escape characters that can't be included in string literals. source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); // Replace delimiters with snippets. if (escapeValue) { isEscaping = true; source += "' +\n__e(" + escapeValue + ") +\n'"; } if (evaluateValue) { isEvaluating = true; source += "';\n" + evaluateValue + ";\n__p += '"; } if (interpolateValue) { source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; } index = offset + match.length; // The JS engine embedded in Adobe products needs `match` returned in // order to produce the correct `offset` value. return match; }); source += "';\n"; // If `variable` is not specified wrap a with-statement around the generated // code to add the data object to the top of the scope chain. var variable = hasOwnProperty.call(options, 'variable') && options.variable; if (!variable) { source = 'with (obj) {\n' + source + '\n}\n'; } // Cleanup code by stripping empty strings. source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source) .replace(reEmptyStringMiddle, '$1') .replace(reEmptyStringTrailing, '$1;'); // Frame code as the function body. source = 'function(' + (variable || 'obj') + ') {\n' + (variable ? '' : 'obj || (obj = {});\n' ) + "var __t, __p = ''" + (isEscaping ? ', __e = _.escape' : '' ) + (isEvaluating ? ', __j = Array.prototype.join;\n' + "function print() { __p += __j.call(arguments, '') }\n" : ';\n' ) + source + 'return __p\n}'; var result = attempt(function() { return Function(importsKeys, sourceURL + 'return ' + source) .apply(undefined, importsValues); }); // Provide the compiled function's source by its `toString` method or // the `source` property as a convenience for inlining compiled templates. result.source = source; if (isError(result)) { throw result; } return result; } /** * Converts `string`, as a whole, to lower case just like * [String#toLowerCase](https://mdn.io/toLowerCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the lower cased string. * @example * * _.toLower('--Foo-Bar--'); * // => '--foo-bar--' * * _.toLower('fooBar'); * // => 'foobar' * * _.toLower('__FOO_BAR__'); * // => '__foo_bar__' */ function toLower(value) { return toString(value).toLowerCase(); } /** * Converts `string`, as a whole, to upper case just like * [String#toUpperCase](https://mdn.io/toUpperCase). * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.toUpper('--foo-bar--'); * // => '--FOO-BAR--' * * _.toUpper('fooBar'); * // => 'FOOBAR' * * _.toUpper('__foo_bar__'); * // => '__FOO_BAR__' */ function toUpper(value) { return toString(value).toUpperCase(); } /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrim, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } /** * Removes trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimEnd(' abc '); * // => ' abc' * * _.trimEnd('-_-abc-_-', '_-'); * // => '-_-abc' */ function trimEnd(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimEnd, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; return castSlice(strSymbols, 0, end).join(''); } /** * Removes leading whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trimStart(' abc '); * // => 'abc ' * * _.trimStart('-_-abc-_-', '_-'); * // => 'abc-_-' */ function trimStart(string, chars, guard) { string = toString(string); if (string && (guard || chars === undefined)) { return string.replace(reTrimStart, ''); } if (!string || !(chars = baseToString(chars))) { return string; } var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); return castSlice(strSymbols, start).join(''); } /** * Truncates `string` if it's longer than the given maximum string length. * The last characters of the truncated string are replaced with the omission * string which defaults to "...". * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to truncate. * @param {Object} [options={}] The options object. * @param {number} [options.length=30] The maximum string length. * @param {string} [options.omission='...'] The string to indicate text is omitted. * @param {RegExp|string} [options.separator] The separator pattern to truncate to. * @returns {string} Returns the truncated string. * @example * * _.truncate('hi-diddly-ho there, neighborino'); * // => 'hi-diddly-ho there, neighbo...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': ' ' * }); * // => 'hi-diddly-ho there,...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'length': 24, * 'separator': /,? +/ * }); * // => 'hi-diddly-ho there...' * * _.truncate('hi-diddly-ho there, neighborino', { * 'omission': ' [...]' * }); * // => 'hi-diddly-ho there, neig [...]' */ function truncate(string, options) { var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; if (isObject(options)) { var separator = 'separator' in options ? options.separator : separator; length = 'length' in options ? toInteger(options.length) : length; omission = 'omission' in options ? baseToString(options.omission) : omission; } string = toString(string); var strLength = string.length; if (hasUnicode(string)) { var strSymbols = stringToArray(string); strLength = strSymbols.length; } if (length >= strLength) { return string; } var end = length - stringSize(omission); if (end < 1) { return omission; } var result = strSymbols ? castSlice(strSymbols, 0, end).join('') : string.slice(0, end); if (separator === undefined) { return result + omission; } if (strSymbols) { end += (result.length - end); } if (isRegExp(separator)) { if (string.slice(end).search(separator)) { var match, substring = result; if (!separator.global) { separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g'); } separator.lastIndex = 0; while ((match = separator.exec(substring))) { var newEnd = match.index; } result = result.slice(0, newEnd === undefined ? end : newEnd); } } else if (string.indexOf(baseToString(separator), end) != end) { var index = result.lastIndexOf(separator); if (index > -1) { result = result.slice(0, index); } } return result + omission; } /** * The inverse of `_.escape`; this method converts the HTML entities * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to * their corresponding characters. * * **Note:** No other HTML entities are unescaped. To unescape additional * HTML entities use a third-party library like [_he_](https://mths.be/he). * * @static * @memberOf _ * @since 0.6.0 * @category String * @param {string} [string=''] The string to unescape. * @returns {string} Returns the unescaped string. * @example * * _.unescape('fred, barney, &amp; pebbles'); * // => 'fred, barney, & pebbles' */ function unescape(string) { string = toString(string); return (string && reHasEscapedHtml.test(string)) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; } /** * Converts `string`, as space separated words, to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the upper cased string. * @example * * _.upperCase('--foo-bar'); * // => 'FOO BAR' * * _.upperCase('fooBar'); * // => 'FOO BAR' * * _.upperCase('__foo_bar__'); * // => 'FOO BAR' */ var upperCase = createCompounder(function(result, word, index) { return result + (index ? ' ' : '') + word.toUpperCase(); }); /** * Converts the first character of `string` to upper case. * * @static * @memberOf _ * @since 4.0.0 * @category String * @param {string} [string=''] The string to convert. * @returns {string} Returns the converted string. * @example * * _.upperFirst('fred'); * // => 'Fred' * * _.upperFirst('FRED'); * // => 'FRED' */ var upperFirst = createCaseFirst('toUpperCase'); /** * Splits `string` into an array of its words. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {RegExp|string} [pattern] The pattern to match words. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Array} Returns the words of `string`. * @example * * _.words('fred, barney, & pebbles'); * // => ['fred', 'barney', 'pebbles'] * * _.words('fred, barney, & pebbles', /[^, ]+/g); * // => ['fred', 'barney', '&', 'pebbles'] */ function words(string, pattern, guard) { string = toString(string); pattern = guard ? undefined : pattern; if (pattern === undefined) { return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); } return string.match(pattern) || []; } /*------------------------------------------------------------------------*/ /** * Attempts to invoke `func`, returning either the result or the caught error * object. Any additional arguments are provided to `func` when it's invoked. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Function} func The function to attempt. * @param {...*} [args] The arguments to invoke `func` with. * @returns {*} Returns the `func` result or error object. * @example * * // Avoid throwing errors for invalid selectors. * var elements = _.attempt(function(selector) { * return document.querySelectorAll(selector); * }, '>_>'); * * if (_.isError(elements)) { * elements = []; * } */ var attempt = baseRest(function(func, args) { try { return apply(func, undefined, args); } catch (e) { return isError(e) ? e : new Error(e); } }); /** * Binds methods of an object to the object itself, overwriting the existing * method. * * **Note:** This method doesn't set the "length" property of bound functions. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Object} object The object to bind and assign the bound methods to. * @param {...(string|string[])} methodNames The object method names to bind. * @returns {Object} Returns `object`. * @example * * var view = { * 'label': 'docs', * 'click': function() { * console.log('clicked ' + this.label); * } * }; * * _.bindAll(view, ['click']); * jQuery(element).on('click', view.click); * // => Logs 'clicked docs' when clicked. */ var bindAll = flatRest(function(object, methodNames) { arrayEach(methodNames, function(key) { key = toKey(key); baseAssignValue(object, key, bind(object[key], object)); }); return object; }); /** * Creates a function that iterates over `pairs` and invokes the corresponding * function of the first predicate to return truthy. The predicate-function * pairs are invoked with the `this` binding and arguments of the created * function. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Array} pairs The predicate-function pairs. * @returns {Function} Returns the new composite function. * @example * * var func = _.cond([ * [_.matches({ 'a': 1 }), _.constant('matches A')], * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], * [_.stubTrue, _.constant('no match')] * ]); * * func({ 'a': 1, 'b': 2 }); * // => 'matches A' * * func({ 'a': 0, 'b': 1 }); * // => 'matches B' * * func({ 'a': '1', 'b': '2' }); * // => 'no match' */ function cond(pairs) { var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); pairs = !length ? [] : arrayMap(pairs, function(pair) { if (typeof pair[1] != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } return [toIteratee(pair[0]), pair[1]]; }); return baseRest(function(args) { var index = -1; while (++index < length) { var pair = pairs[index]; if (apply(pair[0], this, args)) { return apply(pair[1], this, args); } } }); } /** * Creates a function that invokes the predicate properties of `source` with * the corresponding property values of a given object, returning `true` if * all predicates return truthy, else `false`. * * **Note:** The created function is equivalent to `_.conformsTo` with * `source` partially applied. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {Object} source The object of property predicates to conform to. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 2, 'b': 1 }, * { 'a': 1, 'b': 2 } * ]; * * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); * // => [{ 'a': 1, 'b': 2 }] */ function conforms(source) { return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } /** * Checks `value` to determine whether a default value should be returned in * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, * or `undefined`. * * @static * @memberOf _ * @since 4.14.0 * @category Util * @param {*} value The value to check. * @param {*} defaultValue The default value. * @returns {*} Returns the resolved value. * @example * * _.defaultTo(1, 10); * // => 1 * * _.defaultTo(undefined, 10); * // => 10 */ function defaultTo(value, defaultValue) { return (value == null || value !== value) ? defaultValue : value; } /** * Creates a function that returns the result of invoking the given functions * with the `this` binding of the created function, where each successive * invocation is supplied the return value of the previous. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flowRight * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flow([_.add, square]); * addSquare(1, 2); * // => 9 */ var flow = createFlow(); /** * This method is like `_.flow` except that it creates a function that * invokes the given functions from right to left. * * @static * @since 3.0.0 * @memberOf _ * @category Util * @param {...(Function|Function[])} [funcs] The functions to invoke. * @returns {Function} Returns the new composite function. * @see _.flow * @example * * function square(n) { * return n * n; * } * * var addSquare = _.flowRight([square, _.add]); * addSquare(1, 2); * // => 9 */ var flowRight = createFlow(true); /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between a given * object and `source`, returning `true` if the given object has equivalent * property values, else `false`. * * **Note:** The created function is equivalent to `_.isMatch` with `source` * partially applied. * * Partial comparisons will match empty array and empty object `source` * values against any array or object value, respectively. See `_.isEqual` * for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); * // => [{ 'a': 4, 'b': 5, 'c': 6 }] * * // Checking for several possible values * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matches(source) { return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); } /** * Creates a function that performs a partial deep comparison between the * value at `path` of a given object to `srcValue`, returning `true` if the * object value is equivalent, else `false`. * * **Note:** Partial comparisons will match empty array and empty object * `srcValue` values against any array or object value, respectively. See * `_.isEqual` for a list of supported value comparisons. * * **Note:** Multiple values can be checked by combining several matchers * using `_.overSome` * * @static * @memberOf _ * @since 3.2.0 * @category Util * @param {Array|string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. * @example * * var objects = [ * { 'a': 1, 'b': 2, 'c': 3 }, * { 'a': 4, 'b': 5, 'c': 6 } * ]; * * _.find(objects, _.matchesProperty('a', 4)); * // => { 'a': 4, 'b': 5, 'c': 6 } * * // Checking for several possible values * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] */ function matchesProperty(path, srcValue) { return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); } /** * Creates a function that invokes the method at `path` of a given object. * Any additional arguments are provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Array|string} path The path of the method to invoke. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var objects = [ * { 'a': { 'b': _.constant(2) } }, * { 'a': { 'b': _.constant(1) } } * ]; * * _.map(objects, _.method('a.b')); * // => [2, 1] * * _.map(objects, _.method(['a', 'b'])); * // => [2, 1] */ var method = baseRest(function(path, args) { return function(object) { return baseInvoke(object, path, args); }; }); /** * The opposite of `_.method`; this method creates a function that invokes * the method at a given path of `object`. Any additional arguments are * provided to the invoked method. * * @static * @memberOf _ * @since 3.7.0 * @category Util * @param {Object} object The object to query. * @param {...*} [args] The arguments to invoke the method with. * @returns {Function} Returns the new invoker function. * @example * * var array = _.times(3, _.constant), * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.methodOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); * // => [2, 0] */ var methodOf = baseRest(function(object, args) { return function(path) { return baseInvoke(object, path, args); }; }); /** * Adds all own enumerable string keyed function properties of a source * object to the destination object. If `object` is a function, then methods * are added to its prototype as well. * * **Note:** Use `_.runInContext` to create a pristine `lodash` function to * avoid conflicts caused by modifying the original. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {Function|Object} [object=lodash] The destination object. * @param {Object} source The object of functions to add. * @param {Object} [options={}] The options object. * @param {boolean} [options.chain=true] Specify whether mixins are chainable. * @returns {Function|Object} Returns `object`. * @example * * function vowels(string) { * return _.filter(string, function(v) { * return /[aeiou]/i.test(v); * }); * } * * _.mixin({ 'vowels': vowels }); * _.vowels('fred'); * // => ['e'] * * _('fred').vowels().value(); * // => ['e'] * * _.mixin({ 'vowels': vowels }, { 'chain': false }); * _('fred').vowels(); * // => ['e'] */ function mixin(object, source, options) { var props = keys(source), methodNames = baseFunctions(source, props); if (options == null && !(isObject(source) && (methodNames.length || !props.length))) { options = source; source = object; object = this; methodNames = baseFunctions(source, keys(source)); } var chain = !(isObject(options) && 'chain' in options) || !!options.chain, isFunc = isFunction(object); arrayEach(methodNames, function(methodName) { var func = source[methodName]; object[methodName] = func; if (isFunc) { object.prototype[methodName] = function() { var chainAll = this.__chain__; if (chain || chainAll) { var result = object(this.__wrapped__), actions = result.__actions__ = copyArray(this.__actions__); actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); result.__chain__ = chainAll; return result; } return func.apply(object, arrayPush([this.value()], arguments)); }; } }); return object; } /** * Reverts the `_` variable to its previous value and returns a reference to * the `lodash` function. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @returns {Function} Returns the `lodash` function. * @example * * var lodash = _.noConflict(); */ function noConflict() { if (root._ === this) { root._ = oldDash; } return this; } /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } /** * Creates a function that gets the argument at index `n`. If `n` is negative, * the nth argument from the end is returned. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [n=0] The index of the argument to return. * @returns {Function} Returns the new pass-thru function. * @example * * var func = _.nthArg(1); * func('a', 'b', 'c', 'd'); * // => 'b' * * var func = _.nthArg(-2); * func('a', 'b', 'c', 'd'); * // => 'c' */ function nthArg(n) { n = toInteger(n); return baseRest(function(args) { return baseNth(args, n); }); } /** * Creates a function that invokes `iteratees` with the arguments it receives * and returns their results. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [iteratees=[_.identity]] * The iteratees to invoke. * @returns {Function} Returns the new function. * @example * * var func = _.over([Math.max, Math.min]); * * func(1, 2, 3, 4); * // => [4, 1] */ var over = createOver(arrayMap); /** * Creates a function that checks if **all** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overEvery([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => false * * func(NaN); * // => false */ var overEvery = createOver(arrayEvery); /** * Creates a function that checks if **any** of the `predicates` return * truthy when invoked with the arguments it receives. * * Following shorthands are possible for providing predicates. * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {...(Function|Function[])} [predicates=[_.identity]] * The predicates to check. * @returns {Function} Returns the new function. * @example * * var func = _.overSome([Boolean, isFinite]); * * func('1'); * // => true * * func(null); * // => true * * func(NaN); * // => false * * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) */ var overSome = createOver(arraySome); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } /** * The opposite of `_.property`; this method creates a function that returns * the value at a given path of `object`. * * @static * @memberOf _ * @since 3.0.0 * @category Util * @param {Object} object The object to query. * @returns {Function} Returns the new accessor function. * @example * * var array = [0, 1, 2], * object = { 'a': array, 'b': array, 'c': array }; * * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); * // => [2, 0] * * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); * // => [2, 0] */ function propertyOf(object) { return function(path) { return object == null ? undefined : baseGet(object, path); }; } /** * Creates an array of numbers (positive and/or negative) progressing from * `start` up to, but not including, `end`. A step of `-1` is used if a negative * `start` is specified without an `end` or `step`. If `end` is not specified, * it's set to `start` with `start` then set to `0`. * * **Note:** JavaScript follows the IEEE-754 standard for resolving * floating-point values which can produce unexpected results. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.rangeRight * @example * * _.range(4); * // => [0, 1, 2, 3] * * _.range(-4); * // => [0, -1, -2, -3] * * _.range(1, 5); * // => [1, 2, 3, 4] * * _.range(0, 20, 5); * // => [0, 5, 10, 15] * * _.range(0, -4, -1); * // => [0, -1, -2, -3] * * _.range(1, 4, 0); * // => [1, 1, 1] * * _.range(0); * // => [] */ var range = createRange(); /** * This method is like `_.range` except that it populates values in * descending order. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {number} [start=0] The start of the range. * @param {number} end The end of the range. * @param {number} [step=1] The value to increment or decrement by. * @returns {Array} Returns the range of numbers. * @see _.inRange, _.range * @example * * _.rangeRight(4); * // => [3, 2, 1, 0] * * _.rangeRight(-4); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 5); * // => [4, 3, 2, 1] * * _.rangeRight(0, 20, 5); * // => [15, 10, 5, 0] * * _.rangeRight(0, -4, -1); * // => [-3, -2, -1, 0] * * _.rangeRight(1, 4, 0); * // => [1, 1, 1] * * _.rangeRight(0); * // => [] */ var rangeRight = createRange(true); /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } /** * This method returns a new empty object. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Object} Returns the new empty object. * @example * * var objects = _.times(2, _.stubObject); * * console.log(objects); * // => [{}, {}] * * console.log(objects[0] === objects[1]); * // => false */ function stubObject() { return {}; } /** * This method returns an empty string. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {string} Returns the empty string. * @example * * _.times(2, _.stubString); * // => ['', ''] */ function stubString() { return ''; } /** * This method returns `true`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `true`. * @example * * _.times(2, _.stubTrue); * // => [true, true] */ function stubTrue() { return true; } /** * Invokes the iteratee `n` times, returning an array of the results of * each invocation. The iteratee is invoked with one argument; (index). * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {number} n The number of times to invoke `iteratee`. * @param {Function} [iteratee=_.identity] The function invoked per iteration. * @returns {Array} Returns the array of results. * @example * * _.times(3, String); * // => ['0', '1', '2'] * * _.times(4, _.constant(0)); * // => [0, 0, 0, 0] */ function times(n, iteratee) { n = toInteger(n); if (n < 1 || n > MAX_SAFE_INTEGER) { return []; } var index = MAX_ARRAY_LENGTH, length = nativeMin(n, MAX_ARRAY_LENGTH); iteratee = getIteratee(iteratee); n -= MAX_ARRAY_LENGTH; var result = baseTimes(length, iteratee); while (++index < n) { iteratee(index); } return result; } /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } /** * Generates a unique ID. If `prefix` is given, the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } /*------------------------------------------------------------------------*/ /** * Adds two numbers. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {number} augend The first number in an addition. * @param {number} addend The second number in an addition. * @returns {number} Returns the total. * @example * * _.add(6, 4); * // => 10 */ var add = createMathOperation(function(augend, addend) { return augend + addend; }, 0); /** * Computes `number` rounded up to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round up. * @param {number} [precision=0] The precision to round up to. * @returns {number} Returns the rounded up number. * @example * * _.ceil(4.006); * // => 5 * * _.ceil(6.004, 2); * // => 6.01 * * _.ceil(6040, -2); * // => 6100 */ var ceil = createRound('ceil'); /** * Divide two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} dividend The first number in a division. * @param {number} divisor The second number in a division. * @returns {number} Returns the quotient. * @example * * _.divide(6, 4); * // => 1.5 */ var divide = createMathOperation(function(dividend, divisor) { return dividend / divisor; }, 1); /** * Computes `number` rounded down to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round down. * @param {number} [precision=0] The precision to round down to. * @returns {number} Returns the rounded down number. * @example * * _.floor(4.006); * // => 4 * * _.floor(0.046, 2); * // => 0.04 * * _.floor(4060, -2); * // => 4000 */ var floor = createRound('floor'); /** * Computes the maximum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the maximum value. * @example * * _.max([4, 2, 8, 6]); * // => 8 * * _.max([]); * // => undefined */ function max(array) { return (array && array.length) ? baseExtremum(array, identity, baseGt) : undefined; } /** * This method is like `_.max` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * // The `_.property` iteratee shorthand. * _.maxBy(objects, 'n'); * // => { 'n': 2 } */ function maxBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseGt) : undefined; } /** * Computes the mean of the values in `array`. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the mean. * @example * * _.mean([4, 2, 8, 6]); * // => 5 */ function mean(array) { return baseMean(array, identity); } /** * This method is like `_.mean` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be averaged. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the mean. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.meanBy(objects, function(o) { return o.n; }); * // => 5 * * // The `_.property` iteratee shorthand. * _.meanBy(objects, 'n'); * // => 5 */ function meanBy(array, iteratee) { return baseMean(array, getIteratee(iteratee, 2)); } /** * Computes the minimum value of `array`. If `array` is empty or falsey, * `undefined` is returned. * * @static * @since 0.1.0 * @memberOf _ * @category Math * @param {Array} array The array to iterate over. * @returns {*} Returns the minimum value. * @example * * _.min([4, 2, 8, 6]); * // => 2 * * _.min([]); * // => undefined */ function min(array) { return (array && array.length) ? baseExtremum(array, identity, baseLt) : undefined; } /** * This method is like `_.min` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the criterion by which * the value is ranked. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * _.minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * // The `_.property` iteratee shorthand. * _.minBy(objects, 'n'); * // => { 'n': 1 } */ function minBy(array, iteratee) { return (array && array.length) ? baseExtremum(array, getIteratee(iteratee, 2), baseLt) : undefined; } /** * Multiply two numbers. * * @static * @memberOf _ * @since 4.7.0 * @category Math * @param {number} multiplier The first number in a multiplication. * @param {number} multiplicand The second number in a multiplication. * @returns {number} Returns the product. * @example * * _.multiply(6, 4); * // => 24 */ var multiply = createMathOperation(function(multiplier, multiplicand) { return multiplier * multiplicand; }, 1); /** * Computes `number` rounded to `precision`. * * @static * @memberOf _ * @since 3.10.0 * @category Math * @param {number} number The number to round. * @param {number} [precision=0] The precision to round to. * @returns {number} Returns the rounded number. * @example * * _.round(4.006); * // => 4 * * _.round(4.006, 2); * // => 4.01 * * _.round(4060, -2); * // => 4100 */ var round = createRound('round'); /** * Subtract two numbers. * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {number} minuend The first number in a subtraction. * @param {number} subtrahend The second number in a subtraction. * @returns {number} Returns the difference. * @example * * _.subtract(6, 4); * // => 2 */ var subtract = createMathOperation(function(minuend, subtrahend) { return minuend - subtrahend; }, 0); /** * Computes the sum of the values in `array`. * * @static * @memberOf _ * @since 3.4.0 * @category Math * @param {Array} array The array to iterate over. * @returns {number} Returns the sum. * @example * * _.sum([4, 2, 8, 6]); * // => 20 */ function sum(array) { return (array && array.length) ? baseSum(array, identity) : 0; } /** * This method is like `_.sum` except that it accepts `iteratee` which is * invoked for each element in `array` to generate the value to be summed. * The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 * @category Math * @param {Array} array The array to iterate over. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. * @returns {number} Returns the sum. * @example * * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; * * _.sumBy(objects, function(o) { return o.n; }); * // => 20 * * // The `_.property` iteratee shorthand. * _.sumBy(objects, 'n'); * // => 20 */ function sumBy(array, iteratee) { return (array && array.length) ? baseSum(array, getIteratee(iteratee, 2)) : 0; } /*------------------------------------------------------------------------*/ // Add methods that return wrapped values in chain sequences. lodash.after = after; lodash.ary = ary; lodash.assign = assign; lodash.assignIn = assignIn; lodash.assignInWith = assignInWith; lodash.assignWith = assignWith; lodash.at = at; lodash.before = before; lodash.bind = bind; lodash.bindAll = bindAll; lodash.bindKey = bindKey; lodash.castArray = castArray; lodash.chain = chain; lodash.chunk = chunk; lodash.compact = compact; lodash.concat = concat; lodash.cond = cond; lodash.conforms = conforms; lodash.constant = constant; lodash.countBy = countBy; lodash.create = create; lodash.curry = curry; lodash.curryRight = curryRight; lodash.debounce = debounce; lodash.defaults = defaults; lodash.defaultsDeep = defaultsDeep; lodash.defer = defer; lodash.delay = delay; lodash.difference = difference; lodash.differenceBy = differenceBy; lodash.differenceWith = differenceWith; lodash.drop = drop; lodash.dropRight = dropRight; lodash.dropRightWhile = dropRightWhile; lodash.dropWhile = dropWhile; lodash.fill = fill; lodash.filter = filter; lodash.flatMap = flatMap; lodash.flatMapDeep = flatMapDeep; lodash.flatMapDepth = flatMapDepth; lodash.flatten = flatten; lodash.flattenDeep = flattenDeep; lodash.flattenDepth = flattenDepth; lodash.flip = flip; lodash.flow = flow; lodash.flowRight = flowRight; lodash.fromPairs = fromPairs; lodash.functions = functions; lodash.functionsIn = functionsIn; lodash.groupBy = groupBy; lodash.initial = initial; lodash.intersection = intersection; lodash.intersectionBy = intersectionBy; lodash.intersectionWith = intersectionWith; lodash.invert = invert; lodash.invertBy = invertBy; lodash.invokeMap = invokeMap; lodash.iteratee = iteratee; lodash.keyBy = keyBy; lodash.keys = keys; lodash.keysIn = keysIn; lodash.map = map; lodash.mapKeys = mapKeys; lodash.mapValues = mapValues; lodash.matches = matches; lodash.matchesProperty = matchesProperty; lodash.memoize = memoize; lodash.merge = merge; lodash.mergeWith = mergeWith; lodash.method = method; lodash.methodOf = methodOf; lodash.mixin = mixin; lodash.negate = negate; lodash.nthArg = nthArg; lodash.omit = omit; lodash.omitBy = omitBy; lodash.once = once; lodash.orderBy = orderBy; lodash.over = over; lodash.overArgs = overArgs; lodash.overEvery = overEvery; lodash.overSome = overSome; lodash.partial = partial; lodash.partialRight = partialRight; lodash.partition = partition; lodash.pick = pick; lodash.pickBy = pickBy; lodash.property = property; lodash.propertyOf = propertyOf; lodash.pull = pull; lodash.pullAll = pullAll; lodash.pullAllBy = pullAllBy; lodash.pullAllWith = pullAllWith; lodash.pullAt = pullAt; lodash.range = range; lodash.rangeRight = rangeRight; lodash.rearg = rearg; lodash.reject = reject; lodash.remove = remove; lodash.rest = rest; lodash.reverse = reverse; lodash.sampleSize = sampleSize; lodash.set = set; lodash.setWith = setWith; lodash.shuffle = shuffle; lodash.slice = slice; lodash.sortBy = sortBy; lodash.sortedUniq = sortedUniq; lodash.sortedUniqBy = sortedUniqBy; lodash.split = split; lodash.spread = spread; lodash.tail = tail; lodash.take = take; lodash.takeRight = takeRight; lodash.takeRightWhile = takeRightWhile; lodash.takeWhile = takeWhile; lodash.tap = tap; lodash.throttle = throttle; lodash.thru = thru; lodash.toArray = toArray; lodash.toPairs = toPairs; lodash.toPairsIn = toPairsIn; lodash.toPath = toPath; lodash.toPlainObject = toPlainObject; lodash.transform = transform; lodash.unary = unary; lodash.union = union; lodash.unionBy = unionBy; lodash.unionWith = unionWith; lodash.uniq = uniq; lodash.uniqBy = uniqBy; lodash.uniqWith = uniqWith; lodash.unset = unset; lodash.unzip = unzip; lodash.unzipWith = unzipWith; lodash.update = update; lodash.updateWith = updateWith; lodash.values = values; lodash.valuesIn = valuesIn; lodash.without = without; lodash.words = words; lodash.wrap = wrap; lodash.xor = xor; lodash.xorBy = xorBy; lodash.xorWith = xorWith; lodash.zip = zip; lodash.zipObject = zipObject; lodash.zipObjectDeep = zipObjectDeep; lodash.zipWith = zipWith; // Add aliases. lodash.entries = toPairs; lodash.entriesIn = toPairsIn; lodash.extend = assignIn; lodash.extendWith = assignInWith; // Add methods to `lodash.prototype`. mixin(lodash, lodash); /*------------------------------------------------------------------------*/ // Add methods that return unwrapped values in chain sequences. lodash.add = add; lodash.attempt = attempt; lodash.camelCase = camelCase; lodash.capitalize = capitalize; lodash.ceil = ceil; lodash.clamp = clamp; lodash.clone = clone; lodash.cloneDeep = cloneDeep; lodash.cloneDeepWith = cloneDeepWith; lodash.cloneWith = cloneWith; lodash.conformsTo = conformsTo; lodash.deburr = deburr; lodash.defaultTo = defaultTo; lodash.divide = divide; lodash.endsWith = endsWith; lodash.eq = eq; lodash.escape = escape; lodash.escapeRegExp = escapeRegExp; lodash.every = every; lodash.find = find; lodash.findIndex = findIndex; lodash.findKey = findKey; lodash.findLast = findLast; lodash.findLastIndex = findLastIndex; lodash.findLastKey = findLastKey; lodash.floor = floor; lodash.forEach = forEach; lodash.forEachRight = forEachRight; lodash.forIn = forIn; lodash.forInRight = forInRight; lodash.forOwn = forOwn; lodash.forOwnRight = forOwnRight; lodash.get = get; lodash.gt = gt; lodash.gte = gte; lodash.has = has; lodash.hasIn = hasIn; lodash.head = head; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.inRange = inRange; lodash.invoke = invoke; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isArrayBuffer = isArrayBuffer; lodash.isArrayLike = isArrayLike; lodash.isArrayLikeObject = isArrayLikeObject; lodash.isBoolean = isBoolean; lodash.isBuffer = isBuffer; lodash.isDate = isDate; lodash.isElement = isElement; lodash.isEmpty = isEmpty; lodash.isEqual = isEqual; lodash.isEqualWith = isEqualWith; lodash.isError = isError; lodash.isFinite = isFinite; lodash.isFunction = isFunction; lodash.isInteger = isInteger; lodash.isLength = isLength; lodash.isMap = isMap; lodash.isMatch = isMatch; lodash.isMatchWith = isMatchWith; lodash.isNaN = isNaN; lodash.isNative = isNative; lodash.isNil = isNil; lodash.isNull = isNull; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isObjectLike = isObjectLike; lodash.isPlainObject = isPlainObject; lodash.isRegExp = isRegExp; lodash.isSafeInteger = isSafeInteger; lodash.isSet = isSet; lodash.isString = isString; lodash.isSymbol = isSymbol; lodash.isTypedArray = isTypedArray; lodash.isUndefined = isUndefined; lodash.isWeakMap = isWeakMap; lodash.isWeakSet = isWeakSet; lodash.join = join; lodash.kebabCase = kebabCase; lodash.last = last; lodash.lastIndexOf = lastIndexOf; lodash.lowerCase = lowerCase; lodash.lowerFirst = lowerFirst; lodash.lt = lt; lodash.lte = lte; lodash.max = max; lodash.maxBy = maxBy; lodash.mean = mean; lodash.meanBy = meanBy; lodash.min = min; lodash.minBy = minBy; lodash.stubArray = stubArray; lodash.stubFalse = stubFalse; lodash.stubObject = stubObject; lodash.stubString = stubString; lodash.stubTrue = stubTrue; lodash.multiply = multiply; lodash.nth = nth; lodash.noConflict = noConflict; lodash.noop = noop; lodash.now = now; lodash.pad = pad; lodash.padEnd = padEnd; lodash.padStart = padStart; lodash.parseInt = parseInt; lodash.random = random; lodash.reduce = reduce; lodash.reduceRight = reduceRight; lodash.repeat = repeat; lodash.replace = replace; lodash.result = result; lodash.round = round; lodash.runInContext = runInContext; lodash.sample = sample; lodash.size = size; lodash.snakeCase = snakeCase; lodash.some = some; lodash.sortedIndex = sortedIndex; lodash.sortedIndexBy = sortedIndexBy; lodash.sortedIndexOf = sortedIndexOf; lodash.sortedLastIndex = sortedLastIndex; lodash.sortedLastIndexBy = sortedLastIndexBy; lodash.sortedLastIndexOf = sortedLastIndexOf; lodash.startCase = startCase; lodash.startsWith = startsWith; lodash.subtract = subtract; lodash.sum = sum; lodash.sumBy = sumBy; lodash.template = template; lodash.times = times; lodash.toFinite = toFinite; lodash.toInteger = toInteger; lodash.toLength = toLength; lodash.toLower = toLower; lodash.toNumber = toNumber; lodash.toSafeInteger = toSafeInteger; lodash.toString = toString; lodash.toUpper = toUpper; lodash.trim = trim; lodash.trimEnd = trimEnd; lodash.trimStart = trimStart; lodash.truncate = truncate; lodash.unescape = unescape; lodash.uniqueId = uniqueId; lodash.upperCase = upperCase; lodash.upperFirst = upperFirst; // Add aliases. lodash.each = forEach; lodash.eachRight = forEachRight; lodash.first = head; mixin(lodash, (function() { var source = {}; baseForOwn(lodash, function(func, methodName) { if (!hasOwnProperty.call(lodash.prototype, methodName)) { source[methodName] = func; } }); return source; }()), { 'chain': false }); /*------------------------------------------------------------------------*/ /** * The semantic version number. * * @static * @memberOf _ * @type {string} */ lodash.VERSION = VERSION; // Assign default placeholders. arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) { lodash[methodName].placeholder = lodash; }); // Add `LazyWrapper` methods for `_.drop` and `_.take` variants. arrayEach(['drop', 'take'], function(methodName, index) { LazyWrapper.prototype[methodName] = function(n) { n = n === undefined ? 1 : nativeMax(toInteger(n), 0); var result = (this.__filtered__ && !index) ? new LazyWrapper(this) : this.clone(); if (result.__filtered__) { result.__takeCount__ = nativeMin(n, result.__takeCount__); } else { result.__views__.push({ 'size': nativeMin(n, MAX_ARRAY_LENGTH), 'type': methodName + (result.__dir__ < 0 ? 'Right' : '') }); } return result; }; LazyWrapper.prototype[methodName + 'Right'] = function(n) { return this.reverse()[methodName](n).reverse(); }; }); // Add `LazyWrapper` methods that accept an `iteratee` value. arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) { var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; LazyWrapper.prototype[methodName] = function(iteratee) { var result = this.clone(); result.__iteratees__.push({ 'iteratee': getIteratee(iteratee, 3), 'type': type }); result.__filtered__ = result.__filtered__ || isFilter; return result; }; }); // Add `LazyWrapper` methods for `_.head` and `_.last`. arrayEach(['head', 'last'], function(methodName, index) { var takeName = 'take' + (index ? 'Right' : ''); LazyWrapper.prototype[methodName] = function() { return this[takeName](1).value()[0]; }; }); // Add `LazyWrapper` methods for `_.initial` and `_.tail`. arrayEach(['initial', 'tail'], function(methodName, index) { var dropName = 'drop' + (index ? '' : 'Right'); LazyWrapper.prototype[methodName] = function() { return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); }; }); LazyWrapper.prototype.compact = function() { return this.filter(identity); }; LazyWrapper.prototype.find = function(predicate) { return this.filter(predicate).head(); }; LazyWrapper.prototype.findLast = function(predicate) { return this.reverse().find(predicate); }; LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { if (typeof path == 'function') { return new LazyWrapper(this); } return this.map(function(value) { return baseInvoke(value, path, args); }); }); LazyWrapper.prototype.reject = function(predicate) { return this.filter(negate(getIteratee(predicate))); }; LazyWrapper.prototype.slice = function(start, end) { start = toInteger(start); var result = this; if (result.__filtered__ && (start > 0 || end < 0)) { return new LazyWrapper(result); } if (start < 0) { result = result.takeRight(-start); } else if (start) { result = result.drop(start); } if (end !== undefined) { end = toInteger(end); result = end < 0 ? result.dropRight(-end) : result.take(end - start); } return result; }; LazyWrapper.prototype.takeRightWhile = function(predicate) { return this.reverse().takeWhile(predicate).reverse(); }; LazyWrapper.prototype.toArray = function() { return this.take(MAX_ARRAY_LENGTH); }; // Add `LazyWrapper` methods to `lodash.prototype`. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName], retUnwrapped = isTaker || /^find/.test(methodName); if (!lodashFunc) { return; } lodash.prototype[methodName] = function() { var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee = args[0], useLazy = isLazy || isArray(value); var interceptor = function(value) { var result = lodashFunc.apply(lodash, arrayPush([value], args)); return (isTaker && chainAll) ? result[0] : result; }; if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) { // Avoid lazy use if the iteratee has a "length" value other than `1`. isLazy = useLazy = false; } var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; if (!retUnwrapped && useLazy) { value = onlyLazy ? value : new LazyWrapper(this); var result = func.apply(value, args); result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined }); return new LodashWrapper(result, chainAll); } if (isUnwrapped && onlyLazy) { return func.apply(this, args); } result = this.thru(interceptor); return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result; }; }); // Add `Array` methods to `lodash.prototype`. arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) { var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru', retUnwrapped = /^(?:pop|shift)$/.test(methodName); lodash.prototype[methodName] = function() { var args = arguments; if (retUnwrapped && !this.__chain__) { var value = this.value(); return func.apply(isArray(value) ? value : [], args); } return this[chainName](function(value) { return func.apply(isArray(value) ? value : [], args); }); }; }); // Map minified method names to their real names. baseForOwn(LazyWrapper.prototype, function(func, methodName) { var lodashFunc = lodash[methodName]; if (lodashFunc) { var key = lodashFunc.name + ''; if (!hasOwnProperty.call(realNames, key)) { realNames[key] = []; } realNames[key].push({ 'name': methodName, 'func': lodashFunc }); } }); realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{ 'name': 'wrapper', 'func': undefined }]; // Add methods to `LazyWrapper`. LazyWrapper.prototype.clone = lazyClone; LazyWrapper.prototype.reverse = lazyReverse; LazyWrapper.prototype.value = lazyValue; // Add chain sequence methods to the `lodash` wrapper. lodash.prototype.at = wrapperAt; lodash.prototype.chain = wrapperChain; lodash.prototype.commit = wrapperCommit; lodash.prototype.next = wrapperNext; lodash.prototype.plant = wrapperPlant; lodash.prototype.reverse = wrapperReverse; lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue; // Add lazy aliases. lodash.prototype.first = lodash.prototype.head; if (symIterator) { lodash.prototype[symIterator] = wrapperToIterator; } return lodash; }); /*--------------------------------------------------------------------------*/ // Export lodash. var _ = runInContext(); // Some AMD build optimizers, like r.js, check for condition patterns like: if (true) { // Expose Lodash on the global object to prevent errors when Lodash is // loaded by a script tag in the presence of an AMD loader. // See http://requirejs.org/docs/errors.html#mismatch for more details. // Use `_.noConflict` to remove Lodash from the global object. root._ = _; // Define as an anonymous module so, through path mapping, it can be // referenced as the "underscore" module. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function() { return _; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // Check for `exports` after `define` in case a build optimizer adds it. else {} }.call(this)); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ "./node_modules/webpack/buildin/global.js"), __webpack_require__(/*! ./../webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module))) /***/ }), /***/ "./node_modules/process/browser.js": /*!*****************************************!*\ !*** ./node_modules/process/browser.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }), /***/ "./node_modules/webpack/buildin/global.js": /*!***********************************!*\ !*** (webpack)/buildin/global.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { var g; // This works in non-strict mode g = (function() { return this; })(); try { // This works if eval is allowed (see CSP) g = g || new Function("return this")(); } catch (e) { // This works if the window reference is available if (typeof window === "object") g = window; } // g can still be undefined, but nothing to do about it... // We return undefined, instead of nothing here, so it's // easier to handle this case. if(!global) { ...} module.exports = g; /***/ }), /***/ "./node_modules/webpack/buildin/module.js": /*!***********************************!*\ !*** (webpack)/buildin/module.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports) { module.exports = function(module) { if (!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default if (!module.children) module.children = []; Object.defineProperty(module, "loaded", { enumerable: true, get: function() { return module.l; } }); Object.defineProperty(module, "id", { enumerable: true, get: function() { return module.i; } }); module.webpackPolyfill = 1; } return module; }; /***/ }), /***/ "./resources/assets/frontend/sass/app.scss": /*!*************************************************!*\ !*** ./resources/assets/frontend/sass/app.scss ***! \*************************************************/ /*! no static exports found */ /***/ (function(module, exports) { // removed by extract-text-webpack-plugin /***/ }), /***/ "./resources/js/app.js": /*!*****************************!*\ !*** ./resources/js/app.js ***! \*****************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! ./bootstrap */ "./resources/js/bootstrap.js"); /***/ }), /***/ "./resources/js/bootstrap.js": /*!***********************************!*\ !*** ./resources/js/bootstrap.js ***! \***********************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { window._ = __webpack_require__(/*! lodash */ "./node_modules/lodash/lodash.js"); /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ window.axios = __webpack_require__(/*! axios */ "./node_modules/axios/index.js"); window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo'; // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: process.env.MIX_PUSHER_APP_KEY, // cluster: process.env.MIX_PUSHER_APP_CLUSTER, // forceTLS: true // }); /***/ }), /***/ 0: /*!*****************************************************************************!*\ !*** multi ./resources/js/app.js ./resources/assets/frontend/sass/app.scss ***! \*****************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { __webpack_require__(/*! C:\laragon\www\shop\resources\js\app.js */"./resources/js/app.js"); module.exports = __webpack_require__(/*! C:\laragon\www\shop\resources\assets\frontend\sass\app.scss */"./resources/assets/frontend/sass/app.scss"); /***/ }) /******/ });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.getEditorPreview = void 0; var _react = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _netlifyCmsUiDefault = require("netlify-cms-ui-default"); var _serializers = require("./serializers"); var _core = require("@emotion/core"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } let editorPreview; const getEditorPreview = () => editorPreview; exports.getEditorPreview = getEditorPreview; const MarkdownPreview = props => { const { value, getAsset, resolveWidget } = props; (0, _react.useEffect)(() => { editorPreview = props.editorPreview; }, []); if (value === null) { return null; } const html = (0, _serializers.markdownToHtml)(value, { getAsset, resolveWidget }); return (0, _core.jsx)(_netlifyCmsUiDefault.WidgetPreviewContainer, { dangerouslySetInnerHTML: { __html: html } }); }; MarkdownPreview.propTypes = { getAsset: _propTypes.default.func.isRequired, editorPreview: _propTypes.default.func.isRequired, resolveWidget: _propTypes.default.func.isRequired, value: _propTypes.default.string }; var _default = MarkdownPreview; exports.default = _default;
import React from 'react' import { addStoriesFromModule } from '../helpers' import ProgressBar from 'core/components/progress/ProgressBar' const addStories = addStoriesFromModule(module) addStories('Common Components/ProgressBar', { 'Progress bar': () => ( <ProgressBar percent={40} label={progress => `${progress}% used`} /> ), 'Compact': () => ( <ProgressBar compact percent={40} label={progress => <span><strong>{progress}%</strong>{'- 5.7/19.3GB used'}</span>} /> ), })
import { connect } from 'react-redux' import Container from './container'; import { actionCreators as userActions } from '../../redux/modules/user'; const mapDispatchToProps = (dispatch, ownProps) => { return { login: (username, password) => { return dispatch(userActions.login(username, password)); }, fbLogin: () => { return dispatch(userActions.facebookLogin()); } } } export default connect(null, mapDispatchToProps)(Container);
import jsonpickle from .sym_session import Session class APIBase: def __init__(self, current_session: Session): self.session = current_session self.api_base_url = self.session.config['api_host'] + ':' + self.session.config['api_port'] + '/' def get_endpoint(self, symphony_endpoint: str): return self.api_base_url + symphony_endpoint def post(self, endpoint: str, body): return self.rest_callout('post', endpoint, body) def get(self, endpoint: str): return self.rest_callout('get', endpoint) def rest_callout(self, method, endpoint, body_object=None): self.session.authenticate() response = None if method.lower() == 'get': response = self.session.http_session.get(endpoint, headers=self.session.get_rest_headers()) elif method.lower() == 'post': body_str = jsonpickle.encode(body_object, unpicklable=False) response = self.session.http_session.post(endpoint, data=body_str, headers=self.session.get_rest_headers()) # elif method.lower() == 'postv2': if response.status_code // 100 != 2: response.raise_for_status() return response.text
const express = require('express'); const http = require('http').Server(express); const path = require('path'); const expressHandlebars = require('express-handlebars'); const swim = require('@swim/client'); // const swim = new client.Client({sendBufferSize: 1024*1024}); class HttpServer { constructor(httpConfig, db, showDebug = false) { this.config = httpConfig; this.port = this.config.hostPort; this.botName = this.config.botName; this.server = null; this.webApp = null; this.showDebug = showDebug; this.hbsHelpers = null; this.wikiQuote = null; this.main = null; this.hostUrl = this.config.hostUrl; this.swimPort = this.config.swimPort; this.fullHostUrl = 'http://' + this.hostUrl + ((this.port !== 80) ? (':' + this.port) : ''); this.fullSwimUrl = 'ws://' + this.hostUrl + ':' + this.swimPort; this.fullAggUrl = 'http://' + this.config.aggregateHost + ((this.port !== 80) ? (':' + this.port) : ''); this.fullAggSwimUrl = 'ws://' + this.config.aggregateHost + ':9001'; this.isPlantMon = this.config.isPlantMon; this.isSenseHat = this.config.isSenseHat; this.isAggregator = this.config.isAggregator; console.info('create http server @' + this.fullHostUrl); this.botList = []; } /** * start up http server and setup express */ setUpEngine() { // initialized ExpressJS this.webApp = express(); this.webApp.engine('.hbs', expressHandlebars({ defaultLayout: 'main', extname: '.hbs', layoutsDir: path.join(__dirname, 'views/layouts') })); this.webApp.set('view engine', '.hbs'); this.webApp.set('views', path.join(__dirname, 'views')); this.webApp.use('/js', express.static(path.join(__dirname + '/views/js'))); this.webApp.use('/css', express.static(path.join(__dirname + '/views/css'))); this.webApp.use('/assets', express.static(path.join(__dirname + '/views/assets'))); // define our webserver this.server = require('http').Server(this.webApp); // create our handlebars helpers this.hbsHelpers = { 'if_eq': (a, b, opts) => { if (a == b) { return opts.fn(this); } else { return opts.inverse(this); } }, 'if_not_eq': (a, b, opts) => { if (a != b) { return opts.fn(this); } else { return opts.inverse(this); } }, }; } /** * this posts key value pair to a specified sensor lane as a command to swim */ sendSensorDataCommand(messageKey, messageData) { for(const dataKey in messageData) { // console.info(this.fullSwimUrl, `/sensor/${dataKey}`, `addLatest`, messageData[dataKey]); swim.command(this.fullSwimUrl, `/sensor/${dataKey}`, `addLatest`, messageData[dataKey]); } } /** * server error handler * @param {[Object]} err [message object] */ onServerStarted(err) { if (err) { console.error('[httpServer] startup error', err); } if (this.showDebug) { console.info(`[httpServer] express server listening on ${this.port}`); } } /** * utility method which creates all the page routes to be used by ExpressJS */ createPageRoutes() { // home page route this.webApp.get('/', (request, response) => { response.render('homePage', { routeName: 'home', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) // plant monitor page route this.webApp.route('/plantMon') .get((request, response) => { const reqParams = request.params; response.render('plantMon', { routeName: 'plant', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) // senseHat monitor page (a.k.a. bot page) this.webApp.route('/senseHat') .get((request, response) => { const reqParams = request.params; const plantId = reqParams.plantId; response.render('senseHat', { routeName: 'senseHat', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) // main view aggregate page this.webApp.route('/aggregate') .get((request, response) => { const reqParams = request.params; const plantId = reqParams.plantId; response.render('aggregatePage', { routeName: 'aggregator', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) // aggregate status monitor page. this.webApp.route('/monitor') .get((request, response) => { const reqParams = request.params; const plantId = reqParams.plantId; response.render('monitor', { routeName: 'monitor', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) // zones page route this.webApp.route('/zones') .get((request, response) => { const reqParams = request.params; const plantId = reqParams.plantId; response.render('zonesPage', { routeName: 'zones', botName: this.botName, fullHostUrl: this.fullHostUrl, fullSwimUrl: this.fullSwimUrl, aggregateHostUrl: this.fullAggUrl, aggregateSwimUrl: this.fullAggSwimUrl, isAggregator: this.isAggregator, isPlantMon: this.isPlantMon, isSenseHat: this.isSenseHat, helpers: this.hbsHelpers }) }) } /** * startup http server */ startHttpServer(mainThread) { this.main = mainThread; this.setUpEngine(); this.createPageRoutes(); this.server.listen(this.port, this.onServerStarted.bind(this)); } } module.exports = HttpServer;
/*! * tcd-advanced-searchbox v1.2.5 * https://github.com/TheCodeDestroyer/tcd-advanced-searchbox * Copyright (c) 2015 Nace Logar http://thecodedestroyer.com/ * License: MIT */ !function(){"use strict";angular.module("tcd-advanced-searchbox",[]).directive("tcdAdvancedSearchbox",function(){return{restrict:"E",scope:{model:"=ngModel",parameters:"="},replace:!0,templateUrl:"tcd-advanced-searchbox.html",controller:["$scope","$attrs","$element","$timeout","$filter",function(a,b,c,d,e){function f(){angular.forEach(a.model,function(b,c){if("query"===c)a.searchQuery=b;else{var d=e("filter")(a.parameters,function(a){return a.key===c})[0];void 0!==d&&a.addSearchParam(d,b,!1)}})}function g(){i&&d.cancel(i),i=d(function(){a.model={},a.searchQuery.length>0&&(a.model.query=a.searchQuery),angular.forEach(a.searchParams,function(b){void 0!==b.value&&b.value.length>0&&(_.isEmpty(a.model[b.key])&&(a.model[b.key]=[]),a.model[b.key].push({searchValue:b.value,type:b.type,equality:b.equality.value}))})},500)}function h(a){if(!a)return 0;if("number"==typeof a.selectionStart)return"backward"===a.selectionDirection?a.selectionStart:a.selectionEnd;if(document.selection){a.focus();var b=document.selection.createRange(),c=document.selection.createRange().text.length;return b.moveStart("character",-a.value.length),b.text.length-c}return 0}a.placeholder=b.placeholder||"Search ...",a.searchParams=[],a.searchQuery="",a.setSearchFocus=!1,a.equalityChoices=b.equalityChoices?b.equalityChoices:[{value:"Eq",text:"Equal"},{value:"Neq",text:"Not equal"},{value:"Lt",text:"Lower"},{value:"Gt",text:"Greater"},{value:"Lte",text:"Equal or Lower"},{value:"Gte",text:"Equal or Greater"},{value:"Con",text:"Contains"}],a.$watch("searchQuery",function(){g()}),a.$watch("searchParams",function(){g()},!0),a.enterEditMode=function(b){if(void 0!==b){var c=a.searchParams[b];c.editMode=!0}},a.leaveEditMode=function(b){if(void 0!==b){var c=a.searchParams[b];c.editMode=!1,c.value||a.removeSearchParam(b)}},a.typeaheadOnSelect=function(b,c,d){a.addSearchParam(b),a.searchQuery=""},a.addSearchParam=function(b,c,d){void 0===d&&(d=!0),b.equality||(b.equality=a.equalityChoices[0]),a.searchParams.push({key:b.key,name:b.name,equality:b.equality,type:b.type,placeholder:b.placeholder,value:c||"",editMode:d})},a.removeSearchParam=function(b){void 0!==b&&a.searchParams.splice(b,1)},a.removeAll=function(){a.searchParams=[],a.searchQuery=""},a.editPrevious=function(b){void 0!==b&&a.leaveEditMode(b),b>0?a.enterEditMode(b-1):a.searchParams.length>0&&a.enterEditMode(a.searchParams.length-1)},a.editNext=function(b){void 0!==b&&(a.leaveEditMode(b),b<a.searchParams.length-1?a.enterEditMode(b+1):a.setSearchFocus=!0)},a.keydown=function(b,c){var d=[8,9,13,37,39];if(-1!==d.indexOf(b.which)){var e=h(b.target);8==b.which?0===e&&a.editPrevious(c):9==b.which?b.shiftKey?(b.preventDefault(),a.editPrevious(c)):(b.preventDefault(),a.editNext(c)):13==b.which?a.editNext(c):37==b.which?0===e&&a.editPrevious(c):39==b.which&&e===b.target.value.length&&a.editNext(c)}},void 0===a.model?a.model={}:f();var i}]}}).directive("tcdSetFocus",["$timeout","$parse",function(a,b){return{restrict:"A",link:function(c,d,e){var f=b(e.tcdSetFocus);c.$watch(f,function(b){b===!0&&a(function(){d[0].focus()})}),d.bind("blur",function(){c.$apply(f.assign(c,!1))})}}}]).directive("tcdAutoSizeInput",[function(){return{restrict:"A",scope:{model:"=ngModel"},link:function(a,b){function c(){e.text(b.val()||b.attr("placeholder")),b.css("width",e.outerWidth()+10)}var d=angular.element('<div style="position: fixed; top: -9999px; left: 0px;"></div>'),e=angular.element('<span style="white-space:pre;"></span>'),f="none"===b.css("maxWidth")?b.parent().innerWidth():b.css("maxWidth");b.css("maxWidth",f),angular.forEach(["fontSize","fontFamily","fontWeight","fontStyle","letterSpacing","textTransform","wordSpacing","textIndent","boxSizing","borderLeftWidth","borderRightWidth","borderLeftStyle","borderRightStyle","paddingLeft","paddingRight","marginLeft","marginRight"],function(a){e.css(a,b.css(a))}),angular.element("body").append(d.append(e)),c(),a.model?a.$watch("model",function(){c()}):b.on("keypress keyup keydown focus input propertychange change",function(){c()})}}}])}(),angular.module("tcd-advanced-searchbox").run(["$templateCache",function(a){"use strict";a.put("tcd-advanced-searchbox.html",'<div class=advancedSearchBox ng-class="{ active: focus }" ng-init="focus = false"><i ng-show="searchParams.length < 1 && searchQuery.length === 0" class="search-icon fa fa-search"></i> <a ng-href="" ng-show="searchParams.length > 0 || searchQuery.length > 0" ng-click=removeAll() role=button><i class="remove-all-icon fa fa-trash-o"></i></a><div><div class=search-parameter ng-repeat="searchParam in searchParams"><a ng-href="" ng-click=removeSearchParam($index) role=button><i class="remove fa fa-trash-o"></i></a><div class=key>{{ searchParam.name }}</div><div class=value><span ng-show=!searchParam.editMode ng-click=enterEditMode($index)>{{ searchParam.value }}</span><div class=dropdown ng-show="searchParam.value && !searchParam.editMode"><button class="btn btn-default dropdown-toggle" type=button id=dropdownMenu1 data-toggle=dropdown aria-expanded=true style="line-height: 3px">{{ searchParam.equality.text }} <span class=caret></span></button><ul class=dropdown-menu role=menu aria-labelledby=dropdownMenu1><li ng-repeat="equalityChoice in equalityChoices" role=presentation><a role=menuitem tabindex=-1 ng-click="searchParam.equality = equalityChoice">{{ equalityChoice.text }}</a></li></ul></div><input name=value tcd-auto-size-input tcd-set-focus=searchParam.editMode ng-keydown="keydown($event, $index)" ng-blur=leaveEditMode($index) ng-show=searchParam.editMode ng-model=searchParam.value placeholder="{{ searchParam.placeholder }}"></div></div><input name=searchbox class=search-parameter-input tcd-set-focus=setSearchFocus ng-keydown=keydown($event) placeholder="{{ placeholder }}" ng-focus="focus = true" ng-blur="focus = false" typeahead-on-select="typeaheadOnSelect($item, $model, $label)" typeahead="parameter as parameter.name for parameter in parameters | filter:{name:$viewValue} | limitTo:8" ng-model="searchQuery"></div><div class=search-parameter-suggestions ng-show="parameters && focus"><span class=title>Parameter Suggestions:</span> <span class=search-parameter ng-repeat="param in parameters | limitTo:8" ng-mousedown=addSearchParam(param)>{{ param.name }}</span></div></div>')}]);
const form = document.querySelector("form"); const name = document.querySelector("#name"); const cost = document.querySelector("#cost"); const error = document.querySelector("#error"); form.addEventListener("submit", (e) => { e.preventDefault(); if (name.value && cost.value) { const item = { name: name.value, cost: parseInt(cost.value), }; db.collection("expenses") .add(item) .then((res) => { error.textContent = ""; name.value = ""; cost.value = ""; }); } else { error.textContent = "Please enter values before submitting"; } });
# Copyright 2014 Cognitect. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import functools from random import random """ This is an implementation of Rich Hickey's Transducers from Clojure in Python. It uses functional programming in Python and an alternative reduce which recognizes Reduced, a sentinel wrapper with a value that can be extracted to signal early termination. Composed transducers result in a reversed composed process. E.g., > compose(map(f), filter(g)) Will apply f to the reduction step before filtering with g. This comes out of the composition of transducers naturally as a transducer inserts its transformation before the reducing function it accepts as an argument. Transducers can be called with transduce or transduce into a collection with into. """ class Missing(object): """Only for 'is' comparison to simplify arity testing. This is because None is a legal argument differing from 'Not supplied.'""" pass class Reduced(object): """Sentinel wrapper from which terminal value can be retrieved. If received by transducers.reduce, will signal early termination.""" def __init__(self, val): self.val = val def ensure_reduced(x): return x if isinstance(x, Reduced) else Reduced(x) def unreduced(x): return x.val if isinstance(x, Reduced) else x def reduce(function, iterable, initializer=Missing): """ For loop impl of reduce in Python that honors sentinal wrapper Reduced and uses it to signal early termination. """ if initializer is Missing: accum_value = function() # 0 arity initializer. else: accum_value = initializer for x in iterable: accum_value = function(accum_value, x) if isinstance(accum_value, Reduced): # <-- here's where we can terminate early. return accum_value.val return accum_value def compose(*fns): """Compose functions using reduce on splat. compose(f, g) reads 'f composed with g', or f(g(x)) Note: order of inner function application with transducers is inverted from the composition of the transducers. """ return functools.reduce(lambda f,g: lambda x: f(g(x)), fns) def transduce(xform, f, start, coll=Missing): """Return the results of calling transduce on the reducing function, can compose transducers using compose defined above. """ if coll is Missing: return transduce(xform, f, f(), start) reducer = xform(f) ret = reduce(reducer, coll, start) return reducer(ret) # completing step moved to here # Transducers def map(f): """Transducer version of map, returns f(item) with each reduction step.""" def _map_xducer(step): def _map_step(r=Missing, x=Missing): if r is Missing: return step() return step(r) if x is Missing else step(r, f(x)) return _map_step return _map_xducer def filter(pred): """Transducer version of filter.""" def _filter_xducer(step): def _filter_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) return step(r, x) if pred(x) else r return _filter_step return _filter_xducer def cat(step): """Cat transducers (will cat items from nested lists, e.g.).""" def _cat_step(r=Missing, x=Missing): if r is Missing: return step() return step(r) if x is Missing else functools.reduce(step, x, r) return _cat_step def mapcat(f): """Mapcat transducer - maps to a collection then cats item into one less level of nesting.""" return compose(map(f), cat) def take(n): """Takes n values from a collection.""" def _take_xducer(step): outer_vars = {"counter": n} def _take_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) n = outer_vars["counter"] outer_vars["counter"] -= 1 r = step(r, x) if n > 0 else r return ensure_reduced(r) if outer_vars["counter"] <= 0 else r return _take_step return _take_xducer def take_while(pred): """Takes while a condition is true. Note that take_while will take the first input that tests false, so be mindful of mutable input sources.""" def _take_while_xducer(step): def _take_while_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) return step(r, x) if pred(x) else Reduced(r) return _take_while_step return _take_while_xducer def drop(n): """Drops n items from beginning of input sequence.""" def _drop_xducer(step): outer = {"count": 0} def _drop_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) if outer["count"] < n: outer["count"] += 1 return r else: return step(r, x) return _drop_step return _drop_xducer def drop_while(pred): """Drops values so long as a condition is true.""" def _drop_while_xducer(step): outer = {"trigger": False} def _drop_while_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) if outer["trigger"]: return step(r, x) elif not pred(x): outer["trigger"] = True return step(r, x) return r return _drop_while_step return _drop_while_xducer def take_nth(n): """Takes every nth item from input values.""" def _take_nth_xducer(step): outer = {"idx": 0} def _take_nth_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) if outer["idx"] % n: outer["idx"] += 1 return r else: outer["idx"] += 1 return step(r, x) return _take_nth_step return _take_nth_xducer def replace(smap): """Replaces keys in smap with corresponding values.""" def _replace_xducer(step): def _replace_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) if x in smap: return step(r, smap[x]) else: return step(r, x) return _replace_step return _replace_xducer def keep(pred): """Keep pred items for which pred does not return None.""" def _keep_xducer(step): def _keep_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) res = pred(x) return step(r, res) if res is not None else r return _keep_step return _keep_xducer def remove(pred): """Remove anything that satisfies pred.""" def _remove_xducer(step): def _remove_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) return step(r, x) if not pred(x) else r return _remove_step return _remove_xducer def keep_indexed(f): """Keep values where f does not return None. f for keep indexed is a function that takes both index and value as inputs.""" def _keep_indexed_xducer(step): outer = {"idx": 0} def _keep_indexed_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) res = f(outer["idx"], x) outer["idx"] += 1 return step(r, res) if res is not None else r return _keep_indexed_step return _keep_indexed_xducer def dedupe(step): """Removes duplicatees that occur in order. Accepts first inputs through and drops subsequent duplicates.""" outer = {} def _dedupe_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) if "prev" not in outer: outer["prev"] = x return step(r, x) elif x != outer["prev"]: outer["prev"] = x return step(r, x) else: return r return _dedupe_step def partition_by(pred): """Split inputs into lists by starting a new list each time the predicate passed in evaluates to a different condition (true/false) than what holds for the present list.""" def _partition_by_xducer(step): outer = {"last": Missing, "temp": []} def _partition_by_step(r=Missing, x=Missing): if r is Missing: return step() # arity 1 - called on completion. if x is Missing: if not outer["temp"]: return r _temp = outer["temp"][:] del outer["temp"][:] _r = unreduced(step(r, _temp)) return step(_r) # arity 2 - normal step. past_val = outer["last"] present_val = pred(x) outer["last"] = present_val if past_val is Missing or present_val == past_val: outer["temp"].append(x) return r else: _temp = outer["temp"][:] del outer["temp"][:] ret = step(r, _temp) if not isinstance(ret, Reduced): outer["temp"].append(x) return ret return _partition_by_step return _partition_by_xducer def partition_all(n): """Splits inputs into lists of size n.""" def _partition_all_xducer(step): outer = {"temp": []} def _partition_all_step(r=Missing, x=Missing): if r is Missing: return step() # arity 1: called on completion. if x is Missing: if not outer["temp"]: return r _temp = outer["temp"][:] del outer["temp"][:] _r = unreduced(step(r, _temp)) return step(_r) # arity 2: called w/each reduction step. outer["temp"].append(x) if len(outer["temp"]) == n: _temp = outer["temp"][:] del outer["temp"][:] return step(r, _temp) return r return _partition_all_step return _partition_all_xducer def random_sample(prob): """Has prob probability of returning each input it receives.""" def _random_sample_xducer(step): def _random_sample_step(r=Missing, x=Missing): if r is Missing: return step() if x is Missing: return step(r) return step(r, x) if random() < prob else r return _random_sample_step return _random_sample_xducer def append(r=Missing, x=Missing): """Appender used by into. Will work with lists, deques, or anything with an appender.""" if r is Missing: return [] if x is Missing: return r r.append(x) return r def into(target, xducer, coll): """Transduces items from coll into target. :TODO: Write improved dispatch for collections?""" return transduce(xducer, append, target, coll) def eduction(xf, coll): """Return a generator with transform applied. Not implemented.""" raise NotImplementedError
'use strict'; /* Filters */ //angular.module('checkSysFilters', []) // .filter('underGrade', function(grade) { // return function(inputs) { // return inputs.filter(function(e) { // return e.id.length <= newValue * 2 + 1; } // ); // } // }); ///////////////////////////////////////// //angular.module('phonecatFilters', []).filter('checkmark', function() { // return function(input) { // return input ? '\u2713' : '\u2718'; // }; //});
import React, { Component } from 'react'; import { Provider } from 'react-redux'; import { PersistGate } from 'redux-persist/integration/react'; import store, { persistor } from '../src/store/index'; import AppRouter from './router'; import LoadingView from './base_components/LoadingView'; export default class App extends Component { render() { return ( <Provider store={store}> <PersistGate loading={<LoadingView />} persistor={persistor}> <AppRouter /> </PersistGate> </Provider> ); } }
/** * Copyright 2018 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; module.exports = function(context) { return { CallExpression(node) { if (/test-/.test(context.getFilename())) { return; } const {callee} = node; if (callee.type !== 'MemberExpression') { return; } const {property} = callee; if (property.type !== 'Identifier' || property.name !== 'vsyncFor') { return; } context.report(node, [ 'VSync is now a privileged service.', 'You likely want to use the `BaseElement` methods' + ' `measureElement`, `mutateElement`, or `runElement`.', 'In the worst case use the same methods on `Resources`.', ].join('\n\t')); }, }; };
const eye = x => x; export default { eye, };
# coding=utf-8 ''' 作者:Jairus Chan 程序:多项式曲线拟合算法 ''' import matplotlib.pyplot as plt import math import numpy import random #阶数为9阶 order=9 #进行曲线拟合 def getMatA(xa): matA=[] for i in range(0,order+1): matA1=[] for j in range(0,order+1): tx=0.0 for k in range(0,len(xa)): dx=1.0 for l in range(0,j+i): dx=dx*xa[k] tx+=dx matA1.append(tx) matA.append(matA1) matA=numpy.array(matA) return matA def getMatB(xa,ya): matB=[] for i in range(0,order+1): ty=0.0 for k in range(0,len(xa)): dy=1.0 for l in range(0,i): dy=dy*xa[k] ty+=ya[k]*dy matB.append(ty) matB=numpy.array(matB) return matB def getMatAA(xa, ya): matAA=numpy.linalg.solve(getMatA(xa),getMatB(xa, ya)) return matAA #设置阶数(默认为9 def setOrder(newOrder): order = newOrder #获取拟合后的新序列 def getFitYValues(xValues, yValues, xNewValues): matAA_get = getMatAA(xValues, yValues) yya=[] for i in range(0,len(xNewValues)): yy=0.0 for j in range(0,order+1): dy=1.0 for k in range(0,j): dy*=xNewValues[i] dy*=matAA_get[j] yy+=dy yya.append(yy) return yya #画出拟合后的曲线 #print(matAA) if __name__ == "__main__": fig = plt.figure() ax = fig.add_subplot(111) #生成曲线上的各个点 x = numpy.arange(-1,1,0.02) y = [((a*a-1)*(a*a-1)*(a*a-1)+0.5)*numpy.sin(a*2) for a in x] #ax.plot(x,y,color='r',linestyle='-',marker='') #,label="(a*a-1)*(a*a-1)*(a*a-1)+0.5" #生成的曲线上的各个点偏移一下,并放入到xa,ya中去 i=0 xa=[] ya=[] for xx in x: yy=y[i] d=float(random.randint(60,140))/100 #ax.plot([xx*d],[yy*d],color='m',linestyle='',marker='.') i+=1 xa.append(xx*d) ya.append(yy*d) '''for i in range(0,5): xx=float(random.randint(-100,100))/100 yy=float(random.randint(-60,60))/100 xa.append(xx) ya.append(yy)''' ax.plot(xa,ya,color='m',linestyle='',marker='.') matAA_n = getMatAA(xa,ya) print len(matAA_n) xxa= numpy.arange(-1,1.2,0.01) yya= getFitYValues(xa, ya, xxa) ax.plot(xxa,yya,color='g',linestyle='-',marker='') ax.legend() plt.show()
/* Copyright 2019 Nikita Stepochkin Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) { if (changeInfo.url) { chrome.tabs.executeScript(tab.id, {file: "reloadContentScript.js"}); } });
# # python_grabber # # Authors: # Andrea Schiavinato <[email protected]> # # Copyright (C) 2019 Andrea Schiavinato # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # from gui.MainWindow import * root = Tk() my_gui = MainWindow(root) root.mainloop()
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Buy = mongoose.model('Buy'), _ = require('lodash'); /** * Get the error message from error object */ var getErrorMessage = function(err) { var message = ''; if (err.code) { switch (err.code) { case 11000: case 11001: message = 'Buy already exists'; break; default: message = 'Something went wrong'; } } else { for (var errName in err.errors) { if (err.errors[errName].message) message = err.errors[errName].message; } } return message; }; /** * Create a buy */ exports.create = function(req, res) { var buy = new Buy(req.body); buy.user = req.user; buy.save(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(buy); } }); }; /** * Show the current buy */ exports.read = function(req, res) { res.jsonp(req.buy); }; /** * Update a buy */ exports.update = function(req, res) { var buy = req.buy; buy = _.extend(buy, req.body); buy.save(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(buy); } }); }; /** * Delete an buy */ exports.delete = function(req, res) { var buy = req.buy; buy.remove(function(err) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(buy); } }); }; /** * List of Buys */ exports.list = function(req, res) { Buy.find().sort('-created').populate('user', 'displayName').exec(function(err, buys) { if (err) { return res.send(400, { message: getErrorMessage(err) }); } else { res.jsonp(buys); } }); }; /** * Buy middleware */ exports.buyByID = function(req, res, next, id) { Buy.findById(id).populate('user', 'displayName').exec(function(err, buy) { if (err) return next(err); if (!buy) return next(new Error('Failed to load buy ' + id)); req.buy = buy; next(); }); }; /** * Buy authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.buy.user.id !== req.user.id) { return res.send(403, { message: 'User is not authorized' }); } next(); };
import pathlib import pkg_resources from mopidy import config, ext __version__ = pkg_resources.get_distribution("Mopidy-MPD").version class Extension(ext.Extension): dist_name = "Mopidy-MPD" ext_name = "mpd" version = __version__ def get_default_config(self): return config.read(pathlib.Path(__file__).parent / "ext.conf") def get_config_schema(self): schema = super().get_config_schema() schema["hostname"] = config.Hostname() schema["port"] = config.Port(optional=True) schema["password"] = config.Secret(optional=True) schema["filemode"] = config.String(optional=True) schema["max_connections"] = config.Integer(minimum=1) schema["connection_timeout"] = config.Integer(minimum=1) schema["zeroconf"] = config.String(optional=True) schema["command_blacklist"] = config.List(optional=True) schema["default_playlist_scheme"] = config.String() return schema def setup(self, registry): from .actor import MpdFrontend registry.add("frontend", MpdFrontend)
"""Generates a weekly bullet-point list of all the work done by ASF's Tools Team""" from importlib.metadata import PackageNotFoundError, version from bullets.generate import generate_bullets try: __version__ = version(__name__) except PackageNotFoundError: print(f'{__name__} package is not installed!\n' f'Install in editable/develop mode via (from the top of this repo):\n' f' python -m pip install -e .[develop]\n' f'Or, to just get the version number use:\n' f' python setup.py --version') __all__ = [ '__version__', 'generate_bullets', ]
import { createStyleSystem, get as getConfig } from '@wp-g2/create-styles'; import { config, darkHighContrastModeConfig, darkModeConfig, highContrastModeConfig, } from './theme'; const systemConfig = { baseStyles: { MozOsxFontSmoothing: 'grayscale', WebkitFontSmoothing: 'antialiased', fontFamily: getConfig('fontFamily'), fontSize: getConfig('fontSize'), margin: 0, }, config, darkModeConfig, highContrastModeConfig, darkHighContrastModeConfig, }; export const { ThemeProvider, compiler, core, createCoreElement, createToken, get, styled, } = createStyleSystem(systemConfig);
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import isEmpty from 'lodash/isEmpty'; import { Col, CardTitle, CardBody, EmptyStateAction, EmptyStateInfo, Button, Card, CardHeading, DropdownKebab, MenuItem, FieldLevelHelp, MessageDialog, } from 'patternfly-react'; import './DashPluginCardView.css'; import BrainImg from '../../../../assets/img/empty-brain-xs.png'; import PluginPointer from '../../../../assets/img/brainy_welcome-pointer.png'; import RelativeDate from '../../../RelativeDate/RelativeDate'; const DashGitHubEmptyState = () => ( <Col xs={12}> <Card> <CardTitle> My Plugins </CardTitle> <CardBody className="card-body-empty"> <h1 className="card-body-header-text">You have no plugins in the ChRIS store</h1> <h2 className="card-body-subhead">Lets fix that!</h2> <div className="card-body-content-parent"> <div> <img src={PluginPointer} alt="Click Add Plugin" /> </div> <div className="card-body-content-child-right"> <p> Create a new listing for your plugin in the ChRIS store by clicking &#34;Add Plugin&#34; below. </p> <Button bsStyle="primary" bsSize="large" href="/create"> Add Plugin </Button> </div> </div> </CardBody> </Card> </Col>); const DashApplicationType = (type) => { if (type === 'ds') { return (<React.Fragment><span className="fa fa-database" /> Data System</React.Fragment>); } return (<React.Fragment><span className="fa fa-file" /> File System</React.Fragment>); }; class DashPluginCardView extends Component { constructor(props) { super(props); this.state = { showConfirmation: false, pluginToDelete: null, }; const methods = [ 'deletePlugin', 'secondaryAction', 'showModal', ]; methods.forEach((method) => { this[method] = this[method].bind(this); }); } deletePlugin() { const { onDelete } = this.props; const { pluginToDelete } = this.state; onDelete(pluginToDelete.id); this.setState({ showConfirmation: false }); } secondaryAction() { this.setState({ showConfirmation: false }); } showModal(plugin) { this.setState({ showConfirmation: true, pluginToDelete: plugin, }); } render() { let pluginCardBody; const { plugins } = this.props; const { pluginToDelete, showConfirmation } = this.state; const showEmptyState = isEmpty(plugins); const primaryContent = <p className="lead">Are you sure?</p>; const secondaryContent = ( <p> Plugin <b>{pluginToDelete ? pluginToDelete.name : null}</b> will be permanently deleted </p>); const addNewPlugin = ( <Col xs={12} sm={6} md={4} key="addNewPlugin"> <Card> <CardBody className="card-view-add-plugin"> <div> <img width="77" height="61" src={BrainImg} alt="Add new plugin" /> </div> <EmptyStateInfo> Click below to add a new ChRIS plugin </EmptyStateInfo> <EmptyStateAction> <Button bsStyle="primary" bsSize="large" href="/create"> Add Plugin </Button> </EmptyStateAction> </CardBody> </Card> </Col>); if (plugins) { pluginCardBody = plugins.map((plugin) => { const creationDate = new RelativeDate(plugin.creation_date); const applicationType = new DashApplicationType(plugin.type); return ( <Col xs={12} sm={6} md={4} key={plugin.name}> <Card> <CardHeading> <CardTitle> <DropdownKebab id="myKebab" pullRight className="card-view-kebob"> <MenuItem eventKey={plugin} onSelect={this.showModal}> Delete </MenuItem> </DropdownKebab> <Link to={`/plugin/${plugin.id}`} href={`/plugin/${plugin.id}`} >{plugin.name} </Link> <div className="card-view-tag-title"> <FieldLevelHelp content={ <div>{plugin.description}</div>} /> </div> </CardTitle> </CardHeading> <CardBody> <div className="card-view-app-type"> {applicationType} </div> <div> <div className="card-view-plugin-tag"> {`Version ${plugin.version}`} </div> </div> <div> <div className="card-view-plugin-tag"> {creationDate.isValid() && `Created ${creationDate.format()}` } </div> </div> <div> <div className="card-view-plugin-tag"> {`${plugin.license} license`} </div> </div> </CardBody> </Card> </Col> ); }); pluginCardBody.push(addNewPlugin); } return ( showEmptyState ? <DashGitHubEmptyState /> : <React.Fragment> <div className="card-view-row"> {pluginCardBody} <MessageDialog show={showConfirmation} onHide={this.secondaryAction} primaryAction={this.deletePlugin} secondaryAction={this.secondaryAction} primaryActionButtonContent="Delete" secondaryActionButtonContent="Cancel" primaryActionButtonBsStyle="danger" title="Plugin Delete Confirmation" primaryContent={primaryContent} secondaryContent={secondaryContent} accessibleName="deleteConfirmationDialog" accessibleDescription="deleteConfirmationDialogContent" /> </div> </React.Fragment> ); } } DashPluginCardView.propTypes = { plugins: PropTypes.arrayOf(PropTypes.object), onDelete: PropTypes.func.isRequired, }; DashPluginCardView.defaultProps = { plugins: [], }; export default DashPluginCardView;
# coding=utf-8 # Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import hashlib import logging import os import posixpath from collections import namedtuple from contextlib import contextmanager from twitter.common.collections import OrderedSet from pants.base.build_environment import get_buildroot from pants.base.exceptions import TaskError from pants.base.hash_utils import hash_file from pants.fs.archive import archiver as create_archiver from pants.net.http.fetcher import Fetcher from pants.subsystem.subsystem import Subsystem from pants.util.contextutil import temporary_file from pants.util.dirutil import chmod_plus_x, safe_concurrent_creation, safe_open from pants.util.osutil import get_os_id _DEFAULT_PATH_BY_ID = { ('linux', 'x86_64'): ('linux', 'x86_64'), ('linux', 'amd64'): ('linux', 'x86_64'), ('linux', 'i386'): ('linux', 'i386'), ('linux', 'i686'): ('linux', 'i386'), ('darwin', '9'): ('mac', '10.5'), ('darwin', '10'): ('mac', '10.6'), ('darwin', '11'): ('mac', '10.7'), ('darwin', '12'): ('mac', '10.8'), ('darwin', '13'): ('mac', '10.9'), ('darwin', '14'): ('mac', '10.10'), ('darwin', '15'): ('mac', '10.11'), ('darwin', '16'): ('mac', '10.12'), ('darwin', '17'): ('mac', '10.13'), } logger = logging.getLogger(__name__) class BinaryUtil(object): """Wraps utility methods for finding binary executables. :API: public """ class Factory(Subsystem): """ :API: public """ # N.B. `BinaryUtil` sources all of its options from bootstrap options, so that # `BinaryUtil` instances can be created prior to `Subsystem` bootstrapping. So # this options scope is unused, but required to remain a `Subsystem`. options_scope = 'binaries' @classmethod def create(cls): """ :API: public """ # NB: create is a class method to ~force binary fetch location to be global. options = cls.global_instance().get_options() return BinaryUtil( options.binaries_baseurls, options.binaries_fetch_timeout_secs, options.pants_bootstrapdir, options.binaries_path_by_id ) class MissingMachineInfo(TaskError): """Indicates that pants was unable to map this machine's OS to a binary path prefix.""" pass class BinaryNotFound(TaskError): def __init__(self, binary, accumulated_errors): super(BinaryUtil.BinaryNotFound, self).__init__( 'Failed to fetch binary {binary} from any source: ({sources})' .format(binary=binary, sources=', '.join(accumulated_errors))) class NoBaseUrlsError(TaskError): """Indicates that no urls were specified in pants.ini.""" pass class BinaryFileSpec(namedtuple('BinaryFileSpec', ['filename', 'checksum', 'digest'])): def __new__(cls, filename, checksum=None, digest=hashlib.sha1()): return super(BinaryUtil.BinaryFileSpec, cls).__new__(cls, filename, checksum, digest) def _select_binary_base_path(self, supportdir, version, name, uname_func=None): """Calculate the base path. Exposed for associated unit tests. :param supportdir: the path used to make a path under --pants_bootstrapdir. :param version: the version number of the tool used to make a path under --pants-bootstrapdir. :param name: name of the binary to search for. (e.g 'protoc') :param uname_func: method to use to emulate os.uname() in testing :returns: Base path used to select the binary file. """ uname_func = uname_func or os.uname os_id = get_os_id(uname_func=uname_func) if not os_id: raise self.MissingMachineInfo('Pants has no binaries for {}'.format(' '.join(uname_func()))) try: middle_path = self._path_by_id[os_id] except KeyError: raise self.MissingMachineInfo('Unable to find binary {name} version {version}. ' 'Update --binaries-path-by-id to find binaries for {os_id!r}' .format(name=name, version=version, os_id=os_id)) return os.path.join(supportdir, *(middle_path + (version, name))) def __init__(self, baseurls, timeout_secs, bootstrapdir, path_by_id=None): """Creates a BinaryUtil with the given settings to define binary lookup behavior. This constructor is primarily used for testing. Production code will usually initialize an instance using the BinaryUtil.Factory.create() method. :param baseurls: URL prefixes which represent repositories of binaries. :type baseurls: list of string :param int timeout_secs: Timeout in seconds for url reads. :param string bootstrapdir: Directory to use for caching binaries. Uses this directory to search for binaries in, or download binaries to if needed. :param dict path_by_id: Additional mapping from (sysname, id) -> (os, arch) for tool directory naming """ self._baseurls = baseurls self._timeout_secs = timeout_secs self._pants_bootstrapdir = bootstrapdir self._path_by_id = _DEFAULT_PATH_BY_ID.copy() if path_by_id: self._path_by_id.update((tuple(k), tuple(v)) for k, v in path_by_id.items()) # TODO: Deprecate passing in an explicit supportdir? Seems like we should be able to # organize our binary hosting so that it's not needed. def select(self, supportdir, version, name, platform_dependent, archive_type): """Fetches a file, unpacking it if necessary.""" if archive_type is None: return self._select_file(supportdir, version, name, platform_dependent) archiver = create_archiver(archive_type) return self._select_archive(supportdir, version, name, platform_dependent, archiver) def _select_file(self, supportdir, version, name, platform_dependent): """Generates a path to request a file and fetches the file located at that path. :param string supportdir: The path the `name` binaries are stored under. :param string version: The version number of the binary to select. :param string name: The name of the file to fetch. :param bool platform_dependent: Whether the file content differs depending on the current platform. :raises: :class:`pants.binary_util.BinaryUtil.BinaryNotFound` if no file of the given version and name could be found for the current platform. """ binary_path = self._binary_path_to_fetch(supportdir, version, name, platform_dependent) return self._fetch_binary(name=name, binary_path=binary_path) def _select_archive(self, supportdir, version, name, platform_dependent, archiver): """Generates a path to fetch, fetches the archive file, and unpacks the archive. :param string supportdir: The path the `name` binaries are stored under. :param string version: The version number of the binary to select. :param string name: The name of the file to fetch. :param bool platform_dependent: Whether the file content differs depending on the current platform. :param archiver: The archiver object which provides the file extension and unpacks the archive. :type: :class:`pants.fs.archive.Archiver` :raises: :class:`pants.binary_util.BinaryUtil.BinaryNotFound` if no file of the given version and name could be found for the current platform. """ full_name = '{}.{}'.format(name, archiver.extension) downloaded_file = self._select_file(supportdir, version, full_name, platform_dependent) # Use filename without rightmost extension as the directory name. unpacked_dirname, _ = os.path.splitext(downloaded_file) if not os.path.exists(unpacked_dirname): archiver.extract(downloaded_file, unpacked_dirname) return unpacked_dirname def _binary_path_to_fetch(self, supportdir, version, name, platform_dependent): if platform_dependent: # TODO(John Sirois): finish doc of the path structure expected under base_path. return self._select_binary_base_path(supportdir, version, name) return os.path.join(supportdir, version, name) def select_binary(self, supportdir, version, name): return self._select_file( supportdir, version, name, platform_dependent=True) def select_script(self, supportdir, version, name): return self._select_file( supportdir, version, name, platform_dependent=False) @contextmanager def _select_binary_stream(self, name, binary_path, fetcher=None): """Select a binary located at a given path. :param string binary_path: The path to the binary to fetch. :param fetcher: Optional argument used only for testing, to 'pretend' to open urls. :returns: a 'stream' to download it from a support directory. The returned 'stream' is actually a lambda function which returns the files binary contents. :raises: :class:`pants.binary_util.BinaryUtil.BinaryNotFound` if no binary of the given version and name could be found for the current platform. """ if not self._baseurls: raise self.NoBaseUrlsError( 'No urls are defined for the --pants-support-baseurls option.') downloaded_successfully = False accumulated_errors = [] for baseurl in OrderedSet(self._baseurls): # De-dup URLS: we only want to try each URL once. url = posixpath.join(baseurl, binary_path) logger.info('Attempting to fetch {name} binary from: {url} ...'.format(name=name, url=url)) try: with temporary_file() as dest: fetcher = fetcher or Fetcher(get_buildroot()) fetcher.download(url, listener=Fetcher.ProgressListener(), path_or_fd=dest, timeout_secs=self._timeout_secs) logger.info('Fetched {name} binary from: {url} .'.format(name=name, url=url)) downloaded_successfully = True dest.seek(0) yield lambda: dest.read() break except (IOError, Fetcher.Error, ValueError) as e: accumulated_errors.append('Failed to fetch binary from {url}: {error}' .format(url=url, error=e)) if not downloaded_successfully: raise self.BinaryNotFound(binary_path, accumulated_errors) def _fetch_binary(self, name, binary_path): bootstrap_dir = os.path.realpath(os.path.expanduser(self._pants_bootstrapdir)) bootstrapped_binary_path = os.path.join(bootstrap_dir, binary_path) if not os.path.exists(bootstrapped_binary_path): with safe_concurrent_creation(bootstrapped_binary_path) as downloadpath: with self._select_binary_stream(name, binary_path) as stream: with safe_open(downloadpath, 'wb') as bootstrapped_binary: bootstrapped_binary.write(stream()) os.rename(downloadpath, bootstrapped_binary_path) chmod_plus_x(bootstrapped_binary_path) logger.debug('Selected {binary} binary bootstrapped to: {path}' .format(binary=name, path=bootstrapped_binary_path)) return bootstrapped_binary_path @staticmethod def _compare_file_checksums(filepath, checksum=None, digest=None): digest = digest or hashlib.sha1() if os.path.isfile(filepath) and checksum: return hash_file(filepath, digest=digest) == checksum return os.path.isfile(filepath) def is_bin_valid(self, basepath, binary_file_specs=()): """Check if this bin path is valid. :param string basepath: The absolute path where the binaries are stored under. :param BinaryFileSpec[] binary_file_specs: List of filenames and checksum for validation. """ if not os.path.isdir(basepath): return False for f in binary_file_specs: filepath = os.path.join(basepath, f.filename) if not self._compare_file_checksums(filepath, f.checksum, f.digest): return False return True
var MaterialRequestWiseListing = function () { var projectSiteId = $("#globalProjectSite").val(); if(typeof projectSiteId == 'undefined' || projectSiteId == ''){ projectSiteId = 0; } var handleOrders = function () { var grid = new Datatable(); grid.init({ src: $("#materialRequestWise"), onSuccess: function (grid) { // execute some code after table records loaded }, onError: function (grid) { // execute some code on network or other general error }, loadingMessage: 'Loading...', dataTable: { // here you can define a typical datatable settings from http://datatables.net/usage/options // Uncomment below line("dom" parameter) to fix the dropdown overflow issue in the datatable cells. The default datatable layout // setup uses scrollable div(table-scrollable) with overflow:auto to enable vertical scroll(see: assets/global/scripts/datatable.js). // So when dropdowns used the scrollable div should be removed. //"dom": "<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'<'table-group-actions pull-right'>>r>t<'row'<'col-md-8 col-sm-12'pli><'col-md-4 col-sm-12'>>", "lengthMenu": [ [20, 100, 150], [20, 100, 150] // change per page values here ], "pageLength": 20, // default record count per page "ajax": { "url": "/purchase/material-request/material-requestWise-listing?site_id="+projectSiteId+"&_token="+$("input[name='_token']").val() }, "order": [ [1, "asc"] ] // set first column as a default sort by asc } }); // handle group actionsubmit button click grid.getTableWrapper().on('click', '.table-group-action-submit', function (e) { e.preventDefault(); var action = $(".table-group-action-input", grid.getTableWrapper()); if (action.val() != "" && grid.getSelectedRowsCount() > 0) { grid.setAjaxParam("customActionType", "group_action"); grid.setAjaxParam("customActionName", action.val()); grid.setAjaxParam("id", grid.getSelectedRows()); grid.getDataTable().ajax.reload(); grid.clearAjaxParams(); } else if (action.val() == "") { alert({ type: 'danger', icon: 'warning', message: 'Please select an action', container: grid.getTableWrapper(), place: 'prepend' }); } else if (grid.getSelectedRowsCount() === 0) { alert({ type: 'danger', icon: 'warning', message: 'No record selected', container: grid.getTableWrapper(), place: 'prepend' }); } }); } return { //main function to initiate the module init: function () { handleOrders(); } }; }(); jQuery(document).ready(function() { MaterialRequestWiseListing.init(); });
/** * 全局配置文件 */ let baseURL; let imgUrl = '//elm.cangdu.org/img/'; if(process.env.NODE_ENV === 'development'){ baseURL = '//api.cangdu.org'; }else{ baseURL = '//api.cangdu.org'; } export default {imgUrl, baseURL}
__all__ = ('CommandProcessor', ) from ...backend.utils import WeakReferer from ...discord.events.handling_helpers import EventWaitforBase from ...discord.preconverters import preconvert_bool from ...discord.utils import USER_MENTION_RP from ...discord.events.handling_helpers import Router, compare_converted from .command_helpers import default_precheck, test_precheck, test_error_handler, test_name_rule, \ validate_category_or_command_name, get_prefix_parser, COMMAND_NAME_RP, test_unknown_command from .utils import raw_name_to_display from .context import CommandContext from .category import Category from .command import Command DEFAULT_CATEGORY_NAME = 'UNCATEGORIZED' class CommandProcessor(EventWaitforBase): """ Command processor. Attributes ---------- _category_name_rule : `None` or `FunctionType` Function to generate category display names. A category name rule should accept the following parameters: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ Should return the following ones: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ _command_name_rule : `None` or `FunctionType` Function to generate command display names. A command name rule should accept the following parameters: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ Should return the following ones: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ _default_category : ``Category`` The command processor's default category. _error_handlers : `None` or `list` of `async-function` Function to run when a command raises an exception. The following parameters are passed to each error handler: +-------------------+-----------------------+ | Name | Type | +===================+=======================+ | command_context | ``CommandContext`` | +-------------------+-----------------------+ | exception | `BaseException` | +-------------------+-----------------------+ Should return the following parameters: +-------------------+-----------+ | Name | Type | +===================+===========+ | handled | `bool` | +-------------------+-----------+ _mention_prefix_enabled : `bool` Whether mentioning the client at the start of a message counts as prefix. _precheck : `FunctionType` A function used to detect whether a message should be handled. The following parameters are passed to it: +-----------+---------------+ | Name | Type | +===========+===============+ | client | ``Client`` | +-----------+---------------+ | message | ``Message`` | +-----------+---------------+ Should return the following parameters: +-------------------+-----------+ | Name | Type | +===================+===========+ | should_process | `bool` | +-------------------+-----------+ _prefix_getter : `async-callable` Accepts the following parameters: +-----------+---------------+ | Name | Type | +===========+===============+ | message | ``Message`` | +-----------+---------------+ Returns the given values: +-----------+-------------------+ | Name | Type | +===========+===================+ | prefix | `None` or `str` | +-----------+-------------------+ _prefix_ignore_case : `bool` Whether casing in prefix is ignored. _prefix_parser : `async-callable` Parses the prefix down from a message's start. Accepts the following parameters: +-----------+---------------+ | Name | Type | +===========+===============+ | message | ``Message`` | +-----------+---------------+ Returns the given values: +-----------+-------------------+ | Name | Type | +===========+===================+ | prefix | `None` or `str` | +-----------+-------------------+ | end | `int` | +-----------+-------------------+ _prefix_raw : `str`, `tuple` of `str`, `callable` Raw prefix of the command processor. _self_reference : `None` or ``WeakReferer`` to ``CommandProcessor`` Reference to the command processor itself. _unknown_command : `None` or `FunctionType` Called when a command would be called, but not found. Accepts the following parameters: +---------------+---------------+ | Name | Type | +===============+===============+ | client | ``Client`` | +---------------+---------------+ | message | ``Message`` | +---------------+---------------+ | command_name | `str` | +---------------+---------------+ category_name_to_category : `dict` of (`str`, ``Category``) items Category name to category relation. categories : `set` of ``Category`` Categories registered to the command processor. command_name_to_command : `dict` of (`str`, ``Command``) items Command name to command relation. commands : `set` of ``Command`` The registered commands to the command processor. Notes ----- ``CommandProcessor`` supports weakreferencing. """ __slots__ = ('__weakref__', '_category_name_rule', '_command_name_rule', '_default_category', '_error_handlers', '_mention_prefix_enabled', '_precheck', '_prefix_getter', '_prefix_ignore_case', '_prefix_parser', '_prefix_raw', '_self_reference', 'category_name_to_category', '_unknown_command', 'categories', 'command_name_to_command', 'commands') __event_name__ = 'message_create' SUPPORTED_TYPES = (Command, ) def __new__(cls, prefix, *, precheck=None, mention_prefix_enabled=True, category_name_rule=None, command_name_rule=None, default_category_name=None, prefix_ignore_case=True): """ Creates a new command processor instance. Parameters ---------- prefix : `str`, `tuple` of `str`, `callable` Prefix of the command processor. Can be given as a normal `callable` or as an `async-callable` as well, which should accept `1` parameter: +-------------------+---------------+ | Name | Type | +===================+===============+ | message | ``Message`` | +-------------------+---------------+ And return the following value: +-------------------+---------------------------+ | Name | Type | +===================+===========================+ | prefix | `str`, `tuple` of `str` | +-------------------+---------------------------+ precheck : `bool`, Optional (Keyword only) A function used to detect whether a message should be handled. mention_prefix_enabled : `bool`, Optional (Keyword only) Whether mentioning the client at the start of a message counts as prefix. Defaults to `True`. category_name_rule : `None` or `function`, Optional (Keyword only) Function to generate category display names. Defaults to `None`. command_name_rule : `None` or `function`, Optional (Keyword only) Function to generate command display names. Defaults to `None`. default_category_name : `None` or `str`, Optional (Keyword only) The command processor's default category's name. Defaults to `None`. prefix_ignore_case : `bool` Whether the prefix's case should be ignored. Raises ------ TypeError - If `precheck` accepts bad amount of parameters. - If `precheck` is async. - If `mention_prefix_enabled` was not given as a `bool` instance. - If `category_name_rule` is not `None` nor `function`. - If `category_name_rule` is `async-function`. - If `category_name_rule` accepts bad amount of parameters. - If `category_name_rule` raises exception when `str` is passed to it. - If `category_name_rule` not returns `str`, when passing `str` to it. - If `command_name_rule` is not `None` nor `function`. - If `command_name_rule` is `async-function`. - If `command_name_rule` accepts bad amount of parameters. - If `command_name_rule` raises exception when `str` is passed to it. - If `command_name_rule` not returns `str`, when `str` is passed to it. - If `default_category_name` was not given neither as `None` nor as `str` instance. - If `prefix_ignore_case` was not given as `bool` instance. - Prefix's type is incorrect. - Prefix is a callable but accepts bad amount of parameters. ValueError - If `default_category_name`'s length is out of range [1:128]. """ if (category_name_rule is not None): test_name_rule(category_name_rule, 'category_name_rule') if (command_name_rule is not None): test_name_rule(command_name_rule, 'command_name_rule') if default_category_name is None: default_category_name = DEFAULT_CATEGORY_NAME else: default_category_name = validate_category_or_command_name(default_category_name) default_category = Category(default_category_name) if precheck is None: precheck = default_precheck else: test_precheck(precheck) mention_prefix_enabled = preconvert_bool(mention_prefix_enabled, 'mention_prefix_enabled') prefix_ignore_case = preconvert_bool(prefix_ignore_case, 'prefix_ignore_case') prefix_parser, prefix_getter = get_prefix_parser(prefix, prefix_ignore_case) self = object.__new__(cls) self._self_reference = None self._precheck = precheck self._error_handlers = None self._mention_prefix_enabled = mention_prefix_enabled self._category_name_rule = category_name_rule # Assign it later, exception may occur self._self_reference = WeakReferer(self) self._prefix_ignore_case = prefix_ignore_case self._prefix_parser = prefix_parser self._prefix_raw = prefix self._prefix_getter = prefix_getter self._default_category = default_category self._command_name_rule = command_name_rule self._category_name_rule = category_name_rule self.command_name_to_command = {} self.category_name_to_category = {} self.commands = set() self.categories = set() self._unknown_command = None self._self_reference = WeakReferer(self) default_category.set_command_processor(self) return self async def __call__(self, client, message): """ Calls the waitfors of the command processor, processing the given `message`'s content, and calls a command if found, or an other specified event. Details under ``CommandProcessor``'s own docs. This method is a coroutine. Parameters --------- client : ``Client`` The client, who received the message. message : ``Message`` The received message. """ await self.call_waitfors(client, message) if not self._precheck(client, message): return prefix, end = await self._prefix_parser(message) if (prefix is None): if not self._mention_prefix_enabled: return user_mentions = message.user_mentions if (user_mentions is None) or (client not in user_mentions): return content = message.content if content is None: return parsed = USER_MENTION_RP.match(content) if (parsed is None) or (int(parsed.group(1)) != client.id): return end = parsed.end() content = message.content if content is None: return parsed = COMMAND_NAME_RP.match(content, end) if (parsed is None): return command_name = parsed.group(1) end = parsed.end() command_name = raw_name_to_display(command_name) try: command = self.command_name_to_command[command_name] except KeyError: pass else: content = content[end:] if prefix is None: prefix = await self._prefix_getter(message) context = CommandContext(client, message, prefix, content, command) if await context.invoke(): return unknown_command = self._unknown_command if (unknown_command is not None): try: await unknown_command(client, message, command_name) except BaseException as err: await client.events.error(client, f'{self!r}.__call__', err) def error(self, error_handler): """ Adds na error handler to the command processor. Parameters ---------- error_handler : `async-callable` The error handler to add. The following parameters are passed to each error handler: +-------------------+-----------------------+ | Name | Type | +===================+=======================+ | command_context | ``CommandContext`` | +-------------------+-----------------------+ | exception | `BaseException` | +-------------------+-----------------------+ Should return the following parameters: +-------------------+-----------+ | Name | Type | +===================+===========+ | handled | `bool` | +-------------------+-----------+ Returns ------- error_handler : `async-callable` Raises ------ TypeError - If `error_handler` accepts bad amount of parameters. - If `error_handler` is not async. """ test_error_handler(error_handler) error_handlers = self._error_handlers if error_handlers is None: error_handlers = self._error_handlers = [] error_handlers.append(error_handler) return error_handler def update_prefix(self, *, prefix=None, prefix_ignore_case=None): """ Updates the prefix of he Returns ------- prefix : `str`, `tuple` of `str`, `callable`, Optional (Keyword only) Prefix of the command processor. Can be given as a normal `callable` or as an `async-callable` as well, which should accept `1` parameter: +-------------------+---------------+ | Name | Type | +===================+===============+ | message | ``Message`` | +-------------------+---------------+ And return the following value: +-------------------+---------------------------+ | Name | Type | +===================+===========================+ | prefix | `str`, `tuple` of `str` | +-------------------+---------------------------+ prefix_ignore_case : `bool`, Optional (Keyword only) Whether the prefix's case should be ignored. Raises ------ TypeError - If `prefix_ignore_case` was not given as `bool` instance. - Prefix's type is incorrect. - Prefix is a callable but accepts bad amount of parameters. """ if (prefix is None) and (prefix_ignore_case is None): return if prefix is None: prefix = self._prefix_raw if prefix_ignore_case is None: prefix_ignore_case = self._prefix_ignore_case prefix_ignore_case = preconvert_bool(prefix_ignore_case, 'prefix_ignore_case') prefix_parser, prefix_getter = get_prefix_parser(prefix, prefix_ignore_case) self._prefix_ignore_case = prefix_ignore_case self._prefix_parser = prefix_parser self._prefix_raw = prefix self._prefix_getter = prefix_getter async def get_prefix(self, message): """ Gets prefix relating to the given message. This method is a coroutine. Parameters ---------- message : ``Message`` The respective message. Returns ------- prefix : `None` or `str` """ return await self._prefix_getter(message) def get_category(self, category_name): """ Returns the category for the given name. If the name is passed as `None`, then will return the default category of the command processer. Returns `None` if there is no category with the given name. Parameters --------- category_name : `None` or `str` The category's name. Returns ------- category : `None`, ``Category`` Raises ------ TypeError If `category_name` was not given neither as `None` or `str` instance. """ if category_name is None: return self._default_category if not isinstance(category_name, str): raise TypeError(f'`category_name` can be given as `None` or as `str` instance, got ' f'{category_name.__class__.__name__}.') category_name = raw_name_to_display(category_name) return self.category_name_to_category.get(category_name, None) def get_default_category(self): """ Returns the command processor's default category. Returns ------- category : ``Category`` """ return self._default_category def create_category(self, category_name, *, checks=None, description=None): """ Creates a category with the given parameters. Parameters ---------- name : `str` The name of the category. checks : `None`, ``CheckBase`` instance or `list` of ``CheckBase`` instances, Optional (Keyword only) Checks to define in which circumstances a command should be called. description : `Any`, Optional (Keyword only) Optional description for the category. Defaults to `None`. Returns ------- category : ``Category`` Raises ------ TypeError If `checks` was not given neither as `None`, ``CheckBase`` instance or as `list` of ``CheckBase`` instances. ValueError If a category already exists with the given name. """ category_name = validate_category_or_command_name(category_name) if category_name in self.category_name_to_category: raise ValueError(f'There is already a category added with that name: `{category_name!r}`') category = Category(category_name, checks=checks, description=description) category.set_command_processor(self) return category def delete_category(self, category): """ Deletes the given category form the command processor. Parameters ---------- category : ``Category``, `str` The category or the category's name to remove. Raises ------ TypeError If `category` was not given neither as ``Category`` nor as `str` instance. ValueError - Default category cannot be deleted. - If te given category is not the same as the owned one with it's name. """ if isinstance(category, Category): category_name = category.name elif isinstance(category, str): category_name = validate_category_or_command_name(category) category = None else: raise TypeError(f'`category` can be given either as `{Category.__name__}` or as `str` instance, ' f'got {category.__class__.__name__}.') try: owned_category = self.category_name_to_category[category_name] except KeyError: return if (category is not None) and (category is not owned_category): raise ValueError(f'The given category is not the same as the owned owned one with it\'s name: got ' f'{category!r}; owning: {owned_category!r}.') owned_category.unlink() def _add_command(self, command): """ Adds the given command to the command processor. Parameters --------- command : ``Command`` The command to add. Raises ------ RuntimeError - The command is bound to an other command processor. - The command would only partially overwrite """ command_processor = command.get_command_processor() if (command_processor is not None) and (command_processor is not self): raise RuntimeError(f'{Command.__name__}: {command!r} is bound to an other command processor.') category = command.get_category() if category is None: # Bind the command to category. category_hint = command._category_hint if category_hint is None: category = self._default_category else: category = self.get_category(category_hint) if (category is None): category = self.create_category(category_hint) command.set_category(category) def _remove_command(self, command): """ Removes the given command from the command processor. Parameters ---------- command : ``Command`` The command to remove. Raises ------ RuntimeError The command is bound to an other command processor. """ if __debug__: if not isinstance(command, Command): raise AssertionError(f'`command` can be given as `{Command.__name__}` instance, got ' f'{command.__class__.__name__}.') command_processor = command.get_command_processor() if (command_processor is not None) and (command_processor is not self): raise RuntimeError(f'{Command.__name__}: {command!r} is bound to an other command processor.') command.unlink_category() def _add_category(self, category): """ Adds the given category to the command processor. Parameters ---------- category : ``Category`` The category to add. Raises ------ RuntimeError The category is bound to an other category processor. """ command_processor = category.get_command_processor() if (command_processor is not None) and (command_processor is not self): raise RuntimeError(f'{Category.__name__}: {command_processor!r} is bound to an other command processor.') category.set_command_processor(category) def _remove_category(self, category): """ Removes the given category to the command processor. Parameters ---------- category : ``Category`` The category to remove. Raises ------ RuntimeError The category is bound to an other category processor. """ command_processor = category.get_command_processor() if (command_processor is not None) and (command_processor is not self): raise RuntimeError(f'{Category.__name__}: {command_processor!r} is bound to an other command processor.') category.unlink() @property def category_name_rule(self): """ Get-set-del property to modify the command processor's. A category name rule is `None` or a `FunctionType` accepting the following parameters: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ Should return the following ones: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ """ return self._category_name_rule @category_name_rule.setter def category_name_rule(self, category_name_rule): if self._category_name_rule is category_name_rule: return if (category_name_rule is None): for category in self.category_name_to_category.values(): category.display_name = category.name else: test_name_rule(category_name_rule, 'category_name_rule') for category in self.category_name_to_category.values(): category.display_name = category_name_rule(category.name) self._category_name_rule = category_name_rule @category_name_rule.deleter def category_name_rule(self): if self._category_name_rule is None: return for category in self.category_name_to_category.values(): category.display_name = category.name self._category_name_rule = None @property def command_name_rule(self): """ Get-set-del property to modify the command processor's. A command name rule is `None` or a `FunctionType` accepting the following parameters: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ Should return the following ones: +-------+-------------------+ | Name | Type | +=======+===================+ | name | `str` | +-------+-------------------+ """ return self._command_name_rule @command_name_rule.setter def command_name_rule(self, command_name_rule): if self._command_name_rule is command_name_rule: return if command_name_rule is None: for command in self.commands: command.display_name = command.name else: test_name_rule(command_name_rule, 'command_name_rule') for command in self.commands: command.display_name = command_name_rule(command.name) self._command_name_rule = command_name_rule @command_name_rule.deleter def command_name_rule(self): if self._command_name_rule is None: return for command in self.commands: command.display_name = command.name def precheck(self, precheck): """ Changes the command processor's precheck. Parameters ---------- precheck : `None` or `callable` Can be either `None` or `non-async` function accepting following parameters are passed to it: +-----------+---------------+ | Name | Type | +===========+===============+ | client | ``Client`` | +-----------+---------------+ | message | ``Message`` | +-----------+---------------+ Should return the following parameters: +-------------------+-----------+ | Name | Type | +===================+===========+ | should_process | `bool` | +-------------------+-----------+ Returns ------- precheck : `None` or `callable` """ if precheck is None: precheck_to_set = default_precheck else: test_precheck(precheck) precheck_to_set = precheck self._precheck = precheck_to_set return precheck def create_event(self, command, name=None, description=None, aliases=None, category=None, checks=None, error_handlers=None, separator=None, assigner=None, hidden=None, hidden_if_checks_fail=None): """ Adds a command to the command processor. Parameters ---------- command : ``Command``, ``Router``, `None`, `async-callable` Async callable to add as a command. name : `None` or `str` The command's name. name : `None`, `str` or `tuple` of (`None`, `Ellipsis`, `str`) The name to be used instead of the passed `command`'s. description : `None`, `Any` or `tuple` of (`None`, `Ellipsis`, `Any`), Optional Description added to the command. If no description is provided, then it will check the commands's `.__doc__` attribute for it. If the description is a string instance, then it will be normalized with the ``normalize_description`` function. If it ends up as an empty string, then `None` will be set as the description. aliases : `None`, `str`, `list` of `str` or `tuple` of (`None, `Ellipsis`, `str`, `list` of `str`), Optional The aliases of the command. category : `None`, ``Category``, `str` or `tuple` of (`None`, `Ellipsis`, ``Category``, `str`), Optional The category of the command. Can be given as the category itself, or as a category's name. If given as `None`, then the command will go under the command processer's default category. checks : `None`, ``CommandCheckWrapper``, ``CheckBase``, `list` of ``CommandCheckWrapper``, ``CheckBase`` \ instances or `tuple` of (`None`, `Ellipsis`, ``CommandCheckWrapper``, ``CheckBase`` or `list` of \ ``CommandCheckWrapper``, ``CheckBase``), Optional Checks to decide in which circumstances the command should be called. error_handlers : `None`, `async-callable`, `list` of `async-callable`, `tuple` of (`None`, `async-callable`, \ `list` of `async-callable`), Optional Error handlers for the command. separator : `None`, `str` or `tuple` (`str`, `str`), Optional The parameter separator of the command's parser. assigner : `None`, `str`, Optional Parameter assigner sign of the command's parser. hidden : `None`, `bool`, `tuple` (`None`, `Ellipsis`, `bool`), Optional Whether the command should be hidden from the help commands. hidden_if_checks_fail : `None`, `bool`, `tuple` (`None`, `Ellipsis`, `bool`), Optional Whether the command should be hidden from the help commands if any check fails. Returns ------- command : ``Command`` The added command instance. """ if isinstance(command, Command): pass elif isinstance(command, Router): command = command[0] else: command = Command(command, name, description, aliases, category, checks, error_handlers, separator, assigner, hidden, hidden_if_checks_fail) self._add_command(command) return command def create_event_from_class(self, klass): """ Breaks down the given class to it's class attributes and tries to add it as a command. Parameters ---------- klass : `type` The class, from what's attributes the command will be created. Returns ------- command : ``Command`` The added command instance. """ command = Command.from_class(klass) if isinstance(command, Router): command = command[0] self._add_command(command) return command def delete_event(self, command, name=None): """ Removes the specified command from the command processor. Parameters ---------- command : ``Command``, ``Router``, `async-callable` or instantiable to `async-callable` The command to remove. name : `None` or `str`, Optional The command's name to remove. Raises ------ TypeError If `name` was not given as `None` or as `str` instance. """ if (name is not None): name_type = type(name) if name_type is str: pass elif issubclass(name_type, str): name = str(name) else: raise TypeError(f'`name` can be `None` or `str` instance, got {name_type.__name__}.') if isinstance(command, Command): self._remove_command(command) return if isinstance(command, Router): for command in command: self._remove_command(command) return name = raw_name_to_display(name) try: command = self.command_name_to_command[name] except KeyError: return command_function = command._command_function if (command_function is None): return if not compare_converted(command_function._function, command): return self._remove_command(command) def unknown_command(self, unknown_command): """ Registers a function to ba called, when no prefix is found, but no command could be detected. Parameters ---------- unknown_command : `None` of `FunctionType`` The function to call. Should the following parameters: +---------------+---------------+ | Name | Type | +===============+===============+ | client | ``Client`` | +---------------+---------------+ | message | ``Message`` | +---------------+---------------+ | command_name | `str` | +---------------+---------------+ Returns ------- unknown_command : `None` of `FunctionType`` Raises ------ TypeError - If `unknown_command` accepts bad amount of parameters. - If `unknown_command` is not async. """ test_unknown_command(unknown_command) self._unknown_command = unknown_command return unknown_command
/** * Copyright (c) 2017-present, Dash Core Team * * This source code is licensed under the MIT license found in the * COPYING file in the root directory of this source tree. */ 'use strict'; let VMN = require('../../index.js'); let expect = require('chai').expect; describe('Stack: Unit\n ---------------------', function () { describe('DB Unit', function () { let collName = 'selftest'; let obj1 = {id: 1}; let obj2 = {id: 2}; it('should create a collection', function () { let da = new VMN.DAPI(); da.db.addCollection(collName); let o = da.db.getCollection(collName); expect(o).to.exist; }); it('should add object to collection', function () { let da = new VMN.DAPI(); let c = da.db.insertToCollection(collName, obj1); expect(c[0].id).to.equal(1); }); it('should find object in collection', function () { let da = new VMN.DAPI(); let c = da.db.findInCollection(collName, obj1); expect(c).to.exist; }); it('should not find object from mutated query', function () { let da = new VMN.DAPI(); let c = da.db.findInCollection(collName, obj2); expect(c).to.not.exist; }); it('should not insert duplicate object to collection', function () { let da = new VMN.DAPI(); let c = da.db.insertToCollection(collName, obj1); expect(c).to.equal(false); }); it('should insert additional unique object to collection', function () { let da = new VMN.DAPI(); da.db.insertToCollection(collName, obj2); let c2 = da.db.findInCollection(collName, obj2); expect(c2).to.exist; }); it('should return an array of all objects in a collection', function () { let da = new VMN.DAPI(); let c = da.db.getCollection(collName); expect(c.length > 1).to.be.true; }); it('should remove an object from collection', function () { let da = new VMN.DAPI(); da.db.removeFromCollection(collName, obj1); let c2 = da.db.findInCollection(collName, obj1); expect(c2).to.not.exist; }); it('should remove all objects from collection', function () { let da = new VMN.DAPI(); da.db.removeFromCollection(collName); let c2 = da.db.findInCollection(collName, obj2); expect(c2).to.not.exist; }); it('should delete all db data', function () { let da = new VMN.DAPI(); da.db.cleanDB(); let c2 = da.db.collectionExists(collName); expect(c2).to.not.exist; }); }); });
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'CutieEMG.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(640, 480) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.button2 = QtWidgets.QPushButton(self.centralwidget) self.button2.setGeometry(QtCore.QRect(40, 380, 111, 51)) self.button2.setObjectName("button2") self.label1 = QtWidgets.QLabel(self.centralwidget) self.label1.setGeometry(QtCore.QRect(190, 10, 281, 51)) font = QtGui.QFont() font.setPointSize(11) font.setBold(True) font.setWeight(75) self.label1.setFont(font) self.label1.setAlignment(QtCore.Qt.AlignCenter) self.label1.setWordWrap(True) self.label1.setObjectName("label1") self.button3 = QtWidgets.QPushButton(self.centralwidget) self.button3.setGeometry(QtCore.QRect(489, 380, 111, 51)) self.button3.setObjectName("button3") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 640, 21)) self.menubar.setObjectName("menubar") self.fileMenu = QtWidgets.QMenu(self.menubar) self.fileMenu.setObjectName("fileMenu") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionNew = QtWidgets.QAction(MainWindow) self.actionNew.setObjectName("actionNew") self.actionSave = QtWidgets.QAction(MainWindow) self.actionSave.setObjectName("actionSave") self.actionSave_as = QtWidgets.QAction(MainWindow) self.actionSave_as.setObjectName("actionSave_as") self.actionCopy = QtWidgets.QAction(MainWindow) self.actionCopy.setObjectName("actionCopy") self.actionPaste = QtWidgets.QAction(MainWindow) self.actionPaste.setObjectName("actionPaste") self.fileMenu.addAction(self.actionNew) self.fileMenu.addAction(self.actionSave) self.fileMenu.addAction(self.actionSave_as) self.menubar.addAction(self.fileMenu.menuAction()) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.actionNew.triggered.connect(lambda: self.clicked('New file created')) self.actionSave.triggered.connect(lambda: self.clicked('File saved !')) self.actionSave_as.triggered.connect(lambda: self.clicked('Save file created !')) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.button2.setText(_translate("MainWindow", "Pause")) self.label1.setText(_translate("MainWindow", "Real Time \n" " Identification Emotion EMG-based")) self.button3.setText(_translate("MainWindow", "Stop")) self.fileMenu.setTitle(_translate("MainWindow", "File")) self.actionNew.setText(_translate("MainWindow", "New")) self.actionNew.setStatusTip(_translate("MainWindow", "Created new file")) self.actionNew.setShortcut(_translate("MainWindow", "Ctrl+N")) self.actionSave.setText(_translate("MainWindow", "Save")) self.actionSave.setStatusTip(_translate("MainWindow", "Saved!")) self.actionSave.setShortcut(_translate("MainWindow", "Ctrl+S")) self.actionSave_as.setText(_translate("MainWindow", "Save as")) self.actionSave_as.setStatusTip(_translate("MainWindow", "Saved on new file")) self.actionSave_as.setShortcut(_translate("MainWindow", "Ctrl+Shift+S")) self.actionCopy.setText(_translate("MainWindow", "Copy")) self.actionCopy.setShortcut(_translate("MainWindow", "Ctrl+C")) self.actionPaste.setText(_translate("MainWindow", "Paste")) self.actionPaste.setShortcut(_translate("MainWindow", "Ctrl+V")) def clicked(self,text): self.label1.setText(text) self.label1.adjustSize() if __name__ == "__main__": import sys app = QtWidgets.QApplication(sys.argv) MainWindow = QtWidgets.QMainWindow() ui = Ui_MainWindow() ui.setupUi(MainWindow) MainWindow.show() sys.exit(app.exec_())
import Immutable from 'immutable'; // import { getNavigationItem } from './actions'; import { Actions, Properties } from './constants'; const INITIAL_STATE = new Immutable.Map({ [Properties.PROPERTIES]: null, // configuration propereties [Properties.NAVIGATION]: null, // all navigation items from enabled modules as Map selectedNavigationItems: ['home'], // homepage by default i18nReady: null, // localization language is ready modulesReady: false, // modules loaders is ready navigationReady: false, configurationReady: false, appReady: false, appUnavailable: false, hideFooter: false }); /** * Config / layout storage * * @author Radek Tomiška */ export function config(state = INITIAL_STATE, action) { switch (action.type) { case Actions.SELECT_NAVIGATION_ITEMS: { const prevState = state.get('selectedNavigationItems'); const newState = []; for (let i = 0; i < action.selectedNavigationItems.length; i++) { newState[i] = action.selectedNavigationItems[i] || (prevState.length > i ? prevState[i] : null); } return state.set('selectedNavigationItems', newState); } case Actions.SELECT_NAVIGATION_ITEM: { const newState = []; // traverse to item parent let itemId = action.selectedNavigationItemId; while (itemId !== null) { const item = getNavigationItem(state, itemId); if (!item) { break; } newState.splice(0, 0, item.id); // insert at state itemId = item.parentId; } return state.set('selectedNavigationItems', newState); } case Actions.I18N_INIT: { return state.set('i18nReady', null); } case Actions.I18N_READY: { LOGGER.debug('i18n ready [' + action.lng + ']'); return state.set('i18nReady', action.lng); } case Actions.MODULES_INIT: { return state.set('modulesReady', false); } case Actions.MODULES_READY: { LOGGER.debug('modules ready [' + action.ready + ']'); return state.set('modulesReady', action.ready); } case Actions.NAVIGATION_INIT: { return state.set('navigationReady', false); } case Actions.NAVIGATION_READY: { LOGGER.debug('navigation ready [' + action.ready + ']'); let newState = state.set(Properties.NAVIGATION, action.navigation); newState = newState.set('navigationReady', action.ready); return newState; } case Actions.CONFIGURATION_INIT: { return state.set('configurationReady', false); } case Actions.CONFIGURATION_READY: { LOGGER.debug('configuration ready [' + action.ready + ']'); const newState = state.set('configurationReady', action.ready); return newState; } case Actions.APP_INIT: { let newState = state.set('appReady', false); newState = newState.set('appUnavailable', false); return newState; } case Actions.APP_READY: { LOGGER.debug('app ready [' + action.ready + ']'); return state.set('appReady', action.ready); } case Actions.APP_UNAVAILABLE: { let newState = state.set('appReady', false); newState = newState.set('appUnavailable', true); return newState; } case Actions.CONFIGURATION_RECEIVED: { const configs = state.get(Properties.PROPERTIES); if (configs) { // put new values return state.set(Properties.PROPERTIES, configs.merge(action.data)); } return state.set(Properties.PROPERTIES, action.data); } case Actions.HIDE_FOOTER: { return state.set(Properties.HIDE_FOOTER, action.hideFooter); } default: return state; } }
import * as ActionTypes from "../constants/actionTypes"; /* eslint-disable import/prefer-default-export */ export const storeEpicInfo = (payload) => ({ type: ActionTypes.STORE_MINE_EPIC_INFO, payload, });
import React, { useEffect } from 'react'; import { useQuery } from '@apollo/react-hooks'; //import { useStoreContext } from '../../utils/GlobalState'; import { useDispatch, useSelector } from 'react-redux'; import { UPDATE_CATEGORIES, UPDATE_CURRENT_CATEGORY, } from '../../utils/actions'; import { QUERY_CATEGORIES } from '../../utils/queries'; import { idbPromise } from '../../utils/helpers'; function CategoryMenu() { //const [state, dispatch] = useStoreContext(); const state = useSelector((state) => { return state }); const dispatch = useDispatch(); const { categories } = state; const { loading, data: categoryData } = useQuery(QUERY_CATEGORIES); useEffect(() => { if (categoryData) { dispatch({ type: UPDATE_CATEGORIES, categories: categoryData.categories, }); categoryData.categories.forEach((category) => { idbPromise('categories', 'put', category); }); } else if (!loading) { idbPromise('categories', 'get').then((categories) => { dispatch({ type: UPDATE_CATEGORIES, categories: categories, }); }); } }, [categoryData, loading, dispatch]); const handleClick = (id) => { dispatch({ type: UPDATE_CURRENT_CATEGORY, currentCategory: id, }); }; return ( <div> <h2>Choose a Category:</h2> {categories.map((item) => ( <button key={item._id} onClick={() => { handleClick(item._id); }} > {item.name} </button> ))} </div> ); } export default CategoryMenu;
"""This module holds a ConnectionWrapper that is used with a JDBC Connection. The module should only be used when running Jython. """ # Copyright (c) 2009-2011, Christian Thomsen ([email protected]) # All rights reserved. # Redistribution and use in source anqd binary forms, with or without # modification, are permitted provided that the following conditions are met: # - Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # - Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import java.sql as jdbc from copy import copy as pcopy from datetime import datetime from sys import modules from threading import Thread from Queue import Queue import pygrametl from pygrametl.FIFODict import FIFODict # NOTE: This module is made for Jython. __author__ = "Christian Thomsen" __maintainer__ = "Christian Thomsen" __version__ = '0.2.0' __all__ = ['JDBCConnectionWrapper', 'BackgroundJDBCConnectionWrapper'] class JDBCConnectionWrapper(object): """Wrap a JDBC Connection. All Dimension and FactTable communicate with the data warehouse using a ConnectionWrapper. In this way, the code for loading the DW does not have to care about which parameter format is used. This ConnectionWrapper is a special one for JDBC in Jython. """ def __init__(self, jdbcconn, stmtcachesize=20): """Create a ConnectionWrapper around the given JDBC connection. If no default ConnectionWrapper already exists, the new ConnectionWrapper is set to be the default ConnectionWrapper. Arguments: - jdbcconn: An open JDBC Connection (not a PEP249 Connection) - stmtcachesize: The maximum number of PreparedStatements kept open. Default: 20. """ if not isinstance(jdbcconn, jdbc.Connection): raise TypeError, '1st argument must implement java.sql.Connection' if jdbcconn.isClosed(): raise ValueError, '1st argument must be an open Connection' self.__jdbcconn = jdbcconn # Add a finalizer to __prepstmts to close PreparedStatements when # they are pushed out self.__prepstmts = FIFODict(stmtcachesize, lambda k, v: v[0].close()) self.__resultmeta = FIFODict(stmtcachesize) self.__resultset = None self.__resultnames = None self.__resulttypes = None self.nametranslator = lambda s: s self.__jdbcconn.setAutoCommit(False) if pygrametl._defaulttargetconnection is None: pygrametl._defaulttargetconnection = self def __preparejdbcstmt(self, sql): # Find pyformat arguments and change them to question marks while # appending the attribute names to a list names = [] newsql = sql while True: start = newsql.find('%(') if start == -1: break end = newsql.find(')s', start) if end == -1: break name = newsql[start+2 : end] names.append(name) newsql = newsql.replace(newsql[start:end+2], '?', 1) ps = self.__jdbcconn.prepareStatement(newsql) # Find parameter types types = [] parmeta = ps.getParameterMetaData() for i in range(len(names)): types.append(parmeta.getParameterType(i+1)) self.__prepstmts[sql] = (ps, names, types) def __executejdbcstmt(self, sql, args): if self.__resultset: self.__resultset.close() if sql not in self.__prepstmts: self.__preparejdbcstmt(sql) (ps, names, types) = self.__prepstmts[sql] for pos in range(len(names)): # Not very Pythonic, but we're doing Java if args[names[pos]] is None: ps.setNull(pos + 1, types[pos]) else: ps.setObject(pos + 1, args[names[pos]], types[pos]) if ps.execute(): self.__resultset = ps.getResultSet() if sql not in self.__resultmeta: self.__resultmeta[sql] = \ self.__extractresultmetadata(self.__resultset) (self.__resultnames, self.__resulttypes) = self.__resultmeta[sql] else: self.__resultset = None (self.__resultnames, self.__resulttypes) = (None, None) def __extractresultmetadata(self, resultset): # Get jdbc resultset metadata. extract names and types # and add it to self.__resultmeta meta = resultset.getMetaData() names = [] types = [] for col in range(meta.getColumnCount()): names.append(meta.getColumnName(col+1)) types.append(meta.getColumnType(col+1)) return (names, types) def __readresultrow(self): if self.__resultset is None: return None result = [] for i in range(len(self.__resulttypes)): e = self.__resulttypes[i] # Not Pythonic, but we need i for JDBC if e in (jdbc.Types.CHAR, jdbc.Types.VARCHAR, jdbc.Types.LONGVARCHAR): result.append(self.__resultset.getString(i+1)) elif e in (jdbc.Types.BIT, jdbc.Types.BOOLEAN): result.append(self.__resultset.getBool(i+1)) elif e in (jdbc.Types.TINYINT, jdbc.Types.SMALLINT, jdbc.Types.INTEGER): result.append(self.__resultset.getInt(i+1)) elif e in (jdbc.Types.BIGINT, ): result.append(self.__resultset.getLong(i+1)) elif e in (jdbc.Types.DATE, ): result.append(self.__resultset.getDate(i+1)) elif e in (jdbc.Types.TIMESTAMP, ): result.append(self.__resultset.getTimestamp(i+1)) elif e in (jdbc.Types.TIME, ): result.append(self.__resultset.getTime(i+1)) else: # Try this and hope for the best... result.append(self.__resultset.getString(i+1)) return tuple(result) def execute(self, stmt, arguments=None, namemapping=None, ignored=None): """Execute a statement. Arguments: - stmt: the statement to execute - arguments: a mapping with the arguments (default: None) - namemapping: a mapping of names such that if stmt uses %(arg)s and namemapping[arg]=arg2, the value arguments[arg2] is used instead of arguments[arg] - ignored: An ignored argument only present to accept the same number of arguments as ConnectionWrapper.execute """ if namemapping and arguments: arguments = pygrametl.copy(arguments, **namemapping) self.__executejdbcstmt(stmt, arguments) def executemany(self, stmt, params, ignored=None): """Execute a sequence of statements. Arguments: - stmt: the statement to execute - params: a sequence of arguments - ignored: An ignored argument only present to accept the same number of arguments as ConnectionWrapper.executemany """ for paramset in params: self.__executejdbcstmt(stmt, paramset) def rowfactory(self, names=None): """Return a generator object returning result rows (i.e. dicts).""" if names is None: if self.__resultnames is None: return else: names = [self.nametranslator(t[0]) for t in self.__resultnames] empty = (None, ) * len(self.__resultnames) while True: tuple = self.fetchonetuple() if tuple == empty: return yield dict(zip(names, tuple)) def fetchone(self, names=None): """Return one result row (i.e. dict).""" if self.__resultset is None: return {} if names is None: names = [self.nametranslator(t[0]) for t in self.__resultnames] values = self.fetchonetuple() return dict(zip(names, values)) def fetchonetuple(self): """Return one result tuple.""" if self.__resultset is None: return () if not self.__resultset.next(): return (None, ) * len(self.__resultnames) else: return self.__readresultrow() def fetchmanytuples(self, cnt): """Return cnt result tuples.""" if self.__resultset is None: return [] empty = (None, ) * len(self.__resultnames) result = [] for i in range(cnt): tmp = self.fetchonetuple() if tmp == empty: break result.append(tmp) return result def fetchalltuples(self): """Return all result tuples""" if self.__resultset is None: return [] result = [] empty = (None, ) * len(self.__resultnames) while True: tmp = self.fetchonetuple() if tmp == empty: return result result.append(tmp) def rowcount(self): """Not implemented. Return 0. Should return the size of the result.""" return 0 def getunderlyingmodule(self): """Return a reference to the underlying connection's module.""" return modules[self.__class__.__module__] def commit(self): """Commit the transaction.""" pygrametl.endload() self.__jdbcconn.commit() def close(self): """Close the connection to the database,""" self.__jdbcconn.close() def rollback(self): """Rollback the transaction.""" self.__jdbcconn.rollback() def setasdefault(self): """Set this ConnectionWrapper as the default connection.""" pygrametl._defaulttargetconnection = self def cursor(self): """Not implemented for this JDBC connection wrapper!""" raise NotImplementedError, ".cursor() not supported" def resultnames(self): if self.__resultnames is None: return None else: return tuple(self.__resultnames) # BackgroundJDBCConnectionWrapper is added for experiments. It is quite similar # to JDBCConnectionWrapper and one of them may be removed. class BackgroundJDBCConnectionWrapper(object): """Wrap a JDBC Connection and do all DB communication in the background. All Dimension and FactTable communicate with the data warehouse using a ConnectionWrapper. In this way, the code for loading the DW does not have to care about which parameter format is used. This ConnectionWrapper is a special one for JDBC in Jython and does DB communication from a Thread. """ def __init__(self, jdbcconn, stmtcachesize=20): """Create a ConnectionWrapper around the given JDBC connection """ self.__jdbcconn = jdbcconn # Add a finalizer to __prepstmts to close PreparedStatements when # they are pushed out self.__prepstmts = FIFODict(stmtcachesize, lambda k, v: v[0].close()) self.__resultmeta = FIFODict(stmtcachesize) self.__resultset = None self.__resultnames = None self.__resulttypes = None self.nametranslator = lambda s: s self.__jdbcconn.setAutoCommit(False) self.__queue = Queue(5000) t = Thread(target=self.__worker) t.setDaemon(True) # NB: "t.daemon = True" does NOT work... t.setName('BackgroundJDBCConnectionWrapper') t.start() def __worker(self): while True: (sql, args) = self.__queue.get() self.__executejdbcstmt(sql, args) self.__queue.task_done() def __preparejdbcstmt(self, sql): # Find pyformat arguments and change them to question marks while # appending the attribute names to a list names = [] newsql = sql while True: start = newsql.find('%(') if start == -1: break end = newsql.find(')s', start) if end == -1: break name = newsql[start+2 : end] names.append(name) newsql = newsql.replace(newsql[start:end+2], '?', 1) ps = self.__jdbcconn.prepareStatement(newsql) # Find parameter types types = [] parmeta = ps.getParameterMetaData() for i in range(len(names)): types.append(parmeta.getParameterType(i+1)) self.__prepstmts[sql] = (ps, names, types) def __executejdbcstmt(self, sql, args): if self.__resultset: self.__resultset.close() if sql not in self.__prepstmts: self.__preparejdbcstmt(sql) (ps, names, types) = self.__prepstmts[sql] for pos in range(len(names)): # Not very Pythonic, but we're doing Java if args[names[pos]] is None: ps.setNull(pos + 1, types[pos]) else: ps.setObject(pos + 1, args[names[pos]], types[pos]) if ps.execute(): self.__resultset = ps.getResultSet() if sql not in self.__resultmeta: self.__resultmeta[sql] = \ self.__extractresultmetadata(self.__resultset) (self.__resultnames, self.__resulttypes) = self.__resultmeta[sql] else: self.__resultset = None (self.__resultnames, self.__resulttypes) = (None, None) def __extractresultmetadata(self, resultset): # Get jdbc resultset metadata. extract names and types # and add it to self.__resultmeta meta = resultset.getMetaData() names = [] types = [] for col in range(meta.getColumnCount()): names.append(meta.getColumnName(col+1)) types.append(meta.getColumnType(col+1)) return (names, types) def __readresultrow(self): if self.__resultset is None: return None result = [] for i in range(len(self.__resulttypes)): e = self.__resulttypes[i] # Not Pythonic, but we need i for JDBC if e in (jdbc.Types.CHAR, jdbc.Types.VARCHAR, jdbc.Types.LONGVARCHAR): result.append(self.__resultset.getString(i+1)) elif e in (jdbc.Types.BIT, jdbc.Types.BOOLEAN): result.append(self.__resultset.getBool(i+1)) elif e in (jdbc.Types.TINYINT, jdbc.Types.SMALLINT, jdbc.Types.INTEGER): result.append(self.__resultset.getInt(i+1)) elif e in (jdbc.Types.BIGINT, ): result.append(self.__resultset.getLong(i+1)) elif e in (jdbc.Types.DATE, ): result.append(self.__resultset.getDate(i+1)) elif e in (jdbc.Types.TIMESTAMP, ): result.append(self.__resultset.getTimestamp(i+1)) elif e in (jdbc.Types.TIME, ): result.append(self.__resultset.getTime(i+1)) else: # Try this and hope for the best... result.append(self.__resultset.getString(i+1)) return tuple(result) def execute(self, stmt, arguments=None, namemapping=None, ignored=None): """Execute a statement. Arguments: - stmt: the statement to execute - arguments: a mapping with the arguments (default: None) - namemapping: a mapping of names such that if stmt uses %(arg)s and namemapping[arg]=arg2, the value arguments[arg2] is used instead of arguments[arg] - ignored: An ignored argument only present to accept the same number of arguments as ConnectionWrapper.execute """ if namemapping and arguments: arguments = pygrametl.copy(arguments, **namemapping) else: arguments = pcopy(arguments) self.__queue.put((stmt, arguments)) def executemany(self, stmt, params, ignored=None): """Execute a sequence of statements. Arguments: - stmt: the statement to execute - params: a sequence of arguments - ignored: An ignored argument only present to accept the same number of arguments as ConnectionWrapper.executemany """ for paramset in params: self.__queue.put((stmt, paramset)) def rowfactory(self, names=None): """Return a generator object returning result rows (i.e. dicts).""" self.__queue.join() if names is None: if self.__resultnames is None: return else: names = [self.nametranslator(t[0]) for t in self.__resultnames] empty = (None, ) * len(self.__resultnames) while True: tuple = self.fetchonetuple() if tuple == empty: return yield dict(zip(names, tuple)) def fetchone(self, names=None): """Return one result row (i.e. dict).""" self.__queue.join() if self.__resultset is None: return {} if names is None: names = [self.nametranslator(t[0]) for t in self.__resultnames] values = self.fetchonetuple() return dict(zip(names, values)) def fetchonetuple(self): """Return one result tuple.""" self.__queue.join() if self.__resultset is None: return () if not self.__resultset.next(): return (None, ) * len(self.__resultnames) else: return self.__readresultrow() def fetchmanytuples(self, cnt): """Return cnt result tuples.""" self.__queue.join() if self.__resultset is None: return [] empty = (None, ) * len(self.__resultnames) result = [] for i in range(cnt): tmp = self.fetchonetuple() if tmp == empty: break result.append(tmp) return result def fetchalltuples(self): """Return all result tuples""" self.__queue.join() if self.__resultset is None: return [] result = [] empty = (None, ) * len(self.__resultnames) while True: tmp = self.fetchonetuple() if tmp == empty: return result result.append(tmp) def rowcount(self): """Not implemented. Return 0. Should return the size of the result.""" return 0 def getunderlyingmodule(self): """Return a reference to the underlying connection's module.""" return modules[self.__class__.__module__] def commit(self): """Commit the transaction.""" pygrametl.endload() self.__queue.join() self.__jdbcconn.commit() def close(self): """Close the connection to the database,""" self.__queue.join() self.__jdbcconn.close() def rollback(self): """Rollback the transaction.""" self.__queue.join() self.__jdbcconn.rollback() def setasdefault(self): """Set this ConnectionWrapper as the default connection.""" pygrametl._defaulttargetconnection = self def cursor(self): """Not implemented for this JDBC connection wrapper!""" raise NotImplementedError, ".cursor() not supported" def resultnames(self): self.__queue.join() if self.__resultnames is None: return None else: return tuple(self.__resultnames) def Date(year, month, day): date = '%s-%s-%s' % \ (str(year).zfill(4), str(month).zfill(2), str(day).zfill(2)) return jdbc.Date.valueOf(date) def Timestamp(year, month, day, hour, minute, second): date = '%s-%s-%s %s:%s:%s' % \ (str(year).zfill(4), str(month).zfill(2), str(day).zfill(2), str(hour).zfill(2), str(minute).zfill(2), str(second).zfill(2)) return jdbc.Timestamp.valueOf(date)
"use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /* * jQuery Easing v1.4.1 - http://gsgd.co.uk/sandbox/jquery/easing/ * Open source under the BSD License. * Copyright © 2008 George McGinley Smith * All rights reserved. * https://raw.github.com/gdsmith/jquery-easing/master/LICENSE */ (function (factory) { if (typeof define === "function" && define.amd) { define(['jquery'], function ($) { return factory($); }); } else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && _typeof(module.exports) === "object") { exports = factory(require('jquery')); } else { factory(jQuery); } })(function ($) { // Preserve the original jQuery "swing" easing as "jswing" $.easing.jswing = $.easing.swing; var pow = Math.pow, sqrt = Math.sqrt, sin = Math.sin, cos = Math.cos, PI = Math.PI, c1 = 1.70158, c2 = c1 * 1.525, c3 = c1 + 1, c4 = 2 * PI / 3, c5 = 2 * PI / 4.5; // x is the fraction of animation progress, in the range 0..1 function bounceOut(x) { var n1 = 7.5625, d1 = 2.75; if (x < 1 / d1) { return n1 * x * x; } else if (x < 2 / d1) { return n1 * (x -= 1.5 / d1) * x + 0.75; } else if (x < 2.5 / d1) { return n1 * (x -= 2.25 / d1) * x + 0.9375; } else { return n1 * (x -= 2.625 / d1) * x + 0.984375; } } $.extend($.easing, { def: 'easeOutQuad', swing: function swing(x) { return $.easing[$.easing.def](x); }, easeInQuad: function easeInQuad(x) { return x * x; }, easeOutQuad: function easeOutQuad(x) { return 1 - (1 - x) * (1 - x); }, easeInOutQuad: function easeInOutQuad(x) { return x < 0.5 ? 2 * x * x : 1 - pow(-2 * x + 2, 2) / 2; }, easeInCubic: function easeInCubic(x) { return x * x * x; }, easeOutCubic: function easeOutCubic(x) { return 1 - pow(1 - x, 3); }, easeInOutCubic: function easeInOutCubic(x) { return x < 0.5 ? 4 * x * x * x : 1 - pow(-2 * x + 2, 3) / 2; }, easeInQuart: function easeInQuart(x) { return x * x * x * x; }, easeOutQuart: function easeOutQuart(x) { return 1 - pow(1 - x, 4); }, easeInOutQuart: function easeInOutQuart(x) { return x < 0.5 ? 8 * x * x * x * x : 1 - pow(-2 * x + 2, 4) / 2; }, easeInQuint: function easeInQuint(x) { return x * x * x * x * x; }, easeOutQuint: function easeOutQuint(x) { return 1 - pow(1 - x, 5); }, easeInOutQuint: function easeInOutQuint(x) { return x < 0.5 ? 16 * x * x * x * x * x : 1 - pow(-2 * x + 2, 5) / 2; }, easeInSine: function easeInSine(x) { return 1 - cos(x * PI / 2); }, easeOutSine: function easeOutSine(x) { return sin(x * PI / 2); }, easeInOutSine: function easeInOutSine(x) { return -(cos(PI * x) - 1) / 2; }, easeInExpo: function easeInExpo(x) { return x === 0 ? 0 : pow(2, 10 * x - 10); }, easeOutExpo: function easeOutExpo(x) { return x === 1 ? 1 : 1 - pow(2, -10 * x); }, easeInOutExpo: function easeInOutExpo(x) { return x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? pow(2, 20 * x - 10) / 2 : (2 - pow(2, -20 * x + 10)) / 2; }, easeInCirc: function easeInCirc(x) { return 1 - sqrt(1 - pow(x, 2)); }, easeOutCirc: function easeOutCirc(x) { return sqrt(1 - pow(x - 1, 2)); }, easeInOutCirc: function easeInOutCirc(x) { return x < 0.5 ? (1 - sqrt(1 - pow(2 * x, 2))) / 2 : (sqrt(1 - pow(-2 * x + 2, 2)) + 1) / 2; }, easeInElastic: function easeInElastic(x) { return x === 0 ? 0 : x === 1 ? 1 : -pow(2, 10 * x - 10) * sin((x * 10 - 10.75) * c4); }, easeOutElastic: function easeOutElastic(x) { return x === 0 ? 0 : x === 1 ? 1 : pow(2, -10 * x) * sin((x * 10 - 0.75) * c4) + 1; }, easeInOutElastic: function easeInOutElastic(x) { return x === 0 ? 0 : x === 1 ? 1 : x < 0.5 ? -(pow(2, 20 * x - 10) * sin((20 * x - 11.125) * c5)) / 2 : pow(2, -20 * x + 10) * sin((20 * x - 11.125) * c5) / 2 + 1; }, easeInBack: function easeInBack(x) { return c3 * x * x * x - c1 * x * x; }, easeOutBack: function easeOutBack(x) { return 1 + c3 * pow(x - 1, 3) + c1 * pow(x - 1, 2); }, easeInOutBack: function easeInOutBack(x) { return x < 0.5 ? pow(2 * x, 2) * ((c2 + 1) * 2 * x - c2) / 2 : (pow(2 * x - 2, 2) * ((c2 + 1) * (x * 2 - 2) + c2) + 2) / 2; }, easeInBounce: function easeInBounce(x) { return 1 - bounceOut(1 - x); }, easeOutBounce: bounceOut, easeInOutBounce: function easeInOutBounce(x) { return x < 0.5 ? (1 - bounceOut(1 - 2 * x)) / 2 : (1 + bounceOut(2 * x - 1)) / 2; } }); });
'use strict'; /* eslint-disable quote-props, quotes */ module.exports = { "extends": [ "./client-common", "./language/es5", "./vue2-es5" ], "rules": { "no-restricted-properties": [ "error", { "property": "parentElement", "message": "Prefer parentNode to parentElement as Node.parentElement is not supported by IE11." } ] } };
"use strict"; function Tile(x, y, row, col, type, context) { this.isClickable = true; this.x = x; this.y = y; this.row = row; this.col = col; this.type = type; this.context = context; this.color = COLORS[type]; this.radius = CONFIG.shape.radius; this.sAngle = 0; this.eAngle = 1.2*Math.PI; this.strokeStyle = "#fff"; this.fillStyle = this.color; } Tile.prototype.draw = function() { this.context.beginPath(); this.context.arc(this.x, this.y, this.radius, this.sAngle, this.eAngle); this.context.fillStyle = this.fillStyle; this.context.fill(); this.context.strokeStyle = this.strokeStyle; this.context.stroke(); this.context.closePath(); }; Tile.prototype.fadeout = function() { }; Tile.prototype.contains = function(x, y) { return (x >= this.x-this.radius) && (x <= this.x + this.radius) && (y >= this.y-this.radius) && (y <= this.y + this.radius); };
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # Licensed under the Apache License, Version 2.0 (the "License") # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http: // www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Service Class # this is a auto generated file generated by Cheetah # Libre Office Version: 7.3 # Namespace: com.sun.star.ucb from ...lo.ucb.content_result_set import ContentResultSet as ContentResultSet __all__ = ['ContentResultSet']
class Region(object): def __init__(self): self.x = 0 self.y = 0 self.width = 0 self.height = 0 def __iter__(self): yield self.left yield self.top yield self.right yield self.bottom def __getitem__(self, key): if key == 0: return self.left elif key == 1: return self.top elif key == 2: return self.right elif key == 3: return self.bottom else: return None @property def left(self): return self.x @left.setter def left(self, value): self.width -= value - self.x self.x = value @property def right(self): return self.left + self.width @right.setter def right(self, value): self.width = max(value - self.left, 0) @property def top(self): return self.y @top.setter def top(self, value): self.height -= value - self.y self.y = value @property def bottom(self): return self.top + self.height @bottom.setter def bottom(self, value): self.height = max(value - self.top, 0) def ltr(self): return xrange(self.left, self.right) def rtl(self): return xrange(self.right, self.left, -1) def ttb(self): return xrange(self.top, self.bottom) def btt(self): return xrange(self.bottom, self.top, -1)
export { default } from 'ember-date-components/components/time-picker-input';
from django import forms from django.contrib import admin, messages from django.contrib.auth.admin import UserAdmin as AuthUserAdmin from django.contrib.auth.forms import UserChangeForm, UserCreationForm from django.utils.translation import ugettext as _ from .models import User class MyUserChangeForm(UserChangeForm): class Meta(UserChangeForm.Meta): model = User class MyUserCreationForm(UserCreationForm): error_message = UserCreationForm.error_messages.update( {"duplicate_username": "This username has already been taken."} ) class Meta(UserCreationForm.Meta): model = User def clean_username(self): username = self.cleaned_data["username"] try: User.objects.get(username=username) except User.DoesNotExist: return username raise forms.ValidationError(self.error_messages["duplicate_username"]) def gen_address(modeladmin, request, queryset): for user in queryset: user.gen_address() user.save() def ask_for_initial_balance(modeladmin, request, queryset): for user in queryset: result, message = user.ask_for_initial_balance() if result: messages.success(request, _("Initial balance fetched")) else: messages.warning(request, message) @admin.register(User) class MyUserAdmin(AuthUserAdmin): form = MyUserChangeForm add_form = MyUserCreationForm list_display = ("username", "is_superuser", "stellar_key") search_fields = ["username"] fieldsets = AuthUserAdmin.fieldsets + (("Extra data", {"fields": tuple()}),) readonly_fields = ("date_joined", "last_login") actions = [gen_address, ask_for_initial_balance]
import React from "react" import PropTypes from "prop-types" import "./styles/bootstrap.min.css" import "./styles/styles.css" const Layout = ({ children }) => { return ( <div> <div className="container" id=""> <h1> Number Conversion <span className="badge">beta Version</span> </h1> {children} </div> <div className="footer"> <p> Design & Developed By <a href="http://facebook.com/joshimCSE"> Joshim Uddin</a> </p> </div> </div> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
import pytest from pydantic import BaseModel, ValidationError from server.forms.validators import unique_conlist def test_constrained_list_good(): class UniqueConListModel(BaseModel): v: unique_conlist(int, unique_items=True) = [] m = UniqueConListModel(v=[1, 2, 3]) assert m.v == [1, 2, 3] def test_constrained_list_default(): class UniqueConListModel(BaseModel): v: unique_conlist(int, unique_items=True) = [] m = UniqueConListModel() assert m.v == []
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), shell = ctx.requireCordovaModule("shelljs"), UglifyJS = require('uglify-js'), CleanCSS = require('clean-css'), htmlMinify = require('html-minifier').minify, cssOptions = { keepSpecialComments: 0 }, cssMinifier = new CleanCSS(cssOptions), rootDir = ctx.opts.projectRoot, platformPath = path.join(rootDir, 'platforms'), platforms = ctx.opts.cordova.platforms, platform = platforms.length ? platforms[0] : '', cliCommand = ctx.cmdLine, debug = true, //false htmlOptions = { removeAttributeQuotes: true, removeComments: true, minifyJS: true, minifyCSS: cssOptions, collapseWhitespace: true, conservativeCollapse: true, removeComments: true, removeEmptyAttributes: true }, successCounter = 0, errorCounter = 0, notProcessedCounter = 0, pendingCounter = 0, hasStartedProcessing = false, processRoot = false, isBrowserify = (cliCommand.indexOf('--browserify') > -1), //added isRelease = true; // isRelease = false; // isRelease = (cliCommand.indexOf('--release') > -1); // comment the above line and uncomment this line to turn the hook on only for release function processFiles(dir, _noRecursive) { fs.readdir(dir, function (err, list) { if (err) { console.error('processFiles - reading directories error: ' + err); return; } list.forEach(function(file) { file = path.join(dir, file); fs.stat(file, function(err, stat) { hasStartedProcessing = true; if (stat.isDirectory()) { if (!_noRecursive) processFiles(file); } else { compress(file); } }); }); }); } function processFile(file) { fs.stat(file, function(err, stat) { hasStartedProcessing = true; compress(file); }); } function compress(file) { var ext = path.extname(file); switch(ext.toLowerCase()) { case '.js': (debug) && console.log('Compressing/Uglifying JS File: ' + file); var result = UglifyJS.minify(file, { mangle:true, compress: { dead_code: true, drop_debugger: true, drop_console: true, loops: true, if_return: true, keep_fargs: true, keep_fnames: true, properties: true, conditionals: true, booleans: true, evaluate: true, cascade: true, passes: 3 } }); if (!result || !result.code || result.code.length == 0) { errorCounter++; console.error('\x1b[31mEncountered an error minifying a file: %s\x1b[0m', file, result); } else { successCounter++; fs.writeFileSync(file, result.code, 'utf8'); (debug) && console.log('Optimized: ' + file); } break; case '.css': // // (debug) && console.log('Minifying CSS File: ' + file); // var source = fs.readFileSync(file, 'utf8'); // if (!source || source.length == 0) { // errorCounter++; // console.error('Encountered an empty file: ' + file); // } // else { // var result = cssMinifier.minify(source).styles; // if (!result || result.length == 0) { // errorCounter++; // console.error('\x1b[31mEncountered an error minifying a file: %s\x1b[0m', file); // } // else { // successCounter++; // fs.writeFileSync(file, result, 'utf8'); // (debug) && console.log('Optimized: ' + file); // } // } break; case '.html': // (debug) && console.log('Minifying HTML File: ' + file); // var source = fs.readFileSync(file, 'utf8'); // if (!source || source.length == 0) { // errorCounter++; // console.error('Encountered an empty file: ' + file); // } // else { // var result = htmlMinify(source, htmlOptions); // if (!result || result.length == 0) { // errorCounter++; // console.error('\x1b[31mEncountered an error minifying a file: %s\x1b[0m', file); // } // else { // successCounter++; // fs.writeFileSync(file, result, 'utf8'); // (debug) && console.log('Optimized: ' + file); // } // } break; default: console.error('Encountered file with ' + ext + ' extension - not compressing.'); notProcessedCounter++; break; } } function checkIfFinished() { if (hasStartedProcessing && pendingCounter == 0) console.log('\x1b[36m%s %s %s\x1b[0m', successCounter + (successCounter == 1 ? ' file ' : ' files ') + 'minified.', errorCounter + (errorCounter == 1 ? ' file ' : ' files ') + 'had errors.', notProcessedCounter + (notProcessedCounter == 1 ? ' file was ' : ' files were ') + 'not processed.'); else setTimeout(checkIfFinished, 10); } switch (platform) { case 'android': platformPath = path.join(platformPath, platform , 'app', 'src', 'main', "assets", "www"); break; case 'ios': platformPath = path.join(platformPath, platform, "www"); break; default: console.error('Hook currently supports only Android and iOS'); return; } if(isBrowserify) { shell.rm('-rf', path.join(platformPath, 'cordova-js-src')); shell.rm('-rf', path.join(platformPath, 'plugins')); shell.rm('-f', path.join(platformPath, 'cordova_plugins.js')); } if (!isRelease) { return; } console.log('cordova-minify STARTING - minifying your js, css, html. Sit back and relax!'); //minify files inside these directories //var foldersToProcess = ['javascript', 'style', 'js', 'css', 'html']; var foldersToProcess = isBrowserify ? [] : ['cordova-js-src', 'plugins']; // if (processRoot) processFiles(platformPath, true); foldersToProcess.forEach(function(folder) { processFiles(path.join(platformPath, folder)); }); //minify files one by one var filesToProcess = ['cordova.js']; if(!isBrowserify) filesToProcess.push('cordova_plugins.js'); filesToProcess.forEach(function(file) { processFile(path.join(platformPath, file)); }); checkIfFinished(); };
/** * @author A.Lagresta * @name User Data Model * created on 21.8.2017 * @description database model for User entity */ var mysql = require('mysql'); var config = require('../config.sample'); connection = mysql.createConnection(config.connectionData); var userModel = {}; // All users userModel.getUsers = function(callback) { if (connection) { connection.query('SELECT * FROM users ORDER BY id', function(error, rows) { if(error) { throw error; } else { callback(null, rows); } }); } } // User by id userModel.getUserById = function(id,callback) { if (connection) { var sql = 'SELECT * FROM users WHERE id = ' + connection.escape(id); connection.query(sql, function(error, row) { if(error) { throw error; } else { callback(null, row); } }); } } // User by username userModel.getUserByUName = function(username,callback) { if (connection) { var sql = 'SELECT * FROM users WHERE username = ' + connection.escape(username); connection.query(sql, function(error, row) { if(error) { throw error; } else { callback(null, row); } }); } } // insert User userModel.insertUser = function(userData,callback) { if (connection) { connection.query('INSERT INTO users SET ?', userData, function(error, result) { if(error) { throw error; } else { //devolvemos la última id insertada callback(null,{"insertId" : result.insertId}); } }); } } // Update user userModel.updateUser = function(userData, callback) { //console.log(userData); //return; if(connection) { var sql = 'UPDATE users SET '+ 'username = ' + connection.escape(userData.username) + ',' + 'name = ' + connection.escape(userData.name) + ',' + 'lastname = ' + connection.escape(userData.lastname) + ',' + 'email = ' + connection.escape(userData.email) + 'WHERE id = ' + userData.id; console.log(sql); connection.query(sql, function(error, result) { if(error) { throw error; } else { callback(null,{"msg":"success"}); } }); } } // Delete user userModel.deleteUser = function(id, callback) { if(connection) { var sqlExists = 'SELECT * FROM users WHERE id = ' + connection.escape(id); connection.query(sqlExists, function(err, row) { //si existe la id del usuario a eliminar if(row) { var sql = 'DELETE FROM users WHERE id = ' + connection.escape(id); connection.query(sql, function(error, result) { if(error) { throw error; } else { callback(null,{"msg":"deleted"}); } }); } else { callback(null,{"msg":"notExist"}); } }); } } //exportamos el objeto para tenerlo disponible en la zona de rutas module.exports = userModel;
# test file for the integer prime factorization import abstract_binary.base as abs_bin_base from abstract_binary.binary_number import bin_num from abstract_binary.abstract_binary_number import abstract_bin_num import abstract_binary.multiply from abstract_binary.multiply import multiplication_table import compose_BQM.compose_BQM from compose_BQM.compose_BQM import BQM_from_multiplication_table # Setting DEBUG variables abstract_binary.multiply.DEBUG = True compose_BQM.compose_BQM.DEBUG = True #test for the multiplication table # The bitlengths of the binary numbers bitnum1 = 4 bitnum2 = 4 # The abstract representattion of the binary numbers abs_num_1 = abstract_bin_num(bitnum1) abs_num_2 = abstract_bin_num(bitnum2) # cerating class of the multiplication table pq = multiplication_table(abs_num_1, abs_num_2) # determine the block sizes in the multiplcation table pq.determine_blocks(2) for col in range(0, bitnum1+bitnum2): pq.get_column_BQM_dict( col ) ####################################### # test for multiplication 11x13=143 # the target number target = 13*11#143 # creating the represantation of the target number target_num = bin_num( target ) print( 'bit length of the target number: ' + str(target_num.bit_length()) ) # creating the skeleton of the unknows factors num1 = abstract_bin_num(4) num2 = abstract_bin_num(4) # the first and last bit should be 1 num1.set_bit(0,1) num2.set_bit(0,1) #num1.set_bit(3,1) #num2.set_bit(3,1) # create a class to construct the BQM from the multiplication table cBQM = BQM_from_multiplication_table(num1, num2, target_num) # generating the blocks cBQM.determine_blocks(2) # sum up the quadratic terms in a given block >= 0 #block = 1 #cBQM.sum_up_block(block) # generate the (pq-**2 cost function for a given block cBQM.cost_function_of_block(0) update_cost_function = True cBQM.cost_function_of_block(1, update_cost_function) cBQM.cost_function_of_block(2, update_cost_function) cBQM.cost_function_of_block(3, update_cost_function) cBQM.cost_function_of_block(4, update_cost_function) # adding the substitution penalty functions to the (pq-n)**2 cost function cBQM.add_penalties_to_cost_function() # the binary representation of the targer number: print(' ') print('The target number: ' + str(target) +' = (' + str(bin(target)) + ')') # retrive the cost function and the constant term (BQM_model, constant) = cBQM.get_cost_function() ################################################## # Solving by QBsolv print('************************') print( 'Solving by QBsolv' ) from dwave_qbsolv import QBSolv # the response of QBsolve response = QBSolv().sample_qubo(BQM_model, num_repeats=1000) print("samples=" + str(list(response.samples()))) print("energies=" + str(list(response.data_vectors['energy']))) # obatin the QBsolv's result smpls = response.samples() res = dict( smpls[0] ) # the result of the lowest energy print(' ') print( 'The result of the QBsolv:') print(res) # Checking the substitutions print(' ') print('Checking the substitutions') substitutions = cBQM.get_substitutions() for item in substitutions.items(): vars = item[0] subs_var_value = res[vars[0]]*res[vars[1]] if subs_var_value == res[item[1]]: print(str(vars[0]) + '*' + str(vars[1]) + '==' + str(item[1]) + ': Passed') else: print(str(vars[0]) + '*' + str(vars[1]) + '==' + str(item[1]) + ': Failed') print(' ') # Check the energy of the result: the cost function including the constant part should be zero energies = response.data_vectors['energy'] if energies[0] + constant == 0: print( 'The lowest energy solution is: ' + str(energies[0]) ) else: print( 'Energy test failed!' ) # retriving the decimal form of the factors # get the bit labels of the abstract binary numbers bit_labels_num1 = num1.get_bit_labels() bit_labels_num2 = num2.get_bit_labels() for bit in range(num1.bit_length()): bit_label = bit_labels_num1[bit] if bit_label in res.keys(): num1.set_bit( bit, res[bit_label] ) for bit in range(num2.bit_length()): bit_label = bit_labels_num2[bit] if bit_label in res.keys(): num2.set_bit( bit, res[bit_label] ) print(num1.get_decimal()) print(num2.get_decimal()) #num1.define_bit(0,1) #num2.define_bit(0,1) #num1.define_bit(3,1) #num2.define_bit(3,1) quit() # Automated minor embedding print(' ') print( 'Automated minor embedding' ) from dwave.system.samplers import DWaveSampler from dwave.system.composites import EmbeddingComposite # Minor-embed and sample 1000 times on a default D-Wave system response = EmbeddingComposite(DWaveSampler()).sample_qubo(BQM_model, num_reads=10000, chain_strength=1000) print(response) print(response.data()) ''' for (sample, energy, num_occurrences, chain_break) in response.data(): #(sample, energy, num_occurrences, chain_break) = item print(sample, "Energy: ", energy, "Occurrences: ", num_occurrences) '''
import * as React from 'react' import Photo from './Photo' import styled from 'styled-components' const DisplaySearch = ({loading, photos})=>{ return( <DisplaySearchWrapper> <h2>Download high quality images for your next website or social media post.</h2> <div className="photos-center"> { Array.isArray(photos) && (photos.map((photo)=>{ return( <Photo key={photo.id} photo={photo}/> ) }) ) } </div> {loading && <h2 className="loading">Loading...</h2>} </DisplaySearchWrapper> ) } const DisplaySearchWrapper = styled.section` &{ padding 5rem 0; } h2{ font-size: 2rem; text-align: center; margin-bottom: 5rem; } .photos-center { width: 90vw; max-width: var(--max-width); margin: 0 auto; display: grid; gap: 2rem; } @media screen and (min-width: 576px) { .photos-center { grid-template-columns: repeat(auto-fill, minmax(368px, 1fr)); } .search-form { max-width: var(--fixed-width); } } .loading { text-align: center; padding: 3rem; } ` export default DisplaySearch
{ "targets": [ { "target_name": "moncoin-crypto", "defines": [ "NDEBUG", "NO_CRYPTO_EXPORTS", "FORCE_USE_HEAP", "NO_AES" ], "include_dirs": [ "include", "<!(node -e \"require('nan')\")", "external/argon2/include", "external/argon2/lib" ], "sources": [ "src/aesb.c", "src/blake256.c", "src/chacha8.cpp", "src/crypto.cpp", "src/crypto-ops.c", "src/crypto-ops-data.c", "src/groestl.c", "src/hash.c", "src/hash-extra-blake.c", "src/hash-extra-groestl.c", "src/hash-extra-jh.c", "src/hash-extra-skein.c", "src/jh.c", "src/keccak.c", "src/multisig.cpp", "src/oaes_lib.c", "src/random.cpp", "src/skein.c", "src/slow-hash-arm.c", "src/slow-hash-x86.c", "src/slow-hash-portable.c", "src/StringTools.cpp", "src/tree-hash.c", "external/argon2/lib/argon2.c", "external/argon2/arch/generic/lib/argon2-arch.c", "external/argon2/lib/core.c", "external/argon2/lib/encoding.c", "external/argon2/lib/genkat.c", "external/argon2/lib/impl-select.c", "external/argon2/lib/thread.c", "external/argon2/lib/blake2/blake2.c", "src/moncoin-crypto.cpp", "src/moncoin-crypto-node.cpp" ], "cflags!": [ "-std=c11", "-Wall", "-Wextra", "-Wpointer-arith", "-Wvla", "-Wwrite-strings", "-Wno-error=extra", "-Wno-error=unused-function", "-Wno-error=sign-compare", "-Wno-error=strict-aliasing", "-Wno-error=type-limits", "-Wno-error=unused-parameter", "-Wno-error=unused-variable", "-Wno-error=undef", "-Wno-error=uninitialized", "-Wno-error=unused-result", "-Wlogical-op", "-Wno-error=maybe-uninitialized", "-Wno-error=clobbered", "-Wno-error=unused-but-set-variable", "-Waggregate-return", "-Wnested-externs", "-Wold-style-definition", "-Wstrict-prototypes", "-fno-exceptions" ], "cflags_cc!": [ "-fno-exceptions" ], "cflags_cc": [ "-Wall", "-Wextra", "-Wpointer-arith", "-Wvla", "-Wwrite-strings", "-Wno-error=extra", "-Wno-error=unused-function", "-Wno-error=sign-compare", "-Wno-error=strict-aliasing", "-Wno-error=type-limits", "-Wno-unused-parameter", "-Wno-error=unused-variable", "-Wno-error=undef", "-Wno-error=uninitialized", "-Wno-error=unused-result", "-Wlogical-op", "-Wno-error=maybe-uninitialized", "-Wno-error=clobbered", "-Wno-error=unused-but-set-variable", "-Wno-reorder", "-Wno-missing-field-initializers", "-fexceptions" ], "conditions": [ [ 'OS=="mac"', { 'xcode_settings': { 'OTHER_CPLUSPLUSFLAGS': [ '-stdlib=libc++', '-fexceptions', ], 'CLANG_CXX_LIBRARY': 'libc++', 'CLANG_CXX_LANGUAGE_STANDARD':'c++17', 'MACOSX_DEPLOYMENT_TARGET': '10.7' } } ], [ "OS=='win'", { "include_dirs": [ "src/platform/msc" ], "configurations": { "Release": { "msvs_settings": { "VCCLCompilerTool": { "RuntimeLibrary": 0, "Optimization": 3, "FavorSizeOrSpeed": 1, "InlineFunctionExpansion": 2, "WholeProgramOptimization": "true", "OmitFramePointers": "true", "EnableFunctionLevelLinking": "true", "EnableIntrinsicFunctions": "true", "RuntimeTypeInfo": "false", "ExceptionHandling": "0", "AdditionalOptions": [ "/EHsc -D_WIN32_WINNT=0x0501 /bigobj /MP /W3 /D_CRT_SECURE_NO_WARNINGS /wd4996 /wd4345 /D_WIN32_WINNT=0x0600 /DWIN32_LEAN_AND_MEAN /DGTEST_HAS_TR1_TUPLE=0 /D_VARIADIC_MAX=8 /D__SSE4_1__" ] }, "VCLibrarianTool": { "AdditionalOptions": [ "/LTCG" ] }, "VCLinkerTool": { "LinkTimeCodeGeneration": 1, "OptimizeReferences": 2, "EnableCOMDATFolding": 2, "LinkIncremental": 1, "AdditionalLibraryDirectories": [] } } } } } ] ] } ] }
# encoding: utf-8 # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __version__ = "1.18" try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) def initVM(): ''' back compat method for JCC based Tika''' return
(this["webpackJsonpmicrofrontends-demo-container"]=this["webpackJsonpmicrofrontends-demo-container"]||[]).push([[0],{35:function(n,e,t){},61:function(n,e,t){"use strict";t.r(e);var o,r,c,a,i,d,b,s,j,l,p,x,u,O,h,g,f,m,v=t(2),w=t.n(v),y=t(24),k=t.n(y),S=t(25),z=(t(62),t(35),t(12)),L=t(29),I=t.n(L),B=(t(36),t(30),t(9)),P=t(19),R=t(4),U=t(5),A=t(3),E=U.a.button(o||(o=Object(R.a)(["\n background-color: #a4d22a;\n border: none;\n border-radius: 8px;\n color: white;\n cursor: pointer;\n font-size: 16px;\n font-weight: bold;\n outline: none;\n padding: 16px;\n text-transform: uppercase;\n\n :disabled {\n background-color: #ccc;\n }\n"]))),C=Object(U.a)(E)(r||(r=Object(R.a)(["\n background-color: transparent;\n color: #aaa;\n"]))),D=Object(U.a)(E)(c||(c=Object(R.a)(["\n box-shadow: 0px 5px 5px #888;\n"]))),F=function(n){var e=n.type,t=n.children,o=Object(P.a)(n,["type","children"]);switch(e){case"transparent":return Object(A.jsx)(C,Object(B.a)(Object(B.a)({},o),{},{children:t}));case"shadow":return Object(A.jsx)(D,Object(B.a)(Object(B.a)({},o),{},{children:t}));case"google-sign-in":return Object(A.jsx)(E,Object(B.a)(Object(B.a)({},o),{},{children:"Sign in with Google"}));default:return Object(A.jsx)(E,Object(B.a)(Object(B.a)({},o),{},{children:t}))}},J=U.a.hr(a||(a=Object(R.a)(["\n border-top: 1px solid #eee;\n margin: 0 16px;\n"]))),M=U.a.div(i||(i=Object(R.a)(["\n background-color: #ee7777;\n border-radius: 8px;\n color: #fff;\n padding: 16px;\n text-align: center;\n width: 100%;\n"]))),Q=U.a.h1(d||(d=Object(R.a)(["\n font-weight: bold;\n margin-top: 0px;\n padding-top: 16px;\n text-align: center;\n"]))),Z=U.a.h3(b||(b=Object(R.a)(["\n font-weight: bold;\n margin-top: 0px;\n margin-bottom: 0px;\n padding: 16px 0;\n border-bottom: 1px solid #eee;\n"]))),_=(Object(U.a)(F)(s||(s=Object(R.a)(["\n bottom: 32px;\n box-shadow: 0px 10px 10px #888;\n left: 50%;\n margin-left: -100px;\n position: fixed;\n"]))),U.a.div(j||(j=Object(R.a)(["\n background-color: #eee;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n overflow: auto;\n"]))),U.a.div(l||(l=Object(R.a)(["\n background-color: #fff;\n box-sizing: border-box;\n margin: 0 auto;\n max-width: 800px;\n min-height: 100vh;\n padding: 16px;\n"]))),U.a.input(p||(p=Object(R.a)(["\n border: 2px solid #ddd;\n border-radius: 8px;\n box-sizing: border-box;\n font-size: 16px;\n font-weight: bold;\n outline: none;\n padding: 16px;\n\n ::placeholder {\n color: #ddd;\n }\n"])))),q=function(n){var e=Object.assign({},n);return Object(A.jsx)(_,Object(B.a)({type:"text"},e))},G=U.a.div(x||(x=Object(R.a)(["\n background-color: #eee;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n overflow: auto;\n"]))),K=U.a.div(u||(u=Object(R.a)(["\n background-color: #fff;\n box-sizing: border-box;\n margin: 0 auto;\n max-width: 90%;\n min-height: 100vh;\n padding: 16px;\n"]))),N=function(n){var e=n.children;return Object(A.jsx)(G,{children:Object(A.jsx)(K,{children:e})})},T=U.a.div(O||(O=Object(R.a)(["\n position: relative;\n overflow: hidden;\n width: 100%;\n padding-top: 10px;\n height: 70vh;\n"]))),V=U.a.iframe(h||(h=Object(R.a)(["\n background-color: #eee;\n position: relative;\n top: 2%;\n left: 0;\n bottom: 0;\n right: 0;\n width: 100%;\n height: 100%;\n border: none;\n"]))),H=Object(U.a)(Z)(g||(g=Object(R.a)(["\n text-align: center;\n padding: 5px 0;\n"]))),W=function(n){var e=n.id,t=n.src,o=n.type,r=n.onLoad;return Object(A.jsxs)(T,{children:[Object(A.jsx)(H,{children:o}),Object(A.jsx)(V,{id:e,src:t,onLoad:r})]})},X=U.a.div(f||(f=Object(R.a)(["\n display: flex;\n justify-content: center;\n"]))),Y=U.a.div(m||(m=Object(R.a)(["\n align-content: center;\n box-sizing: border-box;\n display: flex;\n justify-content: center;\n width: 100%;\n padding: 16px;\n"]))),$=function(){var n=Object(v.useState)(""),e=Object(z.a)(n,2),t=e[0],o=e[1],r=Object(v.useState)(""),c=Object(z.a)(r,2),a=c[0],i=c[1],d=Object(v.useState)(null),b=Object(z.a)(d,2),s=b[0],j=b[1],l=Object(v.useState)(!1),p=Object(z.a)(l,2),x=(p[0],p[1]),u=Object(v.useState)(!1),O=Object(z.a)(u,2),h=(O[0],O[1]);return Object(A.jsxs)(N,{children:[Object(A.jsx)(Q,{children:"Micro-Frontends Demo"}),Object(A.jsxs)(Y,{children:[Object(A.jsx)(q,{placeholder:"Lesson Presentation URL",style:{flex:5,marginRight:"8px"},value:t,onChange:function(n){return o(n.target.value)}}),Object(A.jsx)(F,{onClick:function(){var n=t.includes("localhost")?{require_tld:!1}:{};I()(t,n)?(x(!0),h(!0),i(t),j(null)):j("Please input correct lesson presentation URL")},style:{flex:2},children:"Load Presentation"})]}),s?Object(A.jsx)(M,{children:s}):null,Object(A.jsx)(J,{}),a?Object(A.jsxs)(X,{children:[Object(A.jsx)(W,{id:"teacheriframe",src:a,type:"Teacher",onLoad:function(){return x(!1)}}),Object(A.jsx)(W,{id:"studentiframe",src:a,type:"Student",onLoad:function(){return h(!1)}})]}):Object(A.jsx)(X,{children:Object(A.jsx)(Z,{children:"Please input lesson presentation URL"})})]})};S.a.initializeApp({apiKey:"AIzaSyBFumNuinkzsQtVtbg2ZEZbgUIQo_Bv7AE",authDomain:"microfrontends-1bd03.firebaseapp.com",projectId:"microfrontends-1bd03",storageBucket:"microfrontends-1bd03.appspot.com",messagingSenderId:"205696778254",appId:"1:205696778254:web:628bfcc791e02b9e01bc5f"}),k.a.render(Object(A.jsx)(w.a.StrictMode,{children:Object(A.jsx)($,{})}),document.getElementById("root"))}},[[61,1,2]]]); //# sourceMappingURL=main.05350148.chunk.js.map
import { formatRecordToString } from 'nightingale-formatter'; export function style(styles, string) { return string; } /** * @param {Object} record * @returns {string} */ export default function format(record) { return formatRecordToString(record, style); } // export style function format.style = style;
import {requestDb} from '../../shared/utils/db' export function createProfileDb(epoch) { const requestProfileDb = () => global.sub(requestDb(), 'profile') const planNextValidationkey = `didPlanNextValidation!!${epoch?.epoch ?? -1}` return { getDidPlanNextValidation() { return requestProfileDb().get(planNextValidationkey) }, putDidPlanNextValidation(value) { return requestProfileDb().put(planNextValidationkey, value) }, getDidShowValidationResults() { return requestProfileDb().get(`didShowValidationResults!!${epoch?.epoch}`) }, putDidShowValidationResults() { return requestProfileDb().put( `didShowValidationResults!!${epoch?.epoch}`, 1 ) }, clear() { return requestProfileDb().clear() }, } }
import routes from "./../../../routes" import { combinePathRoutes } from "./../../../../../helpers" import * as dialogRoute from "./dialog" export const basePath = routes.aptitudeSkillList.path export const dialogRoutes = combinePathRoutes({ path: basePath }, dialogRoute)
var _marked = /*#__PURE__*/ regeneratorRuntime.mark(test1), _marked2 = /*#__PURE__*/ regeneratorRuntime.mark(test2); function test1() { return regeneratorRuntime.wrap(function test1$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return Object.defineProperty(foo(1, 2, 3), Symbol.for("@@redux-saga/LOCATION"), { value: { fileName: "preset-env/source.js", lineNumber: 2, code: "foo(1, 2, 3)" } }); case 2: case "end": return _context.stop(); } } }, _marked, this); } Object.defineProperty(test1, Symbol.for("@@redux-saga/LOCATION"), { value: { fileName: "preset-env/source.js", lineNumber: 1, code: null } }) function test2() { return regeneratorRuntime.wrap(function test2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return 2; case 2: case "end": return _context2.stop(); } } }, _marked2, this); } Object.defineProperty(test2, Symbol.for("@@redux-saga/LOCATION"), { value: { fileName: "preset-env/source.js", lineNumber: 5, code: null } })
import styled from "styled-components"; import Link from "next/link"; const HeaderWrap = styled.header` margin-bottom: 10rem; `; const HeaderLink = styled.div` float: left; position: relative; z-index: 1; margin-right: 2.5rem; &:hover .pt { transform: translateY(0.6rem); } &:hover .pb { transform: translateY(-0.6rem); } `; const HeaderColumn = styled.div` display: block; // max-width: 84rem; margin: 0 auto; padding: 1.6rem 0; `; const HeaderLabel = styled.div` display: inline-block; font-family: ${(props) => props.theme.fonts.monospace}; font-size: ${(props) => props.theme.fontSizes[0]}; background: var(--text-link); color: var(--bg-secondary); padding: 0.1rem 0.7rem; border-radius: ${(props) => props.theme.radii}; opacity: 0.7; `; const Path = styled.path` transition: ${(props) => props.theme.animation}; `; export default function Header() { return ( <HeaderWrap> <HeaderLink> <Link href="/"> <a> <svg className="logo" width="44" height="60" viewBox="0 0 56 67" fill="none" xmlns="http://www.w3.org/2000/svg" alt="mamuso.dev" style={{ backgroundColor: "var(--bg-primary)" }}> <Path className="pt" d="M37.276 45.752C37.2974 45.7591 37.3188 45.7663 37.3403 45.7735C46.6806 48.8965 55.6719 49.22 55.6719 49.22C55.6719 49.22 57.7892 29.8228 51.2671 17.4271C44.745 5.03129 30.0982 0 30.0982 0C30.0982 0 -0.443344 9.04381 0.00488585 26.2813C0.453115 43.5189 12.0332 51.942 12.0332 51.942C12.0332 51.942 14.8572 49.22 18.7567 45.5765C18.8198 45.5175 18.8825 45.4589 18.9448 45.4006C19.2244 45.7139 19.5105 46.0176 19.8031 46.3101C25.828 52.3341 33.0165 54.8493 33.0165 54.8493L37.276 45.752Z" fill="url(#paint0_linear)" /> <g style={{ mixBlendMode: "multiply", transform: "translateZ(0px)" }}> <Path className="pb" d="M37.276 57.752C37.2974 57.7591 37.3188 57.7663 37.3403 57.7735C46.6806 60.8965 55.6719 61.22 55.6719 61.22C55.6719 61.22 57.7892 41.8228 51.2671 29.4271C44.745 17.0313 30.0982 12 30.0982 12C30.0982 12 -0.443344 21.0438 0.00488585 38.2813C0.453115 55.5189 12.0332 63.942 12.0332 63.942C12.0332 63.942 14.8572 61.22 18.7567 57.5765C18.8198 57.5175 18.8825 57.4589 18.9448 57.4006C19.2244 57.7139 19.5105 58.0176 19.8031 58.3101C25.828 64.3341 33.0165 66.8493 33.0165 66.8493L37.276 57.752Z" fill="url(#paint1_linear)" /> </g> <defs> <linearGradient id="paint0_linear" x1="28" y1="-8.17319e-07" x2="0.918546" y2="55.2992" gradientUnits="userSpaceOnUse"> <stop offset="0.326" stopColor="#D80D5C" /> <stop offset="1" stopColor="#FF005E" /> </linearGradient> <linearGradient id="paint1_linear" x1="28" y1="12" x2="0.918546" y2="67.2992" gradientUnits="userSpaceOnUse"> <stop offset="0.265193" stopColor="#5A9AFE" /> <stop offset="1" stopColor="#85C6FE" /> </linearGradient> </defs> </svg> </a> </Link> </HeaderLink> <HeaderColumn> <HeaderLabel>changelog</HeaderLabel> </HeaderColumn> </HeaderWrap> ); }
'use strict' const getURL = '/https/example.com/example.json.json' const apiURL = 'http://online.swagger.io' const apiGetURL = '/validator/debug' const apiGetQueryParams = { url: 'https://example.com/example.json' } const t = (module.exports = require('../tester').createServiceTester()) t.create('Valid (mocked)') .get(getURL) .intercept(nock => nock(apiURL) .get(apiGetURL) .query(apiGetQueryParams) .reply(200, {}) ) .expectBadge({ label: 'swagger', message: 'valid', color: 'brightgreen', }) t.create('Invalid (mocked)') .get(getURL) .intercept(nock => nock(apiURL) .get(apiGetURL) .query(apiGetQueryParams) .reply(200, { schemaValidationMessages: [ { level: 'error', message: 'error', }, ], }) ) .expectBadge({ label: 'swagger', message: 'invalid', color: 'red', })
const { version } = require('../package.json'); const filterQueryParser = (filterQuery) => { const conditions = filterQuery.match(/\(([^\(\)]*?)\)/g); let filter = {}; conditions.map((c) => { const m = c.match(/\(type=="(.*?)"(&&|\|\|)(.*?)(<|>)(.*)\)/); if (m) { const type = m[1]; const operator = m[2]; const key = m[3]; const comp = m[4]; const value = m[5]; if (!filter[type]) { filter[type] = {}; } if (operator === "&&") { if (!filter[type][key]) { filter[type][key] = {}; } if (comp === "<") { filter[type][key].high = parseInt(value, 10); } else if (comp === ">") { filter[type][key].low = parseInt(value, 10); } } } }); return filter; }; const applyFilter = (profiles, filter) => { return profiles.filter(profile => { if (filter.video && filter.video.systemBitrate) { return (profile.bw >= filter.video.systemBitrate.low && profile.bw <= filter.video.systemBitrate.high); } else if (filter.video && filter.video.height) { return (profile.resolution[1] >= filter.video.height.low && profile.resolution[1] <= filter.video.height.high); } return true; }); }; const cloudWatchLog = (silent, type, logEntry) => { if (!silent) { logEntry.type = type; logEntry.time = (new Date()).toISOString(); console.log(JSON.stringify(logEntry)); } }; const m3u8Header = (instanceId) => { let m3u8 = ""; m3u8 += `## Created with Eyevinn Channel Engine library (version=${version}${instanceId ? "<" + instanceId + ">" : "" })\n`; m3u8 += "## https://www.npmjs.com/package/eyevinn-channel-engine\n"; return m3u8; }; const toHHMMSS = (secs) => { var sec_num = parseInt(secs, 10) var hours = Math.floor(sec_num / 3600) var minutes = Math.floor(sec_num / 60) % 60 var seconds = sec_num % 60 return [hours,minutes,seconds] .map(v => v < 10 ? "0" + v : v) .join(":") }; const logerror = (sessionId, err) => { console.error(`ERROR [${sessionId}]:`); console.error(err); }; module.exports = { filterQueryParser, applyFilter, cloudWatchLog, m3u8Header, toHHMMSS, logerror }
/** * Core UI functions are initialized in this file. This prevents * unexpected errors from breaking the core features. Specifically, * actions in this file should not require the usage of any internal * modules, excluding dependencies. */ // Requirements const $ = require('jquery') const {ipcRenderer, shell, webFrame} = require('electron') const remote = require('@electron/remote') const isDev = require('./assets/js/isdev') const LoggerUtil = require('./assets/js/loggerutil') const loggerUICore = LoggerUtil('%c[UICore]', 'color: #000668; font-weight: bold') const loggerAutoUpdater = LoggerUtil('%c[AutoUpdater]', 'color: #000668; font-weight: bold') const loggerAutoUpdaterSuccess = LoggerUtil('%c[AutoUpdater]', 'color: #209b07; font-weight: bold') // Log deprecation and process warnings. process.traceProcessWarnings = true process.traceDeprecation = true // Disable eval function. // eslint-disable-next-line window.eval = global.eval = function () { throw new Error('Sorry, this app does not support window.eval().') } // Display warning when devtools window is opened. remote.getCurrentWebContents().on('devtools-opened', () => { console.log('%cIf you\'ve been told to paste something here, you\'re being scammed.', 'font-size: 5px') console.log('%cUnless you know exactly what you\'re doing, close this window.', 'font-size: 5px') }) // Disable zoom, needed for darwin. webFrame.setZoomLevel(0) webFrame.setVisualZoomLevelLimits(1, 1) // Initialize auto updates in production environments. let updateCheckListener if(!isDev){ ipcRenderer.on('autoUpdateNotification', (event, arg, info) => { switch(arg){ case 'checking-for-update': loggerAutoUpdater.log('Checking for update..') settingsUpdateButtonStatus('Checking for Updates..', true) break case 'update-available': loggerAutoUpdaterSuccess.log('New update available', info.version) if(process.platform === 'darwin'){ info.darwindownload = `https://github.com/ModRealms-Network/HeliosLauncher/releases/download/v${info.version}/ModRealms-Launcher-setup-${info.version}.dmg` showUpdateUI(info) } populateSettingsUpdateInformation(info) break case 'update-downloaded': loggerAutoUpdaterSuccess.log('Update ' + info.version + ' ready to be installed.') settingsUpdateButtonStatus('Install Now', false, () => { if(!isDev){ ipcRenderer.send('autoUpdateAction', 'installUpdateNow') } }) showUpdateUI(info) break case 'update-not-available': loggerAutoUpdater.log('No new update found.') settingsUpdateButtonStatus('Check for Updates') break case 'ready': updateCheckListener = setInterval(() => { ipcRenderer.send('autoUpdateAction', 'checkForUpdate') }, 1800000) ipcRenderer.send('autoUpdateAction', 'checkForUpdate') break case 'realerror': if(info != null && info.code != null){ if(info.code === 'ERR_UPDATER_INVALID_RELEASE_FEED'){ loggerAutoUpdater.log('No suitable releases found.') } else if(info.code === 'ERR_XML_MISSED_ELEMENT'){ loggerAutoUpdater.log('No releases found.') } else { loggerAutoUpdater.error('Error during update check..', info) loggerAutoUpdater.debug('Error Code:', info.code) } } break default: loggerAutoUpdater.log('Unknown argument', arg) break } }) } /** * Send a notification to the main process changing the value of * allowPrerelease. If we are running a prerelease version, then * this will always be set to true, regardless of the current value * of val. * * @param {boolean} val The new allow prerelease value. */ function changeAllowPrerelease(val){ ipcRenderer.send('autoUpdateAction', 'allowPrereleaseChange', val) } function showUpdateUI(info){ //TODO Make this message a bit more informative `${info.version}` document.getElementById('image_seal_container').setAttribute('update', true) document.getElementById('image_seal_container').onclick = () => { /*setOverlayContent('Update Available', 'A new update for the launcher is available. Would you like to install now?', 'Install', 'Later') setOverlayHandler(() => { if(!isDev){ ipcRenderer.send('autoUpdateAction', 'installUpdateNow') } else { console.error('Cannot install updates in development environment.') toggleOverlay(false) } }) setDismissHandler(() => { toggleOverlay(false) }) toggleOverlay(true, true)*/ switchView(getCurrentView(), VIEWS.settings, 250, 250, () => { settingsNavItemListener(document.getElementById('settingsNavUpdate'), false) }) } } /* jQuery Example $(function(){ loggerUICore.log('UICore Initialized'); })*/ document.addEventListener('readystatechange', function () { if (document.readyState === 'interactive'){ loggerUICore.log('UICore Initializing..') // Bind close button. Array.from(document.getElementsByClassName('fCb')).map((val) => { val.addEventListener('click', e => { const window = remote.getCurrentWindow() //window.close() window.destroy() }) }) // Bind restore down button. Array.from(document.getElementsByClassName('fRb')).map((val) => { val.addEventListener('click', e => { const window = remote.getCurrentWindow() if(window.isMaximized()){ window.unmaximize() } else { window.maximize() } document.activeElement.blur() }) }) // Bind minimize button. Array.from(document.getElementsByClassName('fMb')).map((val) => { val.addEventListener('click', e => { const window = remote.getCurrentWindow() window.minimize() document.activeElement.blur() }) }) // Remove focus from social media buttons once they're clicked. Array.from(document.getElementsByClassName('mediaURL')).map(val => { val.addEventListener('click', e => { document.activeElement.blur() }) }) } else if(document.readyState === 'complete'){ //266.01 //170.8 //53.21 // Bind progress bar length to length of bot wrapper //const targetWidth = document.getElementById("launch_content").getBoundingClientRect().width //const targetWidth2 = document.getElementById("server_selection").getBoundingClientRect().width //const targetWidth3 = document.getElementById("launch_button").getBoundingClientRect().width document.getElementById('launch_details').style.maxWidth = 266.01 document.getElementById('launch_progress').style.width = 170.8 document.getElementById('launch_details_right').style.maxWidth = 170.8 document.getElementById('launch_progress_label').style.width = 53.21 } }, false) /** * Open web links in the user's default browser. */ $(document).on('click', 'a[href^="http"]', function(event) { event.preventDefault() shell.openExternal(this.href) }) /** * Opens DevTools window if you hold (ctrl + shift + i). * This will crash the program if you are using multiple * DevTools, for example the chrome debugger in VS Code. */ document.addEventListener('keydown', function (e) { if((e.key === 'I' || e.key === 'i') && e.ctrlKey && e.shiftKey){ let window = remote.getCurrentWindow() window.toggleDevTools() } })
var Properties = { "modem.js" : { device : { type : String, label : "Device"}, number : { type : String, label : "Number"} }, "kannel.js":{ host : { type : String, label : "Kannel Host", help : "Defaut : 127.0.0.1", default : "127.0.0.1" }, port : { type: String , label : "Kannel Port", help : "Defaut : 13001", default : 13001}, id : { type: String, label : "Identifiant de la smsbox", help : "Defaut : LoveIsMyReligion", default : "LoveIsMyReligion" }, tls : {type : Boolean, label :'Secure',default: false, inputType : 'checkbox'} }, "shorty.js" : { "mode" : {type : String, label :"Mode",default:"transceiver", help : "Defaut : transceiver"}, "host" : { type : String, label : "Host", help : "Defaut : 127.0.0.1", default : "127.0.0.1" }, "port" : { type: String , label : "Port", help : "Defaut : 2775", default : 2775}, "system_id": { type: String, label : "Identifiant", help : "Defaut : username", default : "username" }, "password": { type: String, label : "Password", help : "Defaut : password", default : "password" }, "system_type": { type: String, label : "Type", help : "Defaut : SMPP", default : "SMPP" }, "addr_ton": { type: Number, label : "TON", help : "Defaut : 0", default : "0" }, "addr_npi": { type: Number, label : "NPI", help : "Defaut : 1", default : 1 }, "addr_range": { type: String, label : "RANGE", help : "Defaut : **Empty**", default : "" }, "timeout": { type: Number, label : "Timeout", help : "Defaut : 30", default : 30 }, "client_keepalive": {type : Boolean, label :'Keepalive',default: false, inputType : 'checkbox'}, "client_reconnect_interval": { type: Number, label : "Reconnection", help : "Defaut : 2500", default : 2500 }, "strict": {type : Boolean, label :'Strict',default: true, inputType : 'checkbox'} }, "smpp.js" : { "host" : { type : String, label : "Host", help : "Defaut : 127.0.0.1", default : "127.0.0.1" }, "port" : { type: String , label : "Port", help : "Defaut : 2775", default : 2775}, "system_id": { type: String, label : "Identifiant", help : "Defaut : username", default : "username" }, "password": { type: String, label : "Password", help : "Defaut : password", default : "password" } } } module.exports = function(app,dir){ var hidden = {id:1,conf : 1,}, readOnly={id:1,name:1}, liens = { "connector.list" : "Liste des Connectors" }; app.route(/^\/connector\.json(\/([^\/]+)?)?$/i) .get(function(req,res,next){ var id = req.params[1] || false; Models.Connector[ id ? 'findById' : 'find' ](id? id : {},function(err,connectors){ if(err || !connectors) return res.json({success:false, message : err.message}); res.json({success : true, data: (connectors.length ? connectors.map(function(item){ return { value : item.num , text: "["+item.num + "] " +item.desc}}) : connectors),message:"Requete Ok"}) }) }) app.route("/connector.list") .get(function(req,res,next){ if(! ("connector" in req.user.droits)){ res.status(403); return res.render("page-error",{error : {code:403, message : "Acces interdit"}}); } var heads = {}, checkbox = {}, listes = {}, listValues = {}; for(var i in Models.Connector.properties){ if(Models.Connector.properties[i].label) heads[i] = Models.Connector.properties[i].label; if(Models.Connector.properties[i].inputType == 'checkbox') checkbox[i] = 1; else if(Models.Connector.properties[i].list) listes[i] = Models.Connector.properties[i].list; else if(Models.Connector.properties[i].data) listValues[i] = Models.Connector.properties[i].data; } Models.Connector.find({},function(err,items){ if(err) return next(err); res.render("build-resposive-table",{ hidden : hidden, listValues : listValues,fields : heads,title:"Liste des connectors",data : items, checkboxs : checkbox, listes : listes,getActions : function(j,user){ if(!(j.name in VMs)) initVMs(j); return (VMs[j.name].online ? '<a title="Stop server" href="'+dir+'/connector.stop/'+j.name+'" class="btn btn-dark btn-sm"><i class="fa fa-stop"></i> Stop Server</a> ' : '<a title="Start server" href="'+dir+'/connector.start/'+j.name+'" class="btn btn-success btn-sm"><i class="fa fa-play"></i> Start Server</a> ' )+ '<a title="Edit" href="'+dir+'/connector.info/'+j.id+'" class="btn btn-blue btn-sm"><i class="fa fa-edit"></i></a> '+ '<a id="user-remove-'+j.id+'" title="Effacer" href="javascript:exec(\'/admin/connector.remove/'+j.id+'\',\'{1}\',\'Error : {1}\',\'#user-remove-'+j.id+'\')" class="btn btn-red btn-sm"><i class="fa fa-trash-o"></i></a>'; } }); }) }) app.get(/^\/connector.stop\/(.*)$/i,function(req,res){ if(! ("connector" in req.user.droits)){ res.status(403); return res.render("page-error",{error : {code:403, message : "Acces interdit"}}); } if(!(req.params[0] && req.params[0] in VMs)){ res.status(404); return res.render("page-error",{error : {code:404, message : "VM not Found"}}); } VMs[req.params[0]].send("stop"); return res.redirect(dir+"/connector.list"); }); app.get(/^\/connector.start\/(.*)$/i,function(req,res){ if(! ("connector" in req.user.droits)){ res.status(403); return res.render("page-error",{error : {code:403, message : "Acces interdit"}}); } if(!(req.params[0] && req.params[0] in VMs)){ res.status(404); return res.render("page-error",{error : {code:404, message : "VM not Found"}}); } VMs[req.params[0]].send({type:"start",data:VMs[req.params[0]].item.conf}); return res.redirect(dir+"/connector.list"); }); app.route("/connector.add") .all(function(req,res,next){ if(!("connector" in req.user.droits)) return res.redirect(dir+"/connector.list"); next(); }) .get(function(req,res){ var update = {}, hidden = {id:1,conf:1}; for(var cle in Models.Connector.properties){ if(readOnly[cle] || (!req.user.isAdmin && Models.Connector[cle] && Models.Connector[cle].needAdmin) ) continue; if(Models.Connector.properties[cle].default) update[cle] = Models.Connector.properties[cle].default; } res.render("build-form",{hidden:hidden,readOnly:{id:1},fields : Models.Connector.properties,title:"Ajouter un connector",data : update}); }).post(function(req,res,next){ var readOnly = {id:1}, update = { }; for(var cle in Models.Connector.properties){ if(readOnly[cle] || (!req.user.isAdmin && Models.Connector[cle] && Models.Connector[cle].needAdmin) ) continue; if(Models.Connector.properties[cle].type == Boolean) update[cle] = false; if( req.body[cle] ){ if(Models.Connector.properties[cle].type == Boolean) update[cle] = (req.body[cle] == 'true' || req.body[cle] == 'on' || req.body[cle] == 1); else if(Models.Connector.properties[cle].data){ var tmp = {}; for(var i in Models.Connector.properties[cle].data) if(req.body[cle] && req.body[cle].indexOf && req.body[cle].indexOf(i) != -1 ) tmp[i] = 1; update[cle] = tmp; }else update[cle] = req.body[cle] } } Models.Connector.findOne({ where : {name : update.name }}, function(err,connector){ if(err) return next(err); if(connector){ res.status(403); return res.render("page-error",{error : {code:403, message : "Le Connector "+req.body.name+" Existe deja"}}); } new Models.Connector(update).save(function(err,connector){ if(err) return next(err); initVMs(connector); res.redirect(dir+"/connector.info/"+connector.id); }) }); }) app.route(/^\/connector\.info\/([^\/]+)?$/i) .all(function(req,res,next){ if(!("connector" in req.user.droits)) return req.redirect(dir+"/connector.list"); next(); }) .get(function(req,res,next){ var id = req.params[0] || false; if(!id) return req.redirect(dir+"/connector.list"); Models.Connector.findById(id, function(err, connector){ if(err) return next(err); if(connector){ var update = {}, hidden = {}; var properties = Properties[connector.type]; if(!properties){ res.status(403); return res.render("page-error",{error:{ code:404, message:"Connecteur invalide!!!"}}); } var readOnly = {}; var data = connector.conf || {}; for(var cle in properties){ if((properties[cle] && properties[cle].readOnly) || (!req.user.isAdmin && properties[cle] && properties[cle].needAdmin) ) readOnly[cle] = 1; else if(properties[cle] && properties[cle].hidden) hidden[cle] = 1; if(properties[cle].default) data[cle] == data[cle] || properties[cle].default; } res.render("build-form",{liens:liens,hidden : hidden,readOnly : readOnly,fields : properties,title:"Configurer le Connector : "+connector.name,data : data}); }else res.redirect(dir+"/connector.list"); }); }).post(function(req,res,next){ var id = req.params[0] || false; if(!id) return req.redirect(dir+"/connector.list") var readOnly = {}, update = {id:id}; Models.Connector.findById(update.id , function(err,connector){ if(err) return next(err); if(!connector){ res.status(404); return res.render("page-error",{error:{ code:404, message:"Connector Not found"}}); } var properties = Properties[connector.type]; if(!properties){ res.status(403); return res.render("page-error",{error:{ code:404, message:"Connector invalide!!!"}}); } for(var cle in properties){ if(readOnly[cle] || (!req.user.isAdmin && properties[cle] && properties[cle].needAdmin) ){ update[cle] = connector.conf[cle] || properties[cle].default; continue; } if(properties[cle].default && !req.body[cle]) req.body[cle] = properties[cle].default; if(properties[cle].type == Boolean) update[cle] = properties[cle].default ? properties[cle].default : false; if( req.body[cle] ){ if(properties[cle].type == Boolean) update[cle] = (req.body[cle] == 'true' || req.body[cle] == 'on' || req.body[cle] == 1); else if(properties[cle].data){ var tmp = {}; for(var i in properties[cle].data) if(req.body[cle] && req.body[cle].indexOf && req.body[cle].indexOf(i) != -1 ) tmp[i] = 1; update[cle] = tmp; }else update[cle] = req.body[cle]; } } var conf = {} for(var cle in update) conf[cle] = update[cle]; connector.conf = conf; connector.save(function(err,connector){ if(err) return next(err); if(connector.name in VMs) VMs[connector.name].item = connector; else initVMs(connector); res.redirect(dir+"/connector.info/"+connector.id); }) }); }); app.route(/^\/connector\.remove\/([^\/]+)$/i) .all(function(req,res,next){ if(!("connector" in req.user.droits)) return req.redirect(dir+"/connector.list"); next(); }) .get(function(req,res,next){ var id = req.params[0] || false; if(!id) return req.redirect(dir+"/connector.list"); Models.Connector.findById(id, function(err,connector){ if(err) return next(err); if(!connector){ res.status(404); return res.render("page-error",{error:{ code:404, message:"Connector Not found"}}); } Models.Connector.remove({where : {id : req.params[0] }},function(err){ if(err) return next(err); // console.log(arguments); if(connector.name in VMs) try{ VMs[connector.name].kill(); delete VMs[connector.name]; }catch(e){} res.json({success : true, message : 'Connector effacé'}); }); }); }); }
const initStateDashboard = { data: null, loading: false, error: null, }; export default initStateDashboard;
''' zstack snapshot test class @author: Youyk ''' import zstackwoodpecker.header.snapshot as sp_header import zstackwoodpecker.header.vm as vm_header import zstackwoodpecker.header.volume as volume_header import zstackwoodpecker.header.image as image_header import zstackwoodpecker.operations.volume_operations as vol_ops import zstackwoodpecker.operations.resource_operations as res_ops import zstackwoodpecker.operations.image_operations as img_ops import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import uuid checking_point_folder = '%s/checking_point' % test_lib.WOODPECKER_MOUNT_POINT def is_ancestry(snapshot1, snapshot2): ''' Return True, if snapshot2 is snapshot1's ancestry ''' parent = snapshot1.get_parent() while parent: if parent == snapshot2: return True parent = parent.get_parent() def get_snapshot_family(snapshot): sp_list = [snapshot] if not snapshot.get_child_list(): return sp_list for sp in snapshot.get_child_list(): sp_list.extend(get_snapshot_family(sp)) return sp_list def get_all_ancestry(snapshot): ''' Return ancestry chain ''' snapshot_chain = [snapshot] parent = snapshot.get_parent() if parent: snapshot_chain.extend(get_all_ancestry(parent)) return snapshot_chain def print_snapshot_chain_checking_point(snapshot_chain): checking_point_chain = ['Snapshot Chain Checking Point List:'] num = 1 for sp in snapshot_chain: name = sp.get_snapshot().name uuid = sp.get_snapshot().uuid checking_point = sp.get_checking_point() checking_point_info = '\t[%s]: [snapshot:]%s [uuid:]%s\ [checking_point:] %s' % (num, name, uuid, checking_point) checking_point_chain.append(checking_point_info) num += 1 print_info = '\n'.join(checking_point_chain) test_util.test_logger(print_info) return print_info class ZstackVolumeSnapshot(object): ''' Ideally ZstackVolumeSnapshot should inherit from ZstackTestVolume, since all snapshot operations are just belonged to a Volume actions. And it will be easy to remove self.utiltiy_vm . But the only issue is, when Volume is deleted, snapshots structure might be still exist, if there is any snapshot in backuped stage. So Volume.delete() might be not remove this object. Then we can't just inherit ZstackTestVolume class. ''' def __init__(self): self.current_snapshot = None self.snapshot_head = None #The header of snapshot tree self.target_volume = None self.utility_vm = None self.snapshot_list = [] self.original_checking_points = [] self.state = None self.primary_snapshots = [] self.backuped_snapshots = [] self.volume_type = None #Root volume or data volume def __repr__(self): if self.target_volume and self.target_volume.get_volume(): return '%s-for-volume-%s' % (self.__class__.__name__, self.target_volume.get_volume().uuid) return '%s-None' % self.__class__.__name__ def set_volume_type(self, volume_type): self.volume_type = volume_type def get_volume_type(self): return self.volume_type def get_checking_points(self, snapshot): parents_snapshots = get_all_ancestry(snapshot) checking_points_list =[] for checking_snapshot in parents_snapshots: checking_points_list.append('%s' % \ checking_snapshot.get_checking_point()) original_checking_points = self.get_original_checking_points() checking_points_list.extend(original_checking_points) return checking_points_list def set_original_checking_points(self, original_checking_points): ''' The volume is created from template, while the template was generated by another snapshot. So need to add previous snapshot's checking points. This function will automatically called when add_volume() is called. So tester doesn't need to call it, unless there are some additional checking points, which is not generated from snapshot uuid function. ''' self.original_checking_points = original_checking_points def get_original_checking_points(self): return self.original_checking_points def get_snapshot_list(self): return self.snapshot_list def set_utility_vm(self, utility_vm): self.utility_vm = utility_vm def get_utility_vm(self): return self.utility_vm def set_target_volume(self, target_volume): self.target_volume = target_volume self.set_original_checking_points(target_volume.get_original_checking_points()) if target_volume.get_volume().type == volume_header.ROOT_VOLUME: self.set_volume_type(volume_header.ROOT_VOLUME) else: self.set_volume_type(volume_header.DATA_VOLUME) def get_target_volume(self): return self.target_volume def get_current_snapshot(self): return self.current_snapshot def get_snapshot_head(self): return self.snapshot_head def _remove_checking_file(self): import tempfile with tempfile.NamedTemporaryFile() as script: script.write(''' device=/dev/`ls -ltr --file-type /dev | grep disk | awk '{print $NF}' | grep -v '[[:digit:]]' | tail -1`1 mkdir -p %s mount $device %s || exit 1 /bin/rm -rf %s umount %s ''' % (test_lib.WOODPECKER_MOUNT_POINT, \ test_lib.WOODPECKER_MOUNT_POINT, \ checking_point_folder, \ test_lib.WOODPECKER_MOUNT_POINT)) script.flush() if not test_lib.lib_execute_shell_script_in_vm(\ self.utility_vm.get_vm(), script.name): test_util.test_logger('cleanup checking point failed. It might be because there is not any partition in the target volume. It is harmless.') def _cleanup_previous_checking_point(self): if not self.get_utility_vm(): return if not self.get_target_volume(): return test_util.test_logger('cleanup checking point files for target volume: %s' % self.get_target_volume()) volume_obj = self.get_target_volume() volume = volume_obj.get_volume() if volume.type == 'Root': test_util.test_logger('Can not add checking point file for Root Volume: %s, since it can not be detached and reattached to utility vm for checking.' % volume.uuid) return volume_vm = volume_obj.get_target_vm() #check if volume has been attached to the living VM. if volume_obj.get_state() == volume_header.ATTACHED: if volume_vm.get_state() == vm_header.STOPPED or \ volume_vm.get_state() == vm_header.RUNNING: #test_util.test_logger('volume has been attached to living VM.') volume_obj.detach() volume_obj.attach(self.utility_vm) self._remove_checking_file() volume_obj.detach() volume_obj.attach(volume_vm) return volume_obj.attach(self.utility_vm) self._remove_checking_file() volume_obj.detach() def create_snapshot(self, name = None): if not self.target_volume: test_util.test_fail( 'Can not create snapshot, before set target_volume') if not self.utility_vm: test_util.test_fail( 'Can not create snapshot, before set utility_vm, which will be used for doing \ snapshot checking.') sp_option = test_util.SnapshotOption() sp_option.set_name(name) sp_option.set_volume_uuid(self.target_volume.get_volume().uuid) snapshot = ZstackTestSnapshot() snapshot.set_snapshot_creation_option(sp_option) snapshot.set_utility_vm(self.utility_vm) snapshot.set_target_volume(self.target_volume) snapshot.create() self.add_snapshot(snapshot) return snapshot def use_snapshot(self, snapshot): if self.target_volume.get_state() == volume_header.DELETED \ or self.target_volume.get_state() == volume_header.EXPUNGED: test_util.test_fail( 'Can not use [snapshot:] %s, as [target_volume:] %s is deleted' \ % (snapshot.get_snapshot().uuid, \ self.target_volume.get_volume().uuid)) self.current_snapshot = snapshot snapshot.use() def add_snapshot(self, snapshot): ''' Called by self.create() or called by test case after manually create ZstackTestSnapshot() ''' self.snapshot_list.append(snapshot) self.primary_snapshots.append(snapshot) if not self.state: self.state = sp_header.CREATED if not self.snapshot_head: self.current_snapshot = snapshot self.snapshot_head = snapshot snapshot.set_checking_points(self.get_checking_points(snapshot)) return snapshot.set_parent(self.current_snapshot) self.current_snapshot.add_child(snapshot) self.current_snapshot = snapshot snapshot.set_checking_points(self.get_checking_points(snapshot)) def delete_snapshot(self, snapshot): snapshot.delete() if snapshot in self.primary_snapshots: self.primary_snapshots.remove(snapshot) if snapshot in self.backuped_snapshots: self.backuped_snapshots.remove(snapshot) #only Hypervisor based snapshot will clean child if 'Storage' == snapshot.get_snapshot().type: self._update_delete() return sp_list = get_snapshot_family(snapshot) for sp in sp_list: if sp.get_state() == sp_header.DELETED: continue sp.delete2() if sp in self.primary_snapshots: self.primary_snapshots.remove(sp) if sp in self.backuped_snapshots: self.backuped_snapshots.remove(sp) self._update_delete() def delete(self): if self.snapshot_head: self.delete_snapshot(self.snapshot_head) def backup_snapshot(self, snapshot): snapshot.backup() self.backuped_snapshots.append(snapshot) self.state = sp_header.BACKUPED def delete_backuped_snapshot(self, snapshot): snapshot.delete_from_backup_storage() self.backuped_snapshots.remove(snapshot) self._update_delete() def _update_delete(self): for sp in list(self.snapshot_list): if not sp in self.primary_snapshots \ and not sp in self.backuped_snapshots: self.snapshot_list.remove(sp) if not self.backuped_snapshots: if not self.primary_snapshots: self.state = sp_header.DELETED else: self.state = sp_header.CREATED else: if not self.primary_snapshots: self.state = sp_header.PS_DELETED else: self.state = sp_header.BACKUPED def check(self): import zstackwoodpecker.zstack_test.checker_factory as checker_factory self.update() if self.state == sp_header.DELETED: test_util.test_logger('Volume Snapshot has been deleted. Does not need to execute check() function') return checker = checker_factory.CheckerFactory().create_checker(self) checker.check() def update(self): if self.get_target_volume().get_state() == volume_header.DELETED: #since volume is deleted, can't create next snapshot, then #the current snapshot is useless. self.current_snapshot = None #TODO: In current zstack, if volume is deleted, all sp in ps will #be removed. Should update this, after new delete sp API is added. self.primary_snapshots = [] #In case, test case might directly call ZstackTestSnapshot().* API # need to manually update each sp. And if sp's parent is deleted, this # SP is also needed to be deleted. for sp in self.snapshot_list: sp.update() if sp.get_state() == sp_header.DELETED: if sp in self.primary_snapshots: self.primary_snapshots.remove(sp) if sp in self.backuped_snapshots: self.backuped_snapshots.remove(sp) self._update_delete() def get_primary_snapshots(self): return self.primary_snapshots def get_backuped_snapshots(self): return self.backuped_snapshots class ZstackTestSnapshot(sp_header.TestSnapshot): def __init__(self): self.snapshot_option = test_util.SnapshotOption() self.parent = None self.child_list = [] self.checking_point = uuid.uuid1().get_hex() #utility_vm is mostly like a VR vm, which could be connected by ssh. self.utility_vm = None self.image_option = None #all checking points files including parents checking points. self.checking_points = [] super(ZstackTestSnapshot, self).__init__() def set_checking_points(self, checking_points): self.checking_points = checking_points def get_checking_points(self): return self.checking_points def _live_snapshot_cap_check(self): ''' Deprecated. It is not recommended to be called in create_snapshot. ''' volume_obj = self.get_target_volume() volume_vm = volume_obj.get_target_vm() if volume_vm and volume_vm.get_state() == vm_header.RUNNING: host = test_lib.lib_find_host_by_vm(volume_vm.get_vm()) conditions = res_ops.gen_query_conditions('tag', '=', \ 'capability:liveSnapshot') tag_info = test_lib.lib_find_host_tag(host, conditions) if tag_info: test_util.test_logger('host: %s support live snapshot' % \ host.uuid) return True else: test_util.test_fail('host: %s does not support live snapshot' \ % host.uuid) return False return True def create(self): ''' Not recommended to be called by test case directly. Test case needs to call ZstackVolumeSnapshot.create_snapshot() ''' super(ZstackTestSnapshot, self).create() if not self.target_volume: test_util.test_fail('Can not create snapshot, before set target_volume') if not self.utility_vm: test_util.test_fail('Can not create snapshot, before set utility_vm, which will be used for doing snapshot checking. utiltiy_vm is mostly like a VR vm.') #self._live_snapshot_cap_check() self.add_checking_point() self.snapshot = vol_ops.create_snapshot(self.snapshot_option) self.target_volume.update_volume() def add_checking_point(self): volume_obj = self.get_target_volume() volume = volume_obj.get_volume() if volume.type == 'Root': test_util.test_logger('Can not add checking point file for Root Volume: %s, since it can not be detached and reattached to utility vm for checking.' % volume.uuid) return volume_vm = volume_obj.get_target_vm() #check if volume has been attached to the living VM. if volume_obj.get_state() == volume_header.ATTACHED: if volume_vm.get_state() == vm_header.STOPPED or \ volume_vm.get_state() == vm_header.RUNNING: test_util.test_logger('volume has been attached to living VM.') volume_obj.detach() volume_obj.attach(self.utility_vm) #add checking point self._create_checking_file() volume_obj.detach() volume_obj.attach(volume_vm) return volume_obj.attach(self.utility_vm) #add_checking_point self._create_checking_file() volume_obj.detach() def _create_checking_file(self): #make fs for volume, if it doesn't exist if not self.parent and not self.child_list: test_lib.lib_mkfs_for_volume(self.target_volume.get_volume().uuid, \ self.utility_vm.get_vm()) import tempfile with tempfile.NamedTemporaryFile() as script: script.write(''' device=/dev/`ls -ltr --file-type /dev | grep disk | awk '{print $NF}' | grep -v '[[:digit:]]' | tail -1`1 mkdir -p %s mount $device %s mkdir -p %s touch %s/%s umount %s ''' % (test_lib.WOODPECKER_MOUNT_POINT, \ test_lib.WOODPECKER_MOUNT_POINT, \ checking_point_folder, checking_point_folder, \ self.checking_point, test_lib.WOODPECKER_MOUNT_POINT)) script.flush() test_lib.lib_execute_shell_script_in_vm(self.utility_vm.get_vm(), script.name) if self.parent: test_util.test_logger('[snapshot:] %s checking file: %s is created.\ Its [parent:] %s' % \ (self.snapshot_option.get_name(), \ self.checking_point, self.parent.get_snapshot().uuid)) else: test_util.test_logger('[snapshot:] %s checking file: %s is created.'% (self.snapshot_option.get_name(), self.checking_point)) def delete(self): ''' Not recommended to be directly called by test case. Test case needs to call ZstackVolumeSnapshot.delete_snapshot() ''' vol_ops.delete_snapshot(self.snapshot.uuid) self.delete2() def delete2(self): super(ZstackTestSnapshot, self).delete() def backup(self, backup_storage_uuid = None): ''' Not recommended to be directly called by test case. Test case needs to call ZstackVolumeSnapshot.backup_snapshot() ''' self.snapshot = vol_ops.backup_snapshot(self.get_snapshot().uuid, backup_storage_uuid) super(ZstackTestSnapshot, self).backup() def use(self): ''' Not recommended to be directly called by test case. Test case needs to call ZstackVolumeSnapshot.use_snapshot() ''' if self.target_volume.get_state() == volume_header.DELETED: test_util.test_fail( 'Should not be called, as snapshot volume:%s has been deleted. Snapshot can not\ be applied to volume' % self.target_volume.get_volume().uuid) vol_ops.use_snapshot(self.get_snapshot().uuid) super(ZstackTestSnapshot, self).use() #volume installPath will be changed, so need to update volume self.target_volume.update_volume() def delete_from_primary_storage(self): ''' Not recommended to be directly called by test case. Test case needs to call ZstackVolumeSnapshot.delete_snapshot_from_primary_storage() ''' super(ZstackTestSnapshot, self).delete_from_primary_storage() def delete_from_backup_storage(self): ''' Not recommended to be directly called by test case. Test case needs to call ZstackVolumeSnapshot.delete_backuped_snapshot() ''' vol_ops.delete_snapshot_from_backupstorage(self.get_snapshot().uuid) super(ZstackTestSnapshot, self).delete_from_backup_storage() def create_data_volume(self, name = None, ps_uuid = None): ''' @return: zstack_test_volume() object ''' import zstackwoodpecker.zstack_test.zstack_test_volume as \ zstack_volume_header if self.state == sp_header.DELETED: test_util.test_fail( 'Should not be called, as snapshot volume:%s has been deleted. Snapshot can not\ be created to a new data volume' % self.target_volume.get_volume().uuid) if not name: name = 'data volume created by sp: %s' % self.snapshot.uuid snapshot_uuid = self.get_snapshot().uuid volume_inv = vol_ops.create_volume_from_snapshot(snapshot_uuid, \ name, ps_uuid) super(ZstackTestSnapshot, self).create_data_volume() volume_obj = zstack_volume_header.ZstackTestVolume() volume_obj.set_volume(volume_inv) volume_obj.set_state(volume_header.DETACHED) #ROOT Volume won't create checking point. So skip. if self.get_volume_type() != volume_header.ROOT_VOLUME: volume_obj.set_original_checking_points(self.get_checking_points()) return volume_obj def create_image_template(self): ''' @return: zstack_test_image() object ''' import zstackwoodpecker.zstack_test.zstack_test_image as \ zstack_image_header if self.state == sp_header.DELETED: test_util.test_fail(\ 'Should not be called, as snapshot volume:%s has been deleted. Snapshot can \ not be created to a new template' % \ self.target_volume.get_volume().uuid) if not self.image_option.get_root_volume_uuid(): self.image_option.set_root_volume_uuid(self.snapshot.uuid) if not self.image_option.get_backup_storage_uuid_list(): bs_uuid = res_ops.get_resource(res_ops.BACKUP_STORAGE)[0].uuid self.image_option.set_backup_storage_uuid_list([bs_uuid]) img_inv = img_ops.create_template_from_snapshot(self.image_option) super(ZstackTestSnapshot, self).create_image_template() img_obj = zstack_image_header.ZstackTestImage() img_obj.set_image(img_inv) img_obj.set_state(image_header.CREATED) #ROOT Volume won't create checking point. So skip. if self.get_volume_type() != volume_header.ROOT_VOLUME: img_obj.set_original_checking_points(self.get_checking_points()) return img_obj def set_snapshot_creation_option(self, snapshot_option): self.snapshot_option = snapshot_option def get_snapshot_creation_option(self): return self.snapshot_option def set_image_creation_option(self, image_option): self.image_option = image_option def get_image_creation_option(self): return self.image_option def get_checking_point(self): return self.checking_point def set_utility_vm(self, utility_vm): self.utility_vm = utility_vm def get_utility_vm(self): return self.utility_vm def set_parent(self, parent): self.parent = parent def get_parent(self): return self.parent def add_child(self, snapshot): self.child_list.append(snapshot) def get_child_list(self): return self.child_list def rm_child(self, snapshot): self.child_list.remove(snapshot) def update(self): if self.get_target_volume().state == volume_header.DELETED \ or self.get_target_volume().state == volume_header.EXPUNGED: super(ZstackTestSnapshot, self).delete_from_primary_storage() def check(self): ''' Should not be called by test cases ''' super(ZstackTestSnapshot, self).check()
module.exports = { checksum(input) { const string = input.toString(); let sum = 0; let parity = 2; for (let i = string.length - 1; i >= 0; i--) { const digit = Math.max(parity, 1) * string[i]; sum += digit > 9 ? digit.toString().split('').map(Number).reduce((a, b) => a + b, 0) : digit; parity *= -1; } sum %= 10; return sum > 0 ? 10 - sum : 0; }, generate(input, inputOptions) { let string = input.toString(); const options = { pad: 0, weightFactor: 2 }; // option pad if (typeof inputOptions !== 'undefined') { if (typeof inputOptions.pad !== 'undefined') { options.pad = inputOptions.pad; if (options.pad > string.length) { string = Array(options.pad - String(string).length).join('0') + string; } } } return string + this.checksum(string); }, random(input, inputOptions) { function getRandomStringOfNumbers(length) { let randomStringOfNumbers = ''; while (randomStringOfNumbers.length < length) { const random = Math.random().toString(); randomStringOfNumbers += random.substr(2, random.length); if (randomStringOfNumbers.length > length) { randomStringOfNumbers = randomStringOfNumbers.substr(0, length); } } return randomStringOfNumbers; } return this.generate(getRandomStringOfNumbers(input - 1), inputOptions); }, validate(input) { return this.checksum(input.toString().slice(0, -1)) === parseInt(input % 10); }, }
/** * Create self executing function to avoid global scope creation */ (function (angular, tinymce) { 'use strict'; angular .module('mediaCenterContent') /** * Inject dependency */ .controller('ContentCategoryCtrl', ['$scope', 'Buildfire', 'SearchEngine', 'DB', 'COLLECTIONS', 'Location', 'category', 'Messaging', 'EVENTS', 'PATHS', 'AppConfig', 'Orders', 'SubcategoryOrders', 'CategoryOrders', '$csv', function ($scope, Buildfire, SearchEngine, DB, COLLECTIONS, Location, category, Messaging, EVENTS, PATHS, AppConfig, Orders, SubcategoryOrders, CategoryOrders, $csv) { /** * Using Control as syntax this */ var ContentCategory = this; ContentCategory.subcategoryTitle = ""; /** * Create instance of MediaContent, MediaCenter db collection * @type {DB} */ var MediaContent = new DB(COLLECTIONS.MediaContent); var MediaCenter = new DB(COLLECTIONS.MediaCenter); var SearchEngineService = new SearchEngine(COLLECTIONS.MediaContent); var CategoryContent = new DB(COLLECTIONS.CategoryContent); var SubcategoryContent = new DB(COLLECTIONS.SubcategoryContent); var CategoryAccess = new Categories({ db: CategoryContent }) var SubcategoryAccess = new Subcategories({ db: SubcategoryContent }); /** * Get the MediaCenter initialized settings */ if (!AppConfig.getSettings()) { AppConfig.setSettings({ content: { images: [], descriptionHTML: '', description: '', sortCategoriesBy: Orders.ordersMap.Newest, sortCategoriesBy: CategoryOrders.ordersMap.Newest, rankOfLastItem: 0, rankOfLastCategory: 0, allowShare: true, allowSource: true, allowOfflineDownload: false, enableFiltering: false, transferAudioContentToPlayList: false, forceAutoPlay: false, dateIndexed: true, dateCreatedIndexed: true }, design: { listLayout: "list-1", itemLayout: "item-1", backgroundImage: "", skipMediaPage: false } }); } var MediaCenterSettings = AppConfig.getSettings(); function init() { ContentCategory.isBusy = true; Buildfire.auth.getCurrentUser((err, user) => { if (err) { ContentCategory.saving = false; return; } var data = { name: "", icon: "", subcategories: [ ], sortBy: SubcategoryOrders.ordersMap.Newest, // to sort subcategories rank: parseInt((MediaCenterSettings.content.rankOfLastCategory || 0) + 10), rankOfLastSubcategory: 0, lastSubcategoryId: 0, createdOn: "", createdBy: "", lastUpdatedOn: "", lastUpdatedBy: "", deletedOn: "", deletedBy: "", titleIndex:"", }; ContentCategory.sortOptions = SubcategoryOrders.options; if (user) ContentCategory.user = user; /** * if controller is for opened in edit mode, Load media data * else init it with bootstrap data */ if (category) { ContentCategory.item = category; ContentCategory.mode = 'edit'; ContentCategory.title = "Edit Category"; ContentCategory.displayedSubactegories = ContentCategory.item.data.subcategories; // used to display searched subcategories updateMasterItem(ContentCategory.item); } else { ContentCategory.item = { data: data }; ContentCategory.mode = 'add'; ContentCategory.title = "Add Category"; ContentCategory.displayedSubactegories = ContentCategory.item.data.subcategories; updateMasterItem(ContentCategory.item); } ContentCategory.itemSortableOptions.disabled = !(ContentCategory.item.data.sortBy === SubcategoryOrders.ordersMap.Manually); ContentCategory.isBusy = false; $scope.$apply(); }); }; init(); ContentCategory.searchText = ""; ContentCategory.saving = false; function updateMasterItem(item) { ContentCategory.masterItem = angular.copy(item); } ContentCategory.addIcon = function () { var options = { showIcons: true, multiSelection: false }, listImgCB = function (error, result) { if (error) { console.error('Error:', error); } else { ContentCategory.item.data.icon = result && result.selectedFiles && result.selectedFiles[0] || result && result.selectedIcons && result.selectedIcons[0] || ""; if (!$scope.$$phase) $scope.$digest(); } }; buildfire.imageLib.showDialog(options, listImgCB); }; ContentCategory.removeIcon = function () { ContentCategory.item.data.icon = ""; }; //To render icon whether it is an image or icon ContentCategory.isIcon = function (icon) { if (icon) { return icon.indexOf("http") != 0; } return ContentCategory.item.data.icon && ContentCategory.item.data.icon.indexOf("http") != 0; }; ContentCategory.updateItem = function () { if (ContentCategory.item.data.name) { ContentCategory.saving = true; ContentCategory.item.data.name = ContentCategory.item.data.name.trim(); ContentCategory.item.data.titleIndex = ContentCategory.item.data.name.toLowerCase(); if (ContentCategory.item.id) { //then we are editing the item ContentCategory.item.data.id = ContentCategory.item.id; ContentCategory.item.data.lastUpdatedOn = new Date(); ContentCategory.item.data.lastUpdatedBy = ContentCategory.user; ContentCategory.item.data.rankOfLastSubcategory = ContentCategory.item.data.subcategories.length ? ContentCategory.item.data.subcategories[ContentCategory.item.data.subcategories.length - 1].rank : 0; CategoryAccess.updateCategory(ContentCategory.item, function (err, result) { if (err) { ContentCategory.saving = false; console.error('Error saving data: ', err); return; } else { ContentCategory.item = result; updateMasterItem(ContentCategory.item); Messaging.sendMessageToWidget({ name: EVENTS.CATEGORIES_CHANGE, message: {} }); ContentCategory.saving = false; ContentCategory.done(); } }); } else { //then we are adding the item ContentCategory.item.data.createdOn = new Date(); ContentCategory.item.data.createdBy = ContentCategory.user; ContentCategory.item.data.lastSubcategoryId = ContentCategory.item.data.subcategories.length ? ContentCategory.item.data.subcategories.length : 0; ContentCategory.item.data.rankOfLastSubcategory = ContentCategory.item.data.subcategories.length ? ContentCategory.item.data.subcategories[ContentCategory.item.data.subcategories.length - 1].rank : 0; ContentCategory.addItem((err, result) => { if (err) { ContentCategory.saving = false; return console.log('Error saving data: ', err); } if (result) { ContentCategory.item = result; updateMasterItem(ContentCategory.item); if (ContentCategory.item.data.subcategories && ContentCategory.item.data.subcategories.length) { ContentCategory.item.data.subcategories.map((subcategory, index) => { subcategory.categoryId = result.id; subcategory.id = result.id + "_" + index; }); } ContentCategory.item.data.id = result.id; CategoryAccess.updateCategory(ContentCategory.item, function (err, result) { if (err) { ContentCategory.saving = false; console.error('Error saving data: ', err); return; } else { ContentCategory.item = result; updateMasterItem(ContentCategory.item); Messaging.sendMessageToWidget({ name: EVENTS.CATEGORIES_CHANGE, message: {} }); ContentCategory.saving = false; MediaCenterSettings.content.rankOfLastCategory = ContentCategory.item.data.rank; MediaCenter.save(MediaCenterSettings).then(() => { ContentCategory.done(); }); } }); } }); return; } } else { $scope.titleRequired = true; } } ContentCategory.addItem = function (cb) { CategoryAccess.addCategory(ContentCategory.item.data, function (err, result) { if (err) { console.error('Error saving data: ', err); return cb("Error saving data"); } else { ContentCategory.item = result; updateMasterItem(ContentCategory.item); cb(null, result); } }); } ContentCategory.done = function () { setTimeout(() => { Location.go("#/categoryHome"); }, 0); }; ContentCategory.showSubcategoryModal = function (mode, editedSubcategory) { if (mode == "Add") { ContentCategory.subcategoryModalMode = "Add"; ContentCategory.addSubcategoryTitle = "Add Subcategory"; ContentCategory.showSubModal = true; } else if (mode == "Edit" && editedSubcategory && editedSubcategory.name) { // we are editing ContentCategory.subcategoryModalMode = "Edit"; ContentCategory.addSubcategoryTitle = "Edit Subcategory"; ContentCategory.subcategoryTitle = editedSubcategory.name; ContentCategory.showSubModal = true; ContentCategory.editedSubcategory = editedSubcategory; } } ContentCategory.closeSubcategoryModal = function () { ContentCategory.showSubModal = false; ContentCategory.subcategoryTitle = ""; }; ContentCategory.addSucbategoryIcon = function (subcategory, event) { let subIndex = ContentCategory.item.data.subcategories.indexOf(subcategory); var options = { showIcons: true, multiSelection: false }, listImgCB = function (error, result) { if (error) { console.error('Error:', error); } else { ContentCategory.item.data.subcategories[subIndex].icon = result && result.selectedFiles && result.selectedFiles[0] || result && result.selectedIcons && result.selectedIcons[0] || ""; if (!$scope.$$phase) $scope.$digest(); } }; buildfire.imageLib.showDialog(options, listImgCB); }; ContentCategory.removeSubcategoryIcon = function (subcategory) { let subIndex = ContentCategory.item.data.subcategories.indexOf(subcategory); ContentCategory.item.data.subcategories[subIndex].icon = ""; }; ContentCategory.updateSubcategory = function () { if (ContentCategory.subcategoryTitle) { if (ContentCategory.subcategoryModalMode == "Add") { ContentCategory.item.data.subcategories.push(new Subcategory({ name: ContentCategory.subcategoryTitle, id: ContentCategory.item.id + "_" + ContentCategory.item.data.lastSubcategoryId, rank: (ContentCategory.item.data.rankOfLastSubcategory || 0) + 10, icon: "", createdOn: new Date(), createdBy: ContentCategory.user || "", lastUpdatedOn: "", lastUpdatedBy: "", deletedOn: "", deletedBy: "", })); ContentCategory.closeSubcategoryModal(); ContentCategory.subcategoryTitle = ""; ContentCategory.item.data.rankOfLastSubcategory = (ContentCategory.item.data.rankOfLastSubcategory || 0) + 10; ContentCategory.item.data.lastSubcategoryId = parseInt(ContentCategory.item.data.lastSubcategoryId + 1); } else { let itemIndex = ContentCategory.item.data.subcategories.indexOf(ContentCategory.editedSubcategory); ContentCategory.item.data.subcategories[itemIndex] = new Subcategory({ id: ContentCategory.editedSubcategory.id, name: ContentCategory.subcategoryTitle, categoryId: ContentCategory.item.id, rank: ContentCategory.editedSubcategory.rank || (ContentCategory.item.data.rankOfLastCategory || 0) + 10, icon: ContentCategory.editedSubcategory.icon || "", createdOn: ContentCategory.editedSubcategory.createdOn || new Date(), createdBy: ContentCategory.editedSubcategory.createdBy || "", lastUpdatedOn: new Date(), lastUpdatedBy: ContentCategory.user || "", deletedOn: "", deletedBy: "", }) ContentCategory.closeSubcategoryModal(); ContentCategory.subcategoryTitle = ""; } } ContentCategory.searchSubcategories(); }; ContentCategory.removeSubcategory = function (subcategory) { buildfire.dialog.confirm( { title: "Delete Sucbategory", confirmButton: { type: "danger", text: "Delete" }, message: "Are you sure you want to delete this subcategory? This action is not reversible.", }, (err, isConfirmed) => { if (err) console.error(err); if (isConfirmed) { let itemIndex = ContentCategory.item.data.subcategories.indexOf(subcategory); ContentCategory.item.data.subcategories.splice(itemIndex, 1); ContentCategory.searchSubcategories(); $scope.$apply(); } else { //Prevent action } } ); }; ContentCategory.toggleSortOrder = function (name) { if (!name) { console.info('There was a problem sorting your data'); } else { var sortOrder = SubcategoryOrders.getOrder(name || SubcategoryOrders.ordersMap.Default); ContentCategory.item.data.sortBy = name; ContentCategory.item.data.sortByValue = sortOrder.value; ContentCategory.sort(); // ContentCategory.getMore(); ContentCategory.itemSortableOptions.disabled = !(ContentCategory.item.data.sortBy === SubcategoryOrders.ordersMap.Manually); } }; ContentCategory.itemSortableOptions = { handle: '> .cursor-grab', disabled: ContentCategory.isBusy || !(ContentCategory.item.data.sortBy === SubcategoryOrders.ordersMap.Manually), stop: function (e, ui) { var endIndex = ui.item.sortable.dropindex, maxRank = 0, draggedItem = ContentCategory.displayedSubactegories[endIndex]; if (draggedItem) { var prev = ContentCategory.displayedSubactegories[endIndex - 1], next = ContentCategory.displayedSubactegories[endIndex + 1]; var isRankChanged = false; if (next) { if (prev) { draggedItem.rank = ((prev.rank || 0) + (next.rank || 0)) / 2; isRankChanged = true; } else { draggedItem.rank = (next.rank || 0) / 2; isRankChanged = true; } } else { if (prev) { draggedItem.rank = (((prev.rank || 0) * 2) + 10) / 2; maxRank = draggedItem.rank; isRankChanged = true; } } if (isRankChanged) { if (ContentCategory.item.data.rankOfLastSubcategory < maxRank) { ContentCategory.item.data.rankOfLastSubcategory = maxRank; } ContentCategory.item.data.subcategories.sort(function (a, b) { return a.rank - b.rank; }); ContentCategory.searchSubcategories(); } } } }; ContentCategory.sort = function () { if (ContentCategory.item.data.sortBy === "Subcategory Title A-Z") { ContentCategory.item.data.subcategories.sort(function (a, b) { return a.name.localeCompare(b.name); }); } if (ContentCategory.item.data.sortBy === "Subcategory Title Z-A") { ContentCategory.item.data.subcategories.sort(function (a, b) { return b.name.localeCompare(a.name); }); } if (ContentCategory.item.data.sortBy === "Manually") { ContentCategory.item.data.subcategories.sort(function (a, b) { return a.rank - b.rank; }); } if (ContentCategory.item.data.sortBy === "Newest") { ContentCategory.item.data.subcategories.sort(function (a, b) { return (new Date(b.createdOn) - new Date(a.createdOn)); }); } if (ContentCategory.item.data.sortBy === "Oldest") { ContentCategory.item.data.subcategories.sort(function (a, b) { return (new Date(a.createdOn) - new Date(b.createdOn)); }); } }; ContentCategory.cancelAdd = function () { Location.go("#/categoryHome"); }; ContentCategory.searchSubcategories = function () { if (ContentCategory.searchText == "") { ContentCategory.displayedSubactegories = ContentCategory.item.data.subcategories; } else { ContentCategory.displayedSubactegories = ContentCategory.item.data.subcategories.filter(function (subcategory) { return subcategory.name.toLowerCase().indexOf(ContentCategory.searchText.toLowerCase()) > -1; }); } }; ContentCategory.onEnterKey = function (keyEvent) { if (keyEvent.which === 13) ContentCategory.searchSubcategories(); }; var header = { name: "Subcategory name", }; var headerRow = ["name"]; ContentCategory.getTemplate = function () { var templateData = [{ name: '', }]; var csv = $csv.jsonToCsv(angular.toJson(templateData), { header: header }); $csv.download(csv, "Template.csv"); }; ContentCategory.exportCSV = function () { if (ContentCategory.item.data.subcategories && ContentCategory.item.data.subcategories.length) { let persons = ContentCategory.item.data.subcategories.map(function (subcategory) { return { name: subcategory.name }; }); var csv = $csv.jsonToCsv(angular.toJson(persons), { header: header }); $csv.download(csv, "Export.csv"); } else { ContentCategory.getTemplate(); } }; function isValidItem(item, index, array) { return item.name; } function validateCsv(items) { if (!Array.isArray(items) || !items.length) { return false; } return items.every(isValidItem); } ContentCategory.openImportCSVDialog = function () { $csv.import(headerRow).then(function (rows) { ContentCategory.loading = true; if (rows && rows.length > 1) { var columns = rows.shift(); for (var _index = 0; _index < headerRow.length; _index++) { if (header[headerRow[_index]] != columns[headerRow[_index]]) { ContentCategory.loading = false; ContentCategory.csvDataInvalid = true; /* $timeout(function hideCsvDataError() { ContentCategory.csvDataInvalid = false; }, 2000);*/ break; } } if (!ContentCategory.loading) return; var rank = 0; for (var index = 0; index < rows.length; index++) { rank += 10; rows[index].createdOn = new Date().getTime(); rows[index].createdBy = ContentCategory.user || ""; rows[index].lastUpdatedOn = ""; rows[index].lastUpdatedBy = ""; rows[index].deletedOn = ""; rows[index].deletedBy = ""; rows[index].rank = rank; rows[index].id = ContentCategory.item.id ? ContentCategory.item.id + "_" + parseInt(ContentCategory.item.data.lastSubcategoryId + index) : ""; rows[index].name = rows[index].name; } if (validateCsv(rows)) { // MediaContent.insert(rows).then(function (data) { // ContentCategory.loading = false; // ContentCategory.isBusy = false; // ContentCategory.items = []; // ContentCategory.info.data.content.rankOfLastItem = rank; // }, function errorHandler(error) { // console.error(error); // ContentCategory.loading = false; // $scope.$apply(); // }); ContentCategory.item.data.rankOfLastCategory = rank; ContentCategory.item.data.lastSubcategoryId = parseInt(ContentCategory.item.data.lastSubcategoryId + rows.length); ContentCategory.item.data.subcategories = rows; ContentCategory.searchSubcategories(); } else { ContentCategory.loading = false; ContentCategory.csvDataInvalid = true; $timeout(function hideCsvDataError() { ContentCategory.csvDataInvalid = false; }, 2000); } } else { ContentCategory.loading = false; ContentCategory.csvDataInvalid = true; /* $timeout(function hideCsvDataError() { ContentCategory.csvDataInvalid = false; }, 2000);*/ $scope.$apply(); } }, function (error) { ContentCategory.loading = false; $scope.$apply(); //do something on cancel }); }; }]); })(window.angular, window.tinymce);