text
stringlengths
3
1.05M
/* * Copyright 2019 TWO SIGMA OPEN SOURCE, LLC * * 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 React from 'react' import CardList from '../../widgets/CardList' import CardLabelAndNumber from '../../widgets/CardLabelAndNumber' export default function TestsSuccessRatio({report}) { return ( <CardList label="Tests success ratio"> <CardLabelAndNumber label="Passed" number={report.summary.percentagePassed} unit="%"/> <CardLabelAndNumber label="Passed total" number={report.summary.total}/> <CardLabelAndNumber label="Total with Problems" number={report.summary.totalWithProblems}/> </CardList> ) }
const audioCtx = new (window.AudioContext || window.webkitAudioContext)(); // C3 - C6 // https://pages.mtu.edu/~suits/notefreqs.html const sounds = [ 130.81, 146.83, 164.81, 174.61, 196.00, 220.00, 246.94, 261.63, 293.66, 329.63, 349.23, 392.0, 440.0, 493.88, 523.25, 587.33, 659.25, 698.46, 783.99, 880.0, 987.77, 1046.5, ]; let selectedUuid; const attackTime = 0.05; const releaseTime = 0.01; const bassNotes = 6; const finalNoteLength = 0.5; const nthNotes = 8; function generateNew() { selectedUuid = uuid.v4(); document.getElementById("uuidDisplay").innerHTML = selectedUuid; } function parseToIntArray(uuid) { const arr = []; for (let char of uuid) { if (char === "-") continue; switch (char) { case "a": arr.push(10); break; case "b": arr.push(11); break; case "c": arr.push(12); break; case "d": arr.push(13); break; case "e": arr.push(14); break; case "f": arr.push(15); break; default: arr.push(+char); break; } } return arr; } function parseToNotes(arr, melody) { let notes = []; if (melody) { let melodyPointer = 0; arr.forEach((note, i) => { const pitch = sounds[note]; const duration = melody[melodyPointer].duration + melody[melodyPointer + 1].duration; melodyPointer += 2; notes.push({ pitch, duration }); }); notes.push({ pitch: sounds[7], duration: melody[melodyPointer].duration }); notes.push({ pitch: sounds[7], duration: finalNoteLength }); } else { let noteSplit = arr.slice(0, arr.length / 2); let durationSplit = arr.slice(arr.length / 2); noteSplit.forEach((note, i) => { const pitch = sounds[note + 6]; const duration = (1 + durationSplit[i] % 4) / nthNotes; notes.push({ pitch, duration }); }); notes.push({ pitch: sounds[0], duration: finalNoteLength }); } return notes; } function runBass(arr, melody) { const notes = parseToNotes(arr.slice(0, bassNotes), melody); const sine = audioCtx.createOscillator(); const volume = audioCtx.createGain(); let totalTime = audioCtx.currentTime; sine.connect(volume).connect(audioCtx.destination); volume.gain.linearRampToValueAtTime(0.1, totalTime); for (note of notes) { sine.frequency.setValueAtTime(note.pitch, totalTime); volume.gain.linearRampToValueAtTime(0.2, totalTime + attackTime); volume.gain.linearRampToValueAtTime( 0, totalTime + note.duration - releaseTime ); totalTime += note.duration; } sine.start(); sine.stop(totalTime); } function runMelody(arr) { const notes = parseToNotes(arr.slice(bassNotes)); console.log(notes); const sine = audioCtx.createOscillator(); const volume = audioCtx.createGain(); let totalTime = audioCtx.currentTime; sine.connect(volume).connect(audioCtx.destination); volume.gain.linearRampToValueAtTime(0.3, totalTime); for (note of notes) { sine.frequency.setValueAtTime(note.pitch, totalTime); volume.gain.linearRampToValueAtTime(0.7, totalTime + attackTime); volume.gain.linearRampToValueAtTime( 0, totalTime + note.duration - releaseTime ); totalTime += note.duration; } sine.start(); sine.stop(totalTime); return notes; } function playSound() { const arr = parseToIntArray(selectedUuid); const melody = runMelody(arr); runBass(arr, melody); } generateNew();
/** The MIT License (MIT) Copyright (c) 2014 Michiel Visser 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. **/ function chainlist_test() { var testContent = function(l,c) { assert_equal(l.toArray(),c); l._testInvariants(); } var makeList = function(array,parent) { var a=array.slice(0); var l = ChainList.fromArray(a,parent); assert_equal(a,array); testContent(l,array); return l; } var tests = { test_parent: function() { var l=makeList([]); assert(l.parent()==l); l=makeList(['a','b','c'],'x'); assert(l.parent()=='x'); }, test_indexLink_empty: function() { var l=makeList([]); assert(l.parent()==l); assert_equal(l.indexLink(0)._isList,true); assert_equal(l.indexLink(1)._isList,true); assert_equal(l.indexLink(-1)._isList,true); assert_equal(l.indexLink(0).elem(),null); }, test_indexLink_nonEmpty: function() { var l=makeList(['a','b','c'],'x'); assert_equal(l.indexLink(0)._isList,true); assert_equal(l.indexLink(1).elem(),'a'); assert_equal(l.indexLink(2).elem(),'b'); assert_equal(l.indexLink(3).elem(),'c'); assert_equal(l.indexLink(4)._isList,true); assert_equal(l.indexLink(-1).elem(),'c'); assert_equal(l.indexLink(-2).elem(),'b'); assert_equal(l.indexLink(-3).elem(),'a'); assert_equal(l.indexLink(-4)._isList,true); }, test_get_empty: function() { var l=makeList([]); assert_equal(l.get(0),null); assert_equal(l.get(1),null); assert_equal(l.get(-1),null); }, test_get_nonEmpty: function() { var l=makeList(['a','b','c'],'x'); assert_equal(l.get(0),'a'); assert_equal(l.get(1),'b'); assert_equal(l.get(2),'c'); assert_equal(l.get(3),null); assert_equal(l.get(4),null); assert_equal(l.get(-1),'c'); assert_equal(l.get(-2),'b'); assert_equal(l.get(-3),'a'); assert_equal(l.get(-4),null); assert_equal(l.get(-5),null); }, test_indexPos: function() { var l=makeList([]); assert_equal(l.indexPos(0)._isList,true); assert_equal(l.indexPos(1)._isList,true); assert_equal(l.indexPos(-1)._isList,true); l=makeList(['a','b','c'],'x'); assert_equal(l.indexPos(0).elem(),'a'); assert_equal(l.indexPos(1).elem(),'b'); assert_equal(l.indexPos(-3).elem(),'a'); }, test_last: function() { var l=makeList(['a','b','c'],'x'); assert_equal(l.last().elem(),'c'); }, test_takeRange: function() { var l=ChainList.fromArray(['a','b','c'],'x'); var l2=ChainList.fromArray([],'y'); l2.takeRange(l,l); testContent(l,[]); testContent(l2,['a','b','c']); l=ChainList.fromArray(['a','b','c'],'x'); l2=ChainList.fromArray([],'y'); l2.takeRange(l,l.indexPos(0)); testContent(l,['a','b','c']); testContent(l2,[]); l=ChainList.fromArray(['a','b','c'],'x'); l2=ChainList.fromArray([],'y'); l2.takeRange(l,l.indexPos(1)); testContent(l,['b','c']); testContent(l2,['a']); l=ChainList.fromArray(['a','b','c'],'x'); l2=ChainList.fromArray([],'y'); l2.takeRange(l,l.indexPos(2)); testContent(l,['c']); testContent(l2,['a','b']); }, test_take: function() { var l=ChainList.fromArray(['a','b','c'],'x'); var l2=ChainList.fromArray(['d'],'y'); l.indexPos(1).take(l2); testContent(l2,[]); testContent(l,['a','d','b','c']); }, test_takeSome: function() { var l=ChainList.fromArray(['a','b','c'],'x'); var l2=ChainList.fromArray(['d','e'],'y'); l.takeSome(l2,1); testContent(l2,['e']); testContent(l,['a','b','c','d']); }, test_remove: function() { var l=ChainList.fromArray(['a','b','c'],'x'); l.indexPos(0).remove(); testContent(l,['b','c']); l=ChainList.fromArray(['a','b','c'],'x'); l.indexPos(1).remove(); testContent(l,['a','c']); l=ChainList.fromArray(['a','b','c'],'x'); l.indexPos(2).remove(); testContent(l,['a','b']); }, test_removeAt: function() { var l=ChainList.fromArray(['a','b','c'],'x'); l.removeAt(0); testContent(l,['b','c']); l=ChainList.fromArray(['a','b','c'],'x'); l.removeAt(1); testContent(l,['a','c']); l=ChainList.fromArray(['a','b','c'],'x'); l.removeAt(2); testContent(l,['a','b']); }, test_reverse: function() { var l=ChainList.fromArray([]); l.reverse(); testContent(l,[]); l=ChainList.fromArray(['a'],'x'); l.reverse(); testContent(l,['a']); l=ChainList.fromArray(['a','b'],'x'); l.reverse(); testContent(l,['b','a']); }, test_insert: function() { var l=makeList([],'p'); l.insert("a"); testContent(l, ["a"]); l=makeList(['a'],'p'); l.insert("c"); testContent(l,["a","c"]); l=makeList(['a','b'],'p'); l.first().insert("c"); testContent(l, ["c","a","b"]); l=makeList(['a','b'],'p'); l.last().insert("c"); testContent(l, ["a","c","b"]); }, test: function() { var l=makeList(['a','b','c'],'p'); var l2=new ChainList(); l2.takeRange(l,l.indexPos(1)); assert_equal(l2.toArray(),["a"]); testContent(l,["b","c"]); l2.clear(); assert_equal(l2.toArray(),[]); l2 = l.shiftRange(l._next); assert_equal(l2.toArray(),[]); testContent(l, ["b","c"]); l.unshift("a"); testContent(l, ["a","b","c"]); assert_equal(l.indexPos(1).shiftSome(1).toArray(),["b"]); testContent(l, ["a","c"]); var cl=l.clone(); assert_equal(cl.toArray(),["a","c"]); cl.clear(); assert_equal(cl.toArray(),[]); testContent(l, ["a","c"]); l.insertArray(["d","e"]); testContent(l, ["a","c","d","e"]); assert_equal(l.indexPos(1).shiftSome(2).toArray(),["c","d"]); testContent(l, ["a","e"]); l.insert("z"); l.reverse(); testContent(l, ["z","e","a"]); l.reverse(); testContent(l, ["a","e","z"]); assert_equal(l.indexPos(1).get(1),"z"); assert_equal(l.indexPos(1).get(-1),"a"); assert_equal(l.indexPos(1).get(2),null); assert_equal(l.indexPos(1).get(-2),null); assert_equal(l.cloneSome(2).toArray(),["a","e"]); assert_equal(l.slice(1,3).toArray(),["e","z"]); assert_equal(l.slice(0,2).toArray(),["a","e"]); testContent(l, ["a","e","z"]); assert_equal(l.splice(1,1,"f","g").toArray(),["e"]); testContent(l, ["a","f","g","z"]); assert_equal(l._length,4); assert_equal(l.parent(),"p"); assert_equal(l.indexPos(1).parent(),"p"); assert_equal(l.indexPos(-1).parent(),"p"); assert_equal(l.indexPos(-3).parent(),"p"); assert_equal(l.indexOf(l.indexPos(0)),0); assert_equal(l.indexOf(l.indexPos(1)),1); assert_equal(l.indexOf(l.indexPos(2)),2); l.insertAt(0,"x"); testContent(l, ["x","a","f","g","z"]); l.insertAt(-1,"y"); testContent(l, ["x","a","f","g","z","y"]); l.insertAt(l._length,"q"); testContent(l, ["x","a","f","g","z","y","q"]); }, test_chainListSorted: function() { var ls = new ChainListSorted(); testContent(ls, []); ls.insert(2); testContent(ls, [2]); ls.insert(1); testContent(ls, [1,2]); ls.insert(5); testContent(ls, [1,2,5]); ls.insert(5); testContent(ls, [1,2,5,5]); ls.insert(3); testContent(ls, [1,2,3,5,5]); var ls = new ChainListSorted(null,function(a,b) { return b-a; } ); testContent(ls, []); ls.insert(2); testContent(ls, [2]); ls.insert(1); testContent(ls, [2,1]); ls.insert(5); testContent(ls, [5,2,1]); ls.insert(5); testContent(ls, [5,5,2,1]); ls.insert(3); testContent(ls, [5,5,3,2,1]); var ls = new ChainListSorted.fromArray([7,4,8,3,2]); testContent(ls,[2,3,4,7,8]); } }; for(var key in tests) { if (tests.hasOwnProperty(key)) { console.log('Executing: '+key); tests[key](); } } };
module.exports = ["a-2", require("./b")]
from __future__ import print_function import argparse import data_loader import numpy as np import torch import torch.nn as nn import torch.optim as optim import torchvision import time # Command setting parser = argparse.ArgumentParser(description='Finetune') parser.add_argument('-model', '-m', type=str, help='model name', default='resnet') parser.add_argument('-batchsize', '-b', type=int, help='batch size', default=64) parser.add_argument('-cuda', '-g', type=int, help='cuda id', default=0) parser.add_argument('-source', '-src', type=str, default='amazon') parser.add_argument('-target', '-tar', type=str, default='webcam') args = parser.parse_args() # Parameter setting DEVICE = torch.device('cuda:' + str(args.cuda) if torch.cuda.is_available() else 'cpu') N_CLASS = 31 LEARNING_RATE = 1e-4 BATCH_SIZE = {'src': int(args.batchsize), 'tar': int(args.batchsize)} N_EPOCH = 100 MOMENTUM = 0.9 DECAY=5e-4 def load_model(name='alexnet'): if name == 'alexnet': model = torchvision.models.alexnet(pretrained=True) n_features = model.classifier[6].in_features fc = torch.nn.Linear(n_features, N_CLASS) model.classifier[6] = fc elif name == 'resnet': model = torchvision.models.resnet50(pretrained=True) n_features = model.fc.in_features fc = torch.nn.Linear(n_features, N_CLASS) model.fc = fc return model def get_optimizer(model_name): learning_rate = LEARNING_RATE if model_name == 'alexnet': param_group = [{'params': model.features.parameters(), 'lr': learning_rate}] for i in range(6): param_group += [{'params': model.classifier[i].parameters(), 'lr': learning_rate}] param_group += [{'params': model.classifier[6].parameters(), 'lr': learning_rate * 10}] elif model_name == 'resnet': param_group = [] for k, v in model.named_parameters(): if not k.__contains__('fc'): param_group += [{'params': v, 'lr': learning_rate}] else: param_group += [{'params': v, 'lr': learning_rate * 10}] optimizer = optim.SGD(param_group, momentum=MOMENTUM) return optimizer # Schedule learning rate def lr_schedule(optimizer, epoch): def lr_decay(LR, n_epoch, e): return LR / (1 + 10 * e / n_epoch) ** 0.75 for i in range(len(optimizer.param_groups)): if i < len(optimizer.param_groups) - 1: optimizer.param_groups[i]['lr'] = lr_decay(LEARNING_RATE, N_EPOCH, epoch) else: optimizer.param_groups[i]['lr'] = lr_decay(LEARNING_RATE, N_EPOCH, epoch) * 10 def finetune(model, dataloaders, optimizer): since = time.time() best_acc = 0.0 acc_hist = [] criterion = nn.CrossEntropyLoss() for epoch in range(1, N_EPOCH + 1): # lr_schedule(optimizer, epoch) print('Learning rate: {:.8f}'.format(optimizer.param_groups[0]['lr'])) print('Learning rate: {:.8f}'.format(optimizer.param_groups[-1]['lr'])) for phase in ['src', 'val', 'tar']: if phase == 'src': model.train() else: model.eval() total_loss, correct = 0, 0 for inputs, labels in dataloaders[phase]: inputs, labels = inputs.to(DEVICE), labels.to(DEVICE) optimizer.zero_grad() with torch.set_grad_enabled(phase == 'src'): outputs = model(inputs) loss = criterion(outputs, labels) preds = torch.max(outputs, 1)[1] if phase == 'src': loss.backward() optimizer.step() total_loss += loss.item() * inputs.size(0) correct += torch.sum(preds == labels.data) epoch_loss = total_loss / len(dataloaders[phase].dataset) epoch_acc = correct.double() / len(dataloaders[phase].dataset) acc_hist.append([epoch_loss, epoch_acc]) print('Epoch: [{:02d}/{:02d}]---{}, loss: {:.6f}, acc: {:.4f}'.format(epoch, N_EPOCH, phase, epoch_loss, epoch_acc)) if phase == 'tar' and epoch_acc > best_acc: best_acc = epoch_acc print() fname = 'finetune_result' + model_name + str(LEARNING_RATE) + str(args.source) + '-' + str(args.target) + '.csv' np.savetxt(fname, np.asarray(a=acc_hist, dtype=float), delimiter=',', fmt='%.4f') time_pass = time.time() - since print('Training complete in {:.0f}m {:.0f}s'.format(time_pass // 60, time_pass % 60)) return model, best_acc, acc_hist if __name__ == '__main__': torch.manual_seed(10) # Load data root_dir = 'data/OFFICE31/' domain = {'src': str(args.source), 'tar': str(args.target)} dataloaders = {} dataloaders['tar'] = data_loader.load_data(root_dir, domain['tar'], BATCH_SIZE['tar'], 'tar') dataloaders['src'], dataloaders['val'] = data_loader.load_train(root_dir, domain['src'], BATCH_SIZE['src'], 'src') print(len(dataloaders['src'].dataset), len(dataloaders['val'].dataset)) # Load model model_name = str(args.model) model = load_model(model_name).to(DEVICE) print('Source:{}, target:{}, model: {}'.format(domain['src'], domain['tar'], model_name)) optimizer = get_optimizer(model_name) model_best, best_acc, acc_hist = finetune(model, dataloaders, optimizer) print('{}Best acc: {}'.format('*' * 10, best_acc))
/*! * jQuery JavaScript Library v3.6.0 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright OpenJS Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2021-03-02T17:08Z */ ( function( global, factory ) { "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get jQuery. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "jQuery requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet } )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; var arr = []; var getProto = Object.getPrototypeOf; var slice = arr.slice; var flat = arr.flat ? function( array ) { return arr.flat.call( array ); } : function( array ) { return arr.concat.apply( [], array ); }; var push = arr.push; var indexOf = arr.indexOf; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var fnToString = hasOwn.toString; var ObjectFunctionString = fnToString.call( Object ); var support = {}; var isFunction = function isFunction( obj ) { // Support: Chrome <=57, Firefox <=52 // In some browsers, typeof returns "function" for HTML <object> elements // (i.e., `typeof document.createElement( "object" ) === "function"`). // We don't want to classify *any* DOM node as a function. // Support: QtWeb <=3.8.5, WebKit <=534.34, wkhtmltopdf tool <=0.12.5 // Plus for old WebKit, typeof returns "function" for HTML collections // (e.g., `typeof document.getElementsByTagName("div") === "function"`). (gh-4756) return typeof obj === "function" && typeof obj.nodeType !== "number" && typeof obj.item !== "function"; }; var isWindow = function isWindow( obj ) { return obj != null && obj === obj.window; }; var document = window.document; var preservedScriptAttributes = { type: true, src: true, nonce: true, noModule: true }; function DOMEval( code, node, doc ) { doc = doc || document; var i, val, script = doc.createElement( "script" ); script.text = code; if ( node ) { for ( i in preservedScriptAttributes ) { // Support: Firefox 64+, Edge 18+ // Some browsers don't support the "nonce" property on scripts. // On the other hand, just using `getAttribute` is not enough as // the `nonce` attribute is reset to an empty string whenever it // becomes browsing-context connected. // See https://github.com/whatwg/html/issues/2369 // See https://html.spec.whatwg.org/#nonce-attributes // The `node.getAttribute` check was added for the sake of // `jQuery.globalEval` so that it can fake a nonce-containing node // via an object. val = node[ i ] || node.getAttribute && node.getAttribute( i ); if ( val ) { script.setAttribute( i, val ); } } } doc.head.appendChild( script ).parentNode.removeChild( script ); } function toType( obj ) { if ( obj == null ) { return obj + ""; } // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call( obj ) ] || "object" : typeof obj; } /* global Symbol */ // Defining this global in .eslintrc.json would create a danger of using the global // unguarded in another place, it seems safer to define global only for this module var version = "3.6.0", // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: version, constructor: jQuery, // The default length of a jQuery object is 0 length: 0, toArray: function() { return slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { // Return all the elements in a clean array if ( num == null ) { return slice.call( this ); } // Return just the one element from the set return num < 0 ? this[ num + this.length ] : this[ num ]; }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. each: function( callback ) { return jQuery.each( this, callback ); }, map: function( callback ) { return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); } ) ); }, slice: function() { return this.pushStack( slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, even: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return ( i + 1 ) % 2; } ) ); }, odd: function() { return this.pushStack( jQuery.grep( this, function( _elem, i ) { return i % 2; } ) ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, sort: arr.sort, splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { var options, name, src, copy, copyIsArray, clone, target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction( target ) ) { target = {}; } // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( ( options = arguments[ i ] ) != null ) { // Extend the base object for ( name in options ) { copy = options[ name ]; // Prevent Object.prototype pollution // Prevent never-ending loop if ( name === "__proto__" || target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = Array.isArray( copy ) ) ) ) { src = target[ name ]; // Ensure proper type for the source value if ( copyIsArray && !Array.isArray( src ) ) { clone = []; } else if ( !copyIsArray && !jQuery.isPlainObject( src ) ) { clone = {}; } else { clone = src; } copyIsArray = false; // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend( { // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), // Assume jQuery is ready without the ready module isReady: true, error: function( msg ) { throw new Error( msg ); }, noop: function() {}, isPlainObject: function( obj ) { var proto, Ctor; // Detect obvious negatives // Use toString instead of jQuery.type to catch host objects if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } proto = getProto( obj ); // Objects with no prototype (e.g., `Object.create( null )`) are plain if ( !proto ) { return true; } // Objects with prototype are plain iff they were constructed by a global Object function Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, // Evaluates a script in a provided context; falls back to the global one // if not specified. globalEval: function( code, options, doc ) { DOMEval( code, { nonce: options && options.nonce }, doc ); }, each: function( obj, callback ) { var length, i = 0; if ( isArrayLike( obj ) ) { length = obj.length; for ( ; i < length; i++ ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } else { for ( i in obj ) { if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { break; } } } return obj; }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { return arr == null ? -1 : indexOf.call( arr, elem, i ); }, // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; for ( ; j < len; j++ ) { first[ i++ ] = second[ j ]; } first.length = i; return first; }, grep: function( elems, callback, invert ) { var callbackInverse, matches = [], i = 0, length = elems.length, callbackExpect = !invert; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { callbackInverse = !callback( elems[ i ], i ); if ( callbackInverse !== callbackExpect ) { matches.push( elems[ i ] ); } } return matches; }, // arg is for internal usage only map: function( elems, callback, arg ) { var length, value, i = 0, ret = []; // Go through the array, translating each of the items to their new values if ( isArrayLike( elems ) ) { length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret.push( value ); } } } // Flatten any nested arrays return flat( ret ); }, // A global GUID counter for objects guid: 1, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support } ); if ( typeof Symbol === "function" ) { jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; } // Populate the class2type map jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), function( _i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); } ); function isArrayLike( obj ) { // Support: real iOS 8.2 only (not reproducible in simulator) // `in` check used to prevent JIT error (gh-2145) // hasOwn isn't used here due to false negatives // regarding Nodelist length in IE var length = !!obj && "length" in obj && obj.length, type = toType( obj ); if ( isFunction( obj ) || isWindow( obj ) ) { return false; } return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! * Sizzle CSS Selector Engine v2.3.6 * https://sizzlejs.com/ * * Copyright JS Foundation and other contributors * Released under the MIT license * https://js.foundation/ * * Date: 2021-02-16 */ ( function( window ) { var i, support, Expr, getText, isXML, tokenize, compile, select, outermostContext, sortInput, hasDuplicate, // Local document vars setDocument, document, docElem, documentIsHTML, rbuggyQSA, rbuggyMatches, matches, contains, // Instance-specific data expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), nonnativeSelectorCache = createCache(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ( {} ).hasOwnProperty, arr = [], pop = arr.pop, pushNative = arr.push, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf as it's faster than native // https://jsperf.com/thor-indexof-vs-for/5 indexOf = function( list, elem ) { var i = 0, len = list.length; for ( ; i < len; i++ ) { if ( list[ i ] === elem ) { return i; } } return -1; }, booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|" + "ismap|loop|multiple|open|readonly|required|scoped", // Regular expressions // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // https://www.w3.org/TR/css-syntax-3/#ident-token-diagram identifier = "(?:\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] // or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + // 2. simple (capture 6) "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" + // 3. anything else (capture 2) ".*" + ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ), rdescend = new RegExp( whitespace + "|>" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + identifier + ")" ), "CLASS": new RegExp( "^\\.(" + identifier + ")" ), "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), "bool": new RegExp( "^(?:" + booleans + ")$", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rhtml = /HTML$/i, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rnative = /^[^{]+\{\s*\[native \w/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, // CSS escapes // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\[\\da-fA-F]{1,6}" + whitespace + "?|\\\\([^\\r\\n\\f])", "g" ), funescape = function( escape, nonHex ) { var high = "0x" + escape.slice( 1 ) - 0x10000; return nonHex ? // Strip the backslash prefix from a non-hex escape sequence nonHex : // Replace a hexadecimal escape sequence with the encoded Unicode code point // Support: IE <=11+ // For values outside the Basic Multilingual Plane (BMP), manually construct a // surrogate pair high < 0 ? String.fromCharCode( high + 0x10000 ) : String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }, // CSS string/identifier serialization // https://drafts.csswg.org/cssom/#common-serializing-idioms rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g, fcssescape = function( ch, asCodePoint ) { if ( asCodePoint ) { // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER if ( ch === "\0" ) { return "\uFFFD"; } // Control characters and (dependent upon position) numbers get escaped as code points return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; } // Other potentially-special ASCII characters get backslash-escaped return "\\" + ch; }, // Used for iframes // See setDocument() // Removing the function wrapper causes a "Permission Denied" // error in IE unloadHandler = function() { setDocument(); }, inDisabledFieldset = addCombinator( function( elem ) { return elem.disabled === true && elem.nodeName.toLowerCase() === "fieldset"; }, { dir: "parentNode", next: "legend" } ); // Optimize for push.apply( _, NodeList ) try { push.apply( ( arr = slice.call( preferredDoc.childNodes ) ), preferredDoc.childNodes ); // Support: Android<4.0 // Detect silently failing push.apply // eslint-disable-next-line no-unused-expressions arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { pushNative.apply( target, slice.call( els ) ); } : // Support: IE<9 // Otherwise append directly function( target, els ) { var j = target.length, i = 0; // Can't trust NodeList.length while ( ( target[ j++ ] = els[ i++ ] ) ) {} target.length = j - 1; } }; } function Sizzle( selector, context, results, seed ) { var m, i, elem, nid, match, groups, newSelector, newContext = context && context.ownerDocument, // nodeType defaults to 9, since context defaults to document nodeType = context ? context.nodeType : 9; results = results || []; // Return early from calls with invalid selector or context if ( typeof selector !== "string" || !selector || nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { return results; } // Try to shortcut find operations (as opposed to filters) in HTML documents if ( !seed ) { setDocument( context ); context = context || document; if ( documentIsHTML ) { // If the selector is sufficiently simple, try using a "get*By*" DOM method // (excepting DocumentFragment context, where the methods don't exist) if ( nodeType !== 11 && ( match = rquickExpr.exec( selector ) ) ) { // ID selector if ( ( m = match[ 1 ] ) ) { // Document context if ( nodeType === 9 ) { if ( ( elem = context.getElementById( m ) ) ) { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } // Element context } else { // Support: IE, Opera, Webkit // TODO: identify versions // getElementById can match elements by name instead of ID if ( newContext && ( elem = newContext.getElementById( m ) ) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Type selector } else if ( match[ 2 ] ) { push.apply( results, context.getElementsByTagName( selector ) ); return results; // Class selector } else if ( ( m = match[ 3 ] ) && support.getElementsByClassName && context.getElementsByClassName ) { push.apply( results, context.getElementsByClassName( m ) ); return results; } } // Take advantage of querySelectorAll if ( support.qsa && !nonnativeSelectorCache[ selector + " " ] && ( !rbuggyQSA || !rbuggyQSA.test( selector ) ) && // Support: IE 8 only // Exclude object elements ( nodeType !== 1 || context.nodeName.toLowerCase() !== "object" ) ) { newSelector = selector; newContext = context; // qSA considers elements outside a scoping root when evaluating child or // descendant combinators, which is not what we want. // In such cases, we work around the behavior by prefixing every selector in the // list with an ID selector referencing the scope context. // The technique has to be used as well when a leading combinator is used // as such selectors are not recognized by querySelectorAll. // Thanks to Andrew Dupont for this technique. if ( nodeType === 1 && ( rdescend.test( selector ) || rcombinators.test( selector ) ) ) { // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; // We can use :scope instead of the ID hack if the browser // supports it & if we're not changing the context. if ( newContext !== context || !support.scope ) { // Capture the context ID, setting it first if necessary if ( ( nid = context.getAttribute( "id" ) ) ) { nid = nid.replace( rcssescape, fcssescape ); } else { context.setAttribute( "id", ( nid = expando ) ); } } // Prefix every selector in the list groups = tokenize( selector ); i = groups.length; while ( i-- ) { groups[ i ] = ( nid ? "#" + nid : ":scope" ) + " " + toSelector( groups[ i ] ); } newSelector = groups.join( "," ); } try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { nonnativeSelectorCache( selector, true ); } finally { if ( nid === expando ) { context.removeAttribute( "id" ); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Create key-value caches of limited size * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var keys = []; function cache( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key + " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return ( cache[ key + " " ] = value ); } return cache; } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { var el = document.createElement( "fieldset" ); try { return !!fn( el ); } catch ( e ) { return false; } finally { // Remove from its parent by default if ( el.parentNode ) { el.parentNode.removeChild( el ); } // release memory in IE el = null; } } /** * Adds the same handler for all of the specified attrs * @param {String} attrs Pipe-separated list of attributes * @param {Function} handler The method that will be applied */ function addHandle( attrs, handler ) { var arr = attrs.split( "|" ), i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[ i ] ] = handler; } } /** * Checks document order of two siblings * @param {Element} a * @param {Element} b * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b */ function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( ( cur = cur.nextSibling ) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } /** * Returns a function to use in pseudos for input types * @param {String} type */ function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } /** * Returns a function to use in pseudos for buttons * @param {String} type */ function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return ( name === "input" || name === "button" ) && elem.type === type; }; } /** * Returns a function to use in pseudos for :enabled/:disabled * @param {Boolean} disabled true for :disabled; false for :enabled */ function createDisabledPseudo( disabled ) { // Known :disabled false positives: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable return function( elem ) { // Only certain elements can match :enabled or :disabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-enabled // https://html.spec.whatwg.org/multipage/scripting.html#selector-disabled if ( "form" in elem ) { // Check for inherited disabledness on relevant non-disabled elements: // * listed form-associated elements in a disabled fieldset // https://html.spec.whatwg.org/multipage/forms.html#category-listed // https://html.spec.whatwg.org/multipage/forms.html#concept-fe-disabled // * option elements in a disabled optgroup // https://html.spec.whatwg.org/multipage/forms.html#concept-option-disabled // All such elements have a "form" property. if ( elem.parentNode && elem.disabled === false ) { // Option elements defer to a parent optgroup if present if ( "label" in elem ) { if ( "label" in elem.parentNode ) { return elem.parentNode.disabled === disabled; } else { return elem.disabled === disabled; } } // Support: IE 6 - 11 // Use the isDisabled shortcut property to check for disabled fieldset ancestors return elem.isDisabled === disabled || // Where there is no isDisabled, check manually /* jshint -W018 */ elem.isDisabled !== !disabled && inDisabledFieldset( elem ) === disabled; } return elem.disabled === disabled; // Try to winnow out elements that can't be disabled before trusting the disabled property. // Some victims get caught in our net (label, legend, menu, track), but it shouldn't // even exist on them, let alone have a boolean value. } else if ( "label" in elem ) { return elem.disabled === disabled; } // Remaining elements are neither :enabled nor :disabled return false; }; } /** * Returns a function to use in pseudos for positionals * @param {Function} fn */ function createPositionalPseudo( fn ) { return markFunction( function( argument ) { argument = +argument; return markFunction( function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ ( j = matchIndexes[ i ] ) ] ) { seed[ j ] = !( matches[ j ] = seed[ j ] ); } } } ); } ); } /** * Checks a node for validity as a Sizzle context * @param {Element|Object=} context * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value */ function testContext( context ) { return context && typeof context.getElementsByTagName !== "undefined" && context; } // Expose support vars for convenience support = Sizzle.support = {}; /** * Detects XML nodes * @param {Element|Object} elem An element or a document * @returns {Boolean} True iff elem is a non-HTML XML node */ isXML = Sizzle.isXML = function( elem ) { var namespace = elem && elem.namespaceURI, docElem = elem && ( elem.ownerDocument || elem ).documentElement; // Support: IE <=8 // Assume HTML when documentElement doesn't yet exist, such as inside loading iframes // https://bugs.jquery.com/ticket/4833 return !rhtml.test( namespace || docElem && docElem.nodeName || "HTML" ); }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var hasCompare, subWindow, doc = node ? node.ownerDocument || node : preferredDoc; // Return early if doc is invalid or already selected // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( doc == document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Update global variables document = doc; docElem = document.documentElement; documentIsHTML = !isXML( document ); // Support: IE 9 - 11+, Edge 12 - 18+ // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( preferredDoc != document && ( subWindow = document.defaultView ) && subWindow.top !== subWindow ) { // Support: IE 11, Edge if ( subWindow.addEventListener ) { subWindow.addEventListener( "unload", unloadHandler, false ); // Support: IE 9 - 10 only } else if ( subWindow.attachEvent ) { subWindow.attachEvent( "onunload", unloadHandler ); } } // Support: IE 8 - 11+, Edge 12 - 18+, Chrome <=16 - 25 only, Firefox <=3.6 - 31 only, // Safari 4 - 5 only, Opera <=11.6 - 12.x only // IE/Edge & older browsers don't support the :scope pseudo-class. // Support: Safari 6.0 only // Safari 6.0 supports :scope but it's an alias of :root there. support.scope = assert( function( el ) { docElem.appendChild( el ).appendChild( document.createElement( "div" ) ); return typeof el.querySelectorAll !== "undefined" && !el.querySelectorAll( ":scope fieldset div" ).length; } ); /* Attributes ---------------------------------------------------------------------- */ // Support: IE<8 // Verify that getAttribute really returns attributes and not properties // (excepting IE8 booleans) support.attributes = assert( function( el ) { el.className = "i"; return !el.getAttribute( "className" ); } ); /* getElement(s)By* ---------------------------------------------------------------------- */ // Check if getElementsByTagName("*") returns only elements support.getElementsByTagName = assert( function( el ) { el.appendChild( document.createComment( "" ) ); return !el.getElementsByTagName( "*" ).length; } ); // Support: IE<9 support.getElementsByClassName = rnative.test( document.getElementsByClassName ); // Support: IE<10 // Check if getElementById returns elements by name // The broken getElementById methods don't pick up programmatically-set names, // so use a roundabout getElementsByName test support.getById = assert( function( el ) { docElem.appendChild( el ).id = expando; return !document.getElementsByName || !document.getElementsByName( expando ).length; } ); // ID filter and find if ( support.getById ) { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute( "id" ) === attrId; }; }; Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var elem = context.getElementById( id ); return elem ? [ elem ] : []; } }; } else { Expr.filter[ "ID" ] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode( "id" ); return node && node.value === attrId; }; }; // Support: IE 6 - 7 only // getElementById is not reliable as a find shortcut Expr.find[ "ID" ] = function( id, context ) { if ( typeof context.getElementById !== "undefined" && documentIsHTML ) { var node, i, elems, elem = context.getElementById( id ); if ( elem ) { // Verify the id attribute node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } // Fall back on getElementsByName elems = context.getElementsByName( id ); i = 0; while ( ( elem = elems[ i++ ] ) ) { node = elem.getAttributeNode( "id" ); if ( node && node.value === id ) { return [ elem ]; } } } return []; } }; } // Tag Expr.find[ "TAG" ] = support.getElementsByTagName ? function( tag, context ) { if ( typeof context.getElementsByTagName !== "undefined" ) { return context.getElementsByTagName( tag ); // DocumentFragment nodes don't have gEBTN } else if ( support.qsa ) { return context.querySelectorAll( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, // By happy coincidence, a (broken) gEBTN appears on DocumentFragment nodes too results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( ( elem = results[ i++ ] ) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Class Expr.find[ "CLASS" ] = support.getElementsByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== "undefined" && documentIsHTML ) { return context.getElementsByClassName( className ); } }; /* QSA/matchesSelector ---------------------------------------------------------------------- */ // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21) // We allow this because of a bug in IE8/9 that throws an error // whenever `document.activeElement` is accessed on an iframe // So, we allow :focus to pass through QSA all the time to avoid the IE error // See https://bugs.jquery.com/ticket/13378 rbuggyQSA = []; if ( ( support.qsa = rnative.test( document.querySelectorAll ) ) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert( function( el ) { var input; // Select is set to empty string on purpose // This is to test IE's treatment of not explicitly // setting a boolean content attribute, // since its presence should be enough // https://bugs.jquery.com/ticket/12359 docElem.appendChild( el ).innerHTML = "<a id='" + expando + "'></a>" + "<select id='" + expando + "-\r\\' msallowcapture=''>" + "<option selected=''></option></select>"; // Support: IE8, Opera 11-12.16 // Nothing should be selected when empty strings follow ^= or $= or *= // The test attribute must be unknown in Opera but "safe" for WinRT // https://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section if ( el.querySelectorAll( "[msallowcapture^='']" ).length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" ); } // Support: IE8 // Boolean attributes and "value" are not treated correctly if ( !el.querySelectorAll( "[selected]" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" ); } // Support: Chrome<29, Android<4.4, Safari<7.0+, iOS<7.0+, PhantomJS<1.9.8+ if ( !el.querySelectorAll( "[id~=" + expando + "-]" ).length ) { rbuggyQSA.push( "~=" ); } // Support: IE 11+, Edge 15 - 18+ // IE 11/Edge don't find elements on a `[name='']` query in some cases. // Adding a temporary attribute to the document before the selection works // around the issue. // Interestingly, IE 10 & older don't seem to have the issue. input = document.createElement( "input" ); input.setAttribute( "name", "" ); el.appendChild( input ); if ( !el.querySelectorAll( "[name='']" ).length ) { rbuggyQSA.push( "\\[" + whitespace + "*name" + whitespace + "*=" + whitespace + "*(?:''|\"\")" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !el.querySelectorAll( ":checked" ).length ) { rbuggyQSA.push( ":checked" ); } // Support: Safari 8+, iOS 8+ // https://bugs.webkit.org/show_bug.cgi?id=136851 // In-page `selector#id sibling-combinator selector` fails if ( !el.querySelectorAll( "a#" + expando + "+*" ).length ) { rbuggyQSA.push( ".#.+[+~]" ); } // Support: Firefox <=3.6 - 5 only // Old Firefox doesn't throw on a badly-escaped identifier. el.querySelectorAll( "\\\f" ); rbuggyQSA.push( "[\\r\\n\\f]" ); } ); assert( function( el ) { el.innerHTML = "<a href='' disabled='disabled'></a>" + "<select disabled='disabled'><option/></select>"; // Support: Windows 8 Native Apps // The type and name attributes are restricted during .innerHTML assignment var input = document.createElement( "input" ); input.setAttribute( "type", "hidden" ); el.appendChild( input ).setAttribute( "name", "D" ); // Support: IE8 // Enforce case-sensitivity of name attribute if ( el.querySelectorAll( "[name=d]" ).length ) { rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( el.querySelectorAll( ":enabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: IE9-11+ // IE's :disabled selector does not pick up the children of disabled fieldsets docElem.appendChild( el ).disabled = true; if ( el.querySelectorAll( ":disabled" ).length !== 2 ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Support: Opera 10 - 11 only // Opera 10-11 does not throw on post-comma invalid pseudos el.querySelectorAll( "*,:x" ); rbuggyQSA.push( ",.*:" ); } ); } if ( ( support.matchesSelector = rnative.test( ( matches = docElem.matches || docElem.webkitMatchesSelector || docElem.mozMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector ) ) ) ) { assert( function( el ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( el, "*" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( el, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); } ); } rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join( "|" ) ); rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join( "|" ) ); /* Contains ---------------------------------------------------------------------- */ hasCompare = rnative.test( docElem.compareDocumentPosition ); // Element contains another // Purposefully self-exclusive // As in, an element does not contain itself contains = hasCompare || rnative.test( docElem.contains ) ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 ) ); } : function( a, b ) { if ( b ) { while ( ( b = b.parentNode ) ) { if ( b === a ) { return true; } } } return false; }; /* Sorting ---------------------------------------------------------------------- */ // Document order sorting sortOrder = hasCompare ? function( a, b ) { // Flag for duplicate removal if ( a === b ) { hasDuplicate = true; return 0; } // Sort on method existence if only one input has compareDocumentPosition var compare = !a.compareDocumentPosition - !b.compareDocumentPosition; if ( compare ) { return compare; } // Calculate position if both inputs belong to the same document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq compare = ( a.ownerDocument || a ) == ( b.ownerDocument || b ) ? a.compareDocumentPosition( b ) : // Otherwise we know they are disconnected 1; // Disconnected nodes if ( compare & 1 || ( !support.sortDetached && b.compareDocumentPosition( a ) === compare ) ) { // Choose the first element that is related to our preferred document // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( a == document || a.ownerDocument == preferredDoc && contains( preferredDoc, a ) ) { return -1; } // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( b == document || b.ownerDocument == preferredDoc && contains( preferredDoc, b ) ) { return 1; } // Maintain original order return sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; } return compare & 4 ? -1 : 1; } : function( a, b ) { // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; } var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Parentless nodes are either documents or disconnected if ( !aup || !bup ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ return a == document ? -1 : b == document ? 1 : /* eslint-enable eqeqeq */ aup ? -1 : bup ? 1 : sortInput ? ( indexOf( sortInput, a ) - indexOf( sortInput, b ) ) : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( ( cur = cur.parentNode ) ) { ap.unshift( cur ); } cur = b; while ( ( cur = cur.parentNode ) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[ i ] === bp[ i ] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[ i ], bp[ i ] ) : // Otherwise nodes in our document sort first // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. /* eslint-disable eqeqeq */ ap[ i ] == preferredDoc ? -1 : bp[ i ] == preferredDoc ? 1 : /* eslint-enable eqeqeq */ 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { setDocument( elem ); if ( support.matchesSelector && documentIsHTML && !nonnativeSelectorCache[ expr + " " ] && ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) && ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch ( e ) { nonnativeSelectorCache( expr, true ); } } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( context.ownerDocument || context ) != document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( ( elem.ownerDocument || elem ) != document ) { setDocument( elem ); } var fn = Expr.attrHandle[ name.toLowerCase() ], // Don't get fooled by Object.prototype properties (jQuery #13807) val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ? fn( elem, name, !documentIsHTML ) : undefined; return val !== undefined ? val : support.attributes || !documentIsHTML ? elem.getAttribute( name ) : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; }; Sizzle.escape = function( sel ) { return ( sel + "" ).replace( rcssescape, fcssescape ); }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; /** * Document sorting and removing duplicates * @param {ArrayLike} results */ Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], j = 0, i = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; sortInput = !support.sortStable && results.slice( 0 ); results.sort( sortOrder ); if ( hasDuplicate ) { while ( ( elem = results[ i++ ] ) ) { if ( elem === results[ i ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } // Clear input after sorting to release objects // See https://github.com/jquery/sizzle/pull/225 sortInput = null; return results; }; /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array while ( ( node = elem[ i++ ] ) ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (jQuery #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, attrHandle: {}, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[ 1 ] = match[ 1 ].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[ 3 ] = ( match[ 3 ] || match[ 4 ] || match[ 5 ] || "" ).replace( runescape, funescape ); if ( match[ 2 ] === "~=" ) { match[ 3 ] = " " + match[ 3 ] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[ 1 ] = match[ 1 ].toLowerCase(); if ( match[ 1 ].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[ 4 ] = +( match[ 4 ] ? match[ 5 ] + ( match[ 6 ] || 1 ) : 2 * ( match[ 3 ] === "even" || match[ 3 ] === "odd" ) ); match[ 5 ] = +( ( match[ 7 ] + match[ 8 ] ) || match[ 3 ] === "odd" ); // other types prohibit arguments } else if ( match[ 3 ] ) { Sizzle.error( match[ 0 ] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[ 6 ] && match[ 2 ]; if ( matchExpr[ "CHILD" ].test( match[ 0 ] ) ) { return null; } // Accept quoted arguments as-is if ( match[ 3 ] ) { match[ 2 ] = match[ 4 ] || match[ 5 ] || ""; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) ( excess = tokenize( unquoted, true ) ) && // advance to the next closing parenthesis ( excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length ) ) { // excess is a negative index match[ 0 ] = match[ 0 ].slice( 0, excess ); match[ 2 ] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeNameSelector ) { var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase(); return nodeNameSelector === "*" ? function() { return true; } : function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || ( pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" ) ) && classCache( className, function( elem ) { return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== "undefined" && elem.getAttribute( "class" ) || "" ); } ); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; /* eslint-disable max-len */ return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result.replace( rwhitespace, " " ) + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; /* eslint-enable max-len */ }; }, "CHILD": function( type, what, _argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, _context, xml ) { var cache, uniqueCache, outerCache, node, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType, diff = false; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( ( node = node[ dir ] ) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index // ...in a gzip-friendly way node = parent; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex && cache[ 2 ]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( ( node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start ( diff = nodeIndex = 0 ) || start.pop() ) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { uniqueCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } } else { // Use previously-cached element index if available if ( useCache ) { // ...in a gzip-friendly way node = elem; outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); cache = uniqueCache[ type ] || []; nodeIndex = cache[ 0 ] === dirruns && cache[ 1 ]; diff = nodeIndex; } // xml :nth-child(...) // or :nth-last-child(...) or :nth(-last)?-of-type(...) if ( diff === false ) { // Use the same loop as above to seek `elem` from the start while ( ( node = ++nodeIndex && node && node[ dir ] || ( diff = nodeIndex = 0 ) || start.pop() ) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { outerCache = node[ expando ] || ( node[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ node.uniqueID ] || ( outerCache[ node.uniqueID ] = {} ); uniqueCache[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction( function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf( seed, matched[ i ] ); seed[ idx ] = !( matches[ idx ] = matched[ i ] ); } } ) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction( function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction( function( seed, matches, _context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( ( elem = unmatched[ i ] ) ) { seed[ i ] = !( matches[ i ] = elem ); } } } ) : function( elem, _context, xml ) { input[ 0 ] = elem; matcher( input, null, xml, results ); // Don't keep the element (issue #299) input[ 0 ] = null; return !results.pop(); }; } ), "has": markFunction( function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; } ), "contains": markFunction( function( text ) { text = text.replace( runescape, funescape ); return function( elem ) { return ( elem.textContent || getText( elem ) ).indexOf( text ) > -1; }; } ), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifier if ( !ridentifier.test( lang || "" ) ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( ( elemLang = documentIsHTML ? elem.lang : elem.getAttribute( "xml:lang" ) || elem.getAttribute( "lang" ) ) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( ( elem = elem.parentNode ) && elem.nodeType === 1 ); return false; }; } ), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && ( !document.hasFocus || document.hasFocus() ) && !!( elem.type || elem.href || ~elem.tabIndex ); }, // Boolean properties "enabled": createDisabledPseudo( false ), "disabled": createDisabledPseudo( true ), "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return ( nodeName === "input" && !!elem.checked ) || ( nodeName === "option" && !!elem.selected ); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { // eslint-disable-next-line no-unused-expressions elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5), // but not by others (comment: 8; processing instruction: 7; etc.) // nodeType < 6 works because attributes (2) do not appear as children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeType < 6 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos[ "empty" ]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && // Support: IE<8 // New HTML5 attribute values (e.g., "search") appear with elem.type === "text" ( ( attr = elem.getAttribute( "type" ) ) == null || attr.toLowerCase() === "text" ); }, // Position-in-collection "first": createPositionalPseudo( function() { return [ 0 ]; } ), "last": createPositionalPseudo( function( _matchIndexes, length ) { return [ length - 1 ]; } ), "eq": createPositionalPseudo( function( _matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; } ), "even": createPositionalPseudo( function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "odd": createPositionalPseudo( function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; } ), "lt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument > length ? length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; } ), "gt": createPositionalPseudo( function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; } ) } }; Expr.pseudos[ "nth" ] = Expr.pseudos[ "eq" ]; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } // Easy API for creating new setFilters function setFilters() {} setFilters.prototype = Expr.filters = Expr.pseudos; Expr.setFilters = new setFilters(); tokenize = Sizzle.tokenize = function( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || ( match = rcomma.exec( soFar ) ) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[ 0 ].length ) || soFar; } groups.push( ( tokens = [] ) ); } matched = false; // Combinators if ( ( match = rcombinators.exec( soFar ) ) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[ 0 ].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( ( match = matchExpr[ type ].exec( soFar ) ) && ( !preFilters[ type ] || ( match = preFilters[ type ]( match ) ) ) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); }; function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[ i ].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, skip = combinator.next, key = skip || dir, checkNonElements = base && key === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } return false; } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var oldCache, uniqueCache, outerCache, newCache = [ dirruns, doneName ]; // We can't set arbitrary data on XML nodes, so they don't benefit from combinator caching if ( xml ) { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( ( elem = elem[ dir ] ) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || ( elem[ expando ] = {} ); // Support: IE <9 only // Defend against cloned attroperties (jQuery gh-1709) uniqueCache = outerCache[ elem.uniqueID ] || ( outerCache[ elem.uniqueID ] = {} ); if ( skip && skip === elem.nodeName.toLowerCase() ) { elem = elem[ dir ] || elem; } else if ( ( oldCache = uniqueCache[ key ] ) && oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) { // Assign to newCache so results back-propagate to previous elements return ( newCache[ 2 ] = oldCache[ 2 ] ); } else { // Reuse newcache so results back-propagate to previous elements uniqueCache[ key ] = newCache; // A match means we're done; a fail means we have to keep checking if ( ( newCache[ 2 ] = matcher( elem, context, xml ) ) ) { return true; } } } } } return false; }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[ i ]( elem, context, xml ) ) { return false; } } return true; } : matchers[ 0 ]; } function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[ i ], results ); } return results; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( ( elem = unmatched[ i ] ) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction( function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( ( elem = temp[ i ] ) ) { matcherOut[ postMap[ i ] ] = !( matcherIn[ postMap[ i ] ] = elem ); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) ) { // Restore matcherIn since elem is not yet a final match temp.push( ( matcherIn[ i ] = elem ) ); } } postFinder( null, ( matcherOut = [] ), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( ( elem = matcherOut[ i ] ) && ( temp = postFinder ? indexOf( seed, elem ) : preMap[ i ] ) > -1 ) { seed[ temp ] = !( results[ temp ] = elem ); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } } ); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[ 0 ].type ], implicitRelative = leadingRelative || Expr.relative[ " " ], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { var ret = ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( ( checkContext = context ).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); // Avoid hanging onto element (issue #299) checkContext = null; return ret; } ]; for ( ; i < len; i++ ) { if ( ( matcher = Expr.relative[ tokens[ i ].type ] ) ) { matchers = [ addCombinator( elementMatcher( matchers ), matcher ) ]; } else { matcher = Expr.filter[ tokens[ i ].type ].apply( null, tokens[ i ].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[ j ].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( // If the preceding token was a descendant combinator, insert an implicit any-element `*` tokens .slice( 0, i - 1 ) .concat( { value: tokens[ i - 2 ].type === " " ? "*" : "" } ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( ( tokens = tokens.slice( j ) ) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { var bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, outermost ) { var elem, j, matcher, matchedCount = 0, i = "0", unmatched = seed && [], setMatched = [], contextBackup = outermostContext, // We must always have either seed elements or outermost context elems = seed || byElement && Expr.find[ "TAG" ]( "*", outermost ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = ( dirruns += contextBackup == null ? 1 : Math.random() || 0.1 ), len = elems.length; if ( outermost ) { // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq outermostContext = context == document || context || outermost; } // Add elements passing elementMatchers directly to results // Support: IE<9, Safari // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id for ( ; i !== len && ( elem = elems[ i ] ) != null; i++ ) { if ( byElement && elem ) { j = 0; // Support: IE 11+, Edge 17 - 18+ // IE/Edge sometimes throw a "Permission denied" error when strict-comparing // two documents; shallow comparisons work. // eslint-disable-next-line eqeqeq if ( !context && elem.ownerDocument != document ) { setDocument( elem ); xml = !documentIsHTML; } while ( ( matcher = elementMatchers[ j++ ] ) ) { if ( matcher( elem, context || document, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( ( elem = !matcher && elem ) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // `i` is now the count of elements visited above, and adding it to `matchedCount` // makes the latter nonnegative. matchedCount += i; // Apply set filters to unmatched elements // NOTE: This can be skipped if there are no unmatched elements (i.e., `matchedCount` // equals `i`), unless we didn't visit _any_ elements in the above loop because we have // no element matchers and no seed. // Incrementing an initially-string "0" `i` allows `i` to remain a string only in that // case, which will result in a "00" `matchedCount` that differs from `i` but is also // numerically zero. if ( bySet && i !== matchedCount ) { j = 0; while ( ( matcher = setMatchers[ j++ ] ) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !( unmatched[ i ] || setMatched[ i ] ) ) { setMatched[ i ] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !match ) { match = tokenize( selector ); } i = match.length; while ( i-- ) { cached = matcherFromTokens( match[ i ] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); // Save selector and tokenization cached.selector = selector; } return cached; }; /** * A low-level selection function that works with Sizzle's compiled * selector functions * @param {String|Function} selector A selector or a pre-compiled * selector function built with Sizzle.compile * @param {Element} context * @param {Array} [results] * @param {Array} [seed] A set of elements to match against */ select = Sizzle.select = function( selector, context, results, seed ) { var i, tokens, token, type, find, compiled = typeof selector === "function" && selector, match = !seed && tokenize( ( selector = compiled.selector || selector ) ); results = results || []; // Try to minimize operations if there is only one selector in the list and no seed // (the latter of which guarantees us context) if ( match.length === 1 ) { // Reduce context if the leading compound selector is an ID tokens = match[ 0 ] = match[ 0 ].slice( 0 ); if ( tokens.length > 2 && ( token = tokens[ 0 ] ).type === "ID" && context.nodeType === 9 && documentIsHTML && Expr.relative[ tokens[ 1 ].type ] ) { context = ( Expr.find[ "ID" ]( token.matches[ 0 ] .replace( runescape, funescape ), context ) || [] )[ 0 ]; if ( !context ) { return results; // Precompiled matchers will still verify ancestry, so step up a level } else if ( compiled ) { context = context.parentNode; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr[ "needsContext" ].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[ i ]; // Abort if we hit a combinator if ( Expr.relative[ ( type = token.type ) ] ) { break; } if ( ( find = Expr.find[ type ] ) ) { // Search, expanding context for leading sibling combinators if ( ( seed = find( token.matches[ 0 ].replace( runescape, funescape ), rsibling.test( tokens[ 0 ].type ) && testContext( context.parentNode ) || context ) ) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, seed ); return results; } break; } } } } // Compile and execute a filtering function if one is not provided // Provide `match` to avoid retokenization if we modified the selector above ( compiled || compile( selector, match ) )( seed, context, !documentIsHTML, results, !context || rsibling.test( selector ) && testContext( context.parentNode ) || context ); return results; }; // One-time assignments // Sort stability support.sortStable = expando.split( "" ).sort( sortOrder ).join( "" ) === expando; // Support: Chrome 14-35+ // Always assume duplicates if they aren't passed to the comparison function support.detectDuplicates = !!hasDuplicate; // Initialize against the default document setDocument(); // Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27) // Detached nodes confoundingly follow *each other* support.sortDetached = assert( function( el ) { // Should return 1, but returns 4 (following) return el.compareDocumentPosition( document.createElement( "fieldset" ) ) & 1; } ); // Support: IE<8 // Prevent attribute/property "interpolation" // https://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !assert( function( el ) { el.innerHTML = "<a href='#'></a>"; return el.firstChild.getAttribute( "href" ) === "#"; } ) ) { addHandle( "type|href|height|width", function( elem, name, isXML ) { if ( !isXML ) { return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 ); } } ); } // Support: IE<9 // Use defaultValue in place of getAttribute("value") if ( !support.attributes || !assert( function( el ) { el.innerHTML = "<input/>"; el.firstChild.setAttribute( "value", "" ); return el.firstChild.getAttribute( "value" ) === ""; } ) ) { addHandle( "value", function( elem, _name, isXML ) { if ( !isXML && elem.nodeName.toLowerCase() === "input" ) { return elem.defaultValue; } } ); } // Support: IE<9 // Use getAttributeNode to fetch booleans when getAttribute lies if ( !assert( function( el ) { return el.getAttribute( "disabled" ) == null; } ) ) { addHandle( booleans, function( elem, name, isXML ) { var val; if ( !isXML ) { return elem[ name ] === true ? name.toLowerCase() : ( val = elem.getAttributeNode( name ) ) && val.specified ? val.value : null; } } ); } return Sizzle; } )( window ); jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; // Deprecated jQuery.expr[ ":" ] = jQuery.expr.pseudos; jQuery.uniqueSort = jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; jQuery.escapeSelector = Sizzle.escape; var dir = function( elem, dir, until ) { var matched = [], truncate = until !== undefined; while ( ( elem = elem[ dir ] ) && elem.nodeType !== 9 ) { if ( elem.nodeType === 1 ) { if ( truncate && jQuery( elem ).is( until ) ) { break; } matched.push( elem ); } } return matched; }; var siblings = function( n, elem ) { var matched = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { matched.push( n ); } } return matched; }; var rneedsContext = jQuery.expr.match.needsContext; function nodeName( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); } var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( isFunction( qualifier ) ) { return jQuery.grep( elements, function( elem, i ) { return !!qualifier.call( elem, i, elem ) !== not; } ); } // Single element if ( qualifier.nodeType ) { return jQuery.grep( elements, function( elem ) { return ( elem === qualifier ) !== not; } ); } // Arraylike of elements (jQuery, arguments, Array) if ( typeof qualifier !== "string" ) { return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not; } ); } // Filtered directly for both simple and complex selectors return jQuery.filter( qualifier, elements, not ); } jQuery.filter = function( expr, elems, not ) { var elem = elems[ 0 ]; if ( not ) { expr = ":not(" + expr + ")"; } if ( elems.length === 1 && elem.nodeType === 1 ) { return jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : []; } return jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) { return elem.nodeType === 1; } ) ); }; jQuery.fn.extend( { find: function( selector ) { var i, ret, len = this.length, self = this; if ( typeof selector !== "string" ) { return this.pushStack( jQuery( selector ).filter( function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } } ) ); } ret = this.pushStack( [] ); for ( i = 0; i < len; i++ ) { jQuery.find( selector, self[ i ], ret ); } return len > 1 ? jQuery.uniqueSort( ret ) : ret; }, filter: function( selector ) { return this.pushStack( winnow( this, selector || [], false ) ); }, not: function( selector ) { return this.pushStack( winnow( this, selector || [], true ) ); }, is: function( selector ) { return !!winnow( this, // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". typeof selector === "string" && rneedsContext.test( selector ) ? jQuery( selector ) : selector || [], false ).length; } } ); // Initialize a jQuery object // A central reference to the root jQuery(document) var rootjQuery, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) // Shortcut simple #id case for speed rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/, init = jQuery.fn.init = function( selector, context, root ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Method init() accepts an alternate rootjQuery // so migrate can support jQuery.sub (gh-2101) root = root || rootjQuery; // Handle HTML strings if ( typeof selector === "string" ) { if ( selector[ 0 ] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && ( match[ 1 ] || !context ) ) { // HANDLE: $(html) -> $(array) if ( match[ 1 ] ) { context = context instanceof jQuery ? context[ 0 ] : context; // Option to run scripts is true for back-compat // Intentionally let the error be thrown if parseHTML is not present jQuery.merge( this, jQuery.parseHTML( match[ 1 ], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[ 1 ] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[ 2 ] ); if ( elem ) { // Inject the element directly into the jQuery object this[ 0 ] = elem; this.length = 1; } return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || root ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this[ 0 ] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( isFunction( selector ) ) { return root.ready !== undefined ? root.ready( selector ) : // Execute immediately if ready is not present selector( jQuery ); } return jQuery.makeArray( selector, this ); }; // Give the init function the jQuery prototype for later instantiation init.prototype = jQuery.fn; // Initialize central reference rootjQuery = jQuery( document ); var rparentsprev = /^(?:parents|prev(?:Until|All))/, // Methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend( { has: function( target ) { var targets = jQuery( target, this ), l = targets.length; return this.filter( function() { var i = 0; for ( ; i < l; i++ ) { if ( jQuery.contains( this, targets[ i ] ) ) { return true; } } } ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, matched = [], targets = typeof selectors !== "string" && jQuery( selectors ); // Positional selectors never match, since there's no _selection_ context if ( !rneedsContext.test( selectors ) ) { for ( ; i < l; i++ ) { for ( cur = this[ i ]; cur && cur !== context; cur = cur.parentNode ) { // Always skip document fragments if ( cur.nodeType < 11 && ( targets ? targets.index( cur ) > -1 : // Don't pass non-elements to Sizzle cur.nodeType === 1 && jQuery.find.matchesSelector( cur, selectors ) ) ) { matched.push( cur ); break; } } } } return this.pushStack( matched.length > 1 ? jQuery.uniqueSort( matched ) : matched ); }, // Determine the position of an element within the set index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1; } // Index in selector if ( typeof elem === "string" ) { return indexOf.call( jQuery( elem ), this[ 0 ] ); } // Locate the position of the desired element return indexOf.call( this, // If it receives a jQuery object, the first element is used elem.jquery ? elem[ 0 ] : elem ); }, add: function( selector, context ) { return this.pushStack( jQuery.uniqueSort( jQuery.merge( this.get(), jQuery( selector, context ) ) ) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter( selector ) ); } } ); function sibling( cur, dir ) { while ( ( cur = cur[ dir ] ) && cur.nodeType !== 1 ) {} return cur; } jQuery.each( { parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return dir( elem, "parentNode" ); }, parentsUntil: function( elem, _i, until ) { return dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return dir( elem, "previousSibling" ); }, nextUntil: function( elem, _i, until ) { return dir( elem, "nextSibling", until ); }, prevUntil: function( elem, _i, until ) { return dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return siblings( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return siblings( elem.firstChild ); }, contents: function( elem ) { if ( elem.contentDocument != null && // Support: IE 11+ // <object> elements with no `data` attribute has an object // `contentDocument` with a `null` prototype. getProto( elem.contentDocument ) ) { return elem.contentDocument; } // Support: IE 9 - 11 only, iOS 7 only, Android Browser <=4.3 only // Treat the template element as a regular one in browsers that // don't support it. if ( nodeName( elem, "template" ) ) { elem = elem.content || elem; } return jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var matched = jQuery.map( this, fn, until ); if ( name.slice( -5 ) !== "Until" ) { selector = until; } if ( selector && typeof selector === "string" ) { matched = jQuery.filter( selector, matched ); } if ( this.length > 1 ) { // Remove duplicates if ( !guaranteedUnique[ name ] ) { jQuery.uniqueSort( matched ); } // Reverse order for parents* and prev-derivatives if ( rparentsprev.test( name ) ) { matched.reverse(); } } return this.pushStack( matched ); }; } ); var rnothtmlwhite = ( /[^\x20\t\r\n\f]+/g ); // Convert String-formatted options into Object-formatted ones function createOptions( options ) { var object = {}; jQuery.each( options.match( rnothtmlwhite ) || [], function( _, flag ) { object[ flag ] = true; } ); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? createOptions( options ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value for non-forgettable lists memory, // Flag to know if list was already fired fired, // Flag to prevent firing locked, // Actual callback list list = [], // Queue of execution data for repeatable lists queue = [], // Index of currently firing callback (modified by add/remove as needed) firingIndex = -1, // Fire callbacks fire = function() { // Enforce single-firing locked = locked || options.once; // Execute callbacks for all pending executions, // respecting firingIndex overrides and runtime changes fired = firing = true; for ( ; queue.length; firingIndex = -1 ) { memory = queue.shift(); while ( ++firingIndex < list.length ) { // Run callback and check for early termination if ( list[ firingIndex ].apply( memory[ 0 ], memory[ 1 ] ) === false && options.stopOnFalse ) { // Jump to end and forget the data so .add doesn't re-fire firingIndex = list.length; memory = false; } } } // Forget the data if we're done with it if ( !options.memory ) { memory = false; } firing = false; // Clean up if we're done firing for good if ( locked ) { // Keep an empty list if we have data for future add calls if ( memory ) { list = []; // Otherwise, this object is spent } else { list = ""; } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // If we have memory from a past run, we should fire after adding if ( memory && !firing ) { firingIndex = list.length - 1; queue.push( memory ); } ( function add( args ) { jQuery.each( args, function( _, arg ) { if ( isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && toType( arg ) !== "string" ) { // Inspect recursively add( arg ); } } ); } )( arguments ); if ( memory && !firing ) { fire(); } } return this; }, // Remove a callback from the list remove: function() { jQuery.each( arguments, function( _, arg ) { var index; while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( index <= firingIndex ) { firingIndex--; } } } ); return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : list.length > 0; }, // Remove all callbacks from the list empty: function() { if ( list ) { list = []; } return this; }, // Disable .fire and .add // Abort any current/pending executions // Clear all callbacks and values disable: function() { locked = queue = []; list = memory = ""; return this; }, disabled: function() { return !list; }, // Disable .fire // Also disable .add unless we have memory (since it would have no effect) // Abort any pending executions lock: function() { locked = queue = []; if ( !memory && !firing ) { list = memory = ""; } return this; }, locked: function() { return !!locked; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { if ( !locked ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; queue.push( args ); if ( !firing ) { fire(); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; function Identity( v ) { return v; } function Thrower( ex ) { throw ex; } function adoptValue( value, resolve, reject, noValue ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Control `resolve` arguments by letting Array#slice cast boolean `noValue` to integer: // * false: [ value ].slice( 0 ) => resolve( value ) // * true: [ value ].slice( 1 ) => resolve() resolve.apply( undefined, [ value ].slice( noValue ) ); } // For Promises/A+, convert exceptions into rejections // Since jQuery.when doesn't unwrap thenables, we can skip the extra checks appearing in // Deferred#then to conditionally suppress rejection. } catch ( value ) { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context reject.apply( undefined, [ value ] ); } } jQuery.extend( { Deferred: function( func ) { var tuples = [ // action, add listener, callbacks, // ... .then handlers, argument index, [final state] [ "notify", "progress", jQuery.Callbacks( "memory" ), jQuery.Callbacks( "memory" ), 2 ], [ "resolve", "done", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 0, "resolved" ], [ "reject", "fail", jQuery.Callbacks( "once memory" ), jQuery.Callbacks( "once memory" ), 1, "rejected" ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, "catch": function( fn ) { return promise.then( null, fn ); }, // Keep pipe for back-compat pipe: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred( function( newDefer ) { jQuery.each( tuples, function( _i, tuple ) { // Map tuples (progress, done, fail) to arguments (done, fail, progress) var fn = isFunction( fns[ tuple[ 4 ] ] ) && fns[ tuple[ 4 ] ]; // deferred.progress(function() { bind to newDefer or newDefer.notify }) // deferred.done(function() { bind to newDefer or newDefer.resolve }) // deferred.fail(function() { bind to newDefer or newDefer.reject }) deferred[ tuple[ 1 ] ]( function() { var returned = fn && fn.apply( this, arguments ); if ( returned && isFunction( returned.promise ) ) { returned.promise() .progress( newDefer.notify ) .done( newDefer.resolve ) .fail( newDefer.reject ); } else { newDefer[ tuple[ 0 ] + "With" ]( this, fn ? [ returned ] : arguments ); } } ); } ); fns = null; } ).promise(); }, then: function( onFulfilled, onRejected, onProgress ) { var maxDepth = 0; function resolve( depth, deferred, handler, special ) { return function() { var that = this, args = arguments, mightThrow = function() { var returned, then; // Support: Promises/A+ section 2.3.3.3.3 // https://promisesaplus.com/#point-59 // Ignore double-resolution attempts if ( depth < maxDepth ) { return; } returned = handler.apply( that, args ); // Support: Promises/A+ section 2.3.1 // https://promisesaplus.com/#point-48 if ( returned === deferred.promise() ) { throw new TypeError( "Thenable self-resolution" ); } // Support: Promises/A+ sections 2.3.3.1, 3.5 // https://promisesaplus.com/#point-54 // https://promisesaplus.com/#point-75 // Retrieve `then` only once then = returned && // Support: Promises/A+ section 2.3.4 // https://promisesaplus.com/#point-64 // Only check objects and functions for thenability ( typeof returned === "object" || typeof returned === "function" ) && returned.then; // Handle a returned thenable if ( isFunction( then ) ) { // Special processors (notify) just wait for resolution if ( special ) { then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ) ); // Normal processors (resolve) also hook into progress } else { // ...and disregard older resolution values maxDepth++; then.call( returned, resolve( maxDepth, deferred, Identity, special ), resolve( maxDepth, deferred, Thrower, special ), resolve( maxDepth, deferred, Identity, deferred.notifyWith ) ); } // Handle all other returned values } else { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Identity ) { that = undefined; args = [ returned ]; } // Process the value(s) // Default process is resolve ( special || deferred.resolveWith )( that, args ); } }, // Only normal processors (resolve) catch and reject exceptions process = special ? mightThrow : function() { try { mightThrow(); } catch ( e ) { if ( jQuery.Deferred.exceptionHook ) { jQuery.Deferred.exceptionHook( e, process.stackTrace ); } // Support: Promises/A+ section 2.3.3.3.4.1 // https://promisesaplus.com/#point-61 // Ignore post-resolution exceptions if ( depth + 1 >= maxDepth ) { // Only substitute handlers pass on context // and multiple values (non-spec behavior) if ( handler !== Thrower ) { that = undefined; args = [ e ]; } deferred.rejectWith( that, args ); } } }; // Support: Promises/A+ section 2.3.3.3.1 // https://promisesaplus.com/#point-57 // Re-resolve promises immediately to dodge false rejection from // subsequent errors if ( depth ) { process(); } else { // Call an optional hook to record the stack, in case of exception // since it's otherwise lost when execution goes async if ( jQuery.Deferred.getStackHook ) { process.stackTrace = jQuery.Deferred.getStackHook(); } window.setTimeout( process ); } }; } return jQuery.Deferred( function( newDefer ) { // progress_handlers.add( ... ) tuples[ 0 ][ 3 ].add( resolve( 0, newDefer, isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, isFunction( onRejected ) ? onRejected : Thrower ) ); } ).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 5 ]; // promise.progress = list.add // promise.done = list.add // promise.fail = list.add promise[ tuple[ 1 ] ] = list.add; // Handle state if ( stateString ) { list.add( function() { // state = "resolved" (i.e., fulfilled) // state = "rejected" state = stateString; }, // rejected_callbacks.disable // fulfilled_callbacks.disable tuples[ 3 - i ][ 2 ].disable, // rejected_handlers.disable // fulfilled_handlers.disable tuples[ 3 - i ][ 3 ].disable, // progress_callbacks.lock tuples[ 0 ][ 2 ].lock, // progress_handlers.lock tuples[ 0 ][ 3 ].lock ); } // progress_handlers.fire // fulfilled_handlers.fire // rejected_handlers.fire list.add( tuple[ 3 ].fire ); // deferred.notify = function() { deferred.notifyWith(...) } // deferred.resolve = function() { deferred.resolveWith(...) } // deferred.reject = function() { deferred.rejectWith(...) } deferred[ tuple[ 0 ] ] = function() { deferred[ tuple[ 0 ] + "With" ]( this === deferred ? undefined : this, arguments ); return this; }; // deferred.notifyWith = list.fireWith // deferred.resolveWith = list.fireWith // deferred.rejectWith = list.fireWith deferred[ tuple[ 0 ] + "With" ] = list.fireWith; } ); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( singleValue ) { var // count of uncompleted subordinates remaining = arguments.length, // count of unprocessed arguments i = remaining, // subordinate fulfillment data resolveContexts = Array( i ), resolveValues = slice.call( arguments ), // the primary Deferred primary = jQuery.Deferred(), // subordinate callback factory updateFunc = function( i ) { return function( value ) { resolveContexts[ i ] = this; resolveValues[ i ] = arguments.length > 1 ? slice.call( arguments ) : value; if ( !( --remaining ) ) { primary.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, primary.done( updateFunc( i ) ).resolve, primary.reject, !remaining ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( primary.state() === "pending" || isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return primary.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), primary.reject ); } return primary.promise(); } } ); // These usually indicate a programmer mistake during development, // warn about them ASAP rather than swallowing them by default. var rerrorNames = /^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/; jQuery.Deferred.exceptionHook = function( error, stack ) { // Support: IE 8 - 9 only // Console exists when dev tools are open, which can happen at any time if ( window.console && window.console.warn && error && rerrorNames.test( error.name ) ) { window.console.warn( "jQuery.Deferred exception: " + error.message, error.stack, stack ); } }; jQuery.readyException = function( error ) { window.setTimeout( function() { throw error; } ); }; // The deferred used on DOM ready var readyList = jQuery.Deferred(); jQuery.fn.ready = function( fn ) { readyList .then( fn ) // Wrap jQuery.readyException in a function so that the lookup // happens at the time of error handling instead of callback // registration. .catch( function( error ) { jQuery.readyException( error ); } ); return this; }; jQuery.extend( { // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); } } ); jQuery.ready.then = readyList.then; // The ready event handler and self cleanup method function completed() { document.removeEventListener( "DOMContentLoaded", completed ); window.removeEventListener( "load", completed ); jQuery.ready(); } // Catch cases where $(document).ready() is called // after the browser event has already occurred. // Support: IE <=9 - 10 only // Older IE sometimes signals "interactive" too soon if ( document.readyState === "complete" || ( document.readyState !== "loading" && !document.documentElement.doScroll ) ) { // Handle it asynchronously to allow scripts the opportunity to delay ready window.setTimeout( jQuery.ready ); } else { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed ); } // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function var access = function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, len = elems.length, bulk = key == null; // Sets many values if ( toType( key ) === "object" ) { chainable = true; for ( i in key ) { access( elems, fn, i, key[ i ], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, _key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < len; i++ ) { fn( elems[ i ], key, raw ? value : value.call( elems[ i ], i, fn( elems[ i ], key ) ) ); } } } if ( chainable ) { return elems; } // Gets if ( bulk ) { return fn.call( elems ); } return len ? fn( elems[ 0 ], key ) : emptyGet; }; // Matches dashed string for camelizing var rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g; // Used by camelCase as callback to replace() function fcamelCase( _all, letter ) { return letter.toUpperCase(); } // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 15 // Microsoft forgot to hump their vendor prefix (#9572) function camelCase( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); } var acceptData = function( owner ) { // Accepts only: // - Node // - Node.ELEMENT_NODE // - Node.DOCUMENT_NODE // - Object // - Any return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType ); }; function Data() { this.expando = jQuery.expando + Data.uid++; } Data.uid = 1; Data.prototype = { cache: function( owner ) { // Check if the owner object already has a cache var value = owner[ this.expando ]; // If not, create one if ( !value ) { value = {}; // We can accept data for non-element nodes in modern browsers, // but we should not, see #8335. // Always return an empty object. if ( acceptData( owner ) ) { // If it is a node unlikely to be stringify-ed or looped over // use plain assignment if ( owner.nodeType ) { owner[ this.expando ] = value; // Otherwise secure it in a non-enumerable property // configurable must be true to allow the property to be // deleted when data is removed } else { Object.defineProperty( owner, this.expando, { value: value, configurable: true } ); } } } return value; }, set: function( owner, data, value ) { var prop, cache = this.cache( owner ); // Handle: [ owner, key, value ] args // Always use camelCase key (gh-2257) if ( typeof data === "string" ) { cache[ camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ camelCase( prop ) ] = data[ prop ]; } } return cache; }, get: function( owner, key ) { return key === undefined ? this.cache( owner ) : // Always use camelCase key (gh-2257) owner[ this.expando ] && owner[ this.expando ][ camelCase( key ) ]; }, access: function( owner, key, value ) { // In cases where either: // // 1. No key was specified // 2. A string key was specified, but no value provided // // Take the "read" path and allow the get method to determine // which value to return, respectively either: // // 1. The entire cache object // 2. The data stored at the key // if ( key === undefined || ( ( key && typeof key === "string" ) && value === undefined ) ) { return this.get( owner, key ); } // When the key is not a string, or both a key and value // are specified, set or extend (existing objects) with either: // // 1. An object of properties // 2. A key and value // this.set( owner, key, value ); // Since the "set" path can have two possible entry points // return the expected data based on which path was taken[*] return value !== undefined ? value : key; }, remove: function( owner, key ) { var i, cache = owner[ this.expando ]; if ( cache === undefined ) { return; } if ( key !== undefined ) { // Support array or space separated string of keys if ( Array.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( camelCase ); } else { key = camelCase( key ); // If a key with the spaces exists, use it. // Otherwise, create an array by matching non-whitespace key = key in cache ? [ key ] : ( key.match( rnothtmlwhite ) || [] ); } i = key.length; while ( i-- ) { delete cache[ key[ i ] ]; } } // Remove the expando if there's no more data if ( key === undefined || jQuery.isEmptyObject( cache ) ) { // Support: Chrome <=35 - 45 // Webkit & Blink performance suffers when deleting properties // from DOM nodes, so set to undefined instead // https://bugs.chromium.org/p/chromium/issues/detail?id=378607 (bug restricted) if ( owner.nodeType ) { owner[ this.expando ] = undefined; } else { delete owner[ this.expando ]; } } }, hasData: function( owner ) { var cache = owner[ this.expando ]; return cache !== undefined && !jQuery.isEmptyObject( cache ); } }; var dataPriv = new Data(); var dataUser = new Data(); // Implementation Summary // // 1. Enforce API surface and semantic compatibility with 1.9.x branch // 2. Improve the module's maintainability by reducing the storage // paths to a single mechanism. // 3. Use the same single mechanism to support "private" and "user" data. // 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData) // 5. Avoid exposing implementation details on user objects (eg. expando properties) // 6. Provide a clear path for implementation upgrade to WeakMap in 2014 var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/, rmultiDash = /[A-Z]/g; function getData( data ) { if ( data === "true" ) { return true; } if ( data === "false" ) { return false; } if ( data === "null" ) { return null; } // Only convert to a number if it doesn't change the string if ( data === +data + "" ) { return +data; } if ( rbrace.test( data ) ) { return JSON.parse( data ); } return data; } function dataAttr( elem, key, data ) { var name; // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { name = "data-" + key.replace( rmultiDash, "-$&" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = getData( data ); } catch ( e ) {} // Make sure we set the data so it isn't changed later dataUser.set( elem, key, data ); } else { data = undefined; } } return data; } jQuery.extend( { hasData: function( elem ) { return dataUser.hasData( elem ) || dataPriv.hasData( elem ); }, data: function( elem, name, data ) { return dataUser.access( elem, name, data ); }, removeData: function( elem, name ) { dataUser.remove( elem, name ); }, // TODO: Now that all calls to _data and _removeData have been replaced // with direct calls to dataPriv methods, these can be deprecated. _data: function( elem, name, data ) { return dataPriv.access( elem, name, data ); }, _removeData: function( elem, name ) { dataPriv.remove( elem, name ); } } ); jQuery.fn.extend( { data: function( key, value ) { var i, name, data, elem = this[ 0 ], attrs = elem && elem.attributes; // Gets all values if ( key === undefined ) { if ( this.length ) { data = dataUser.get( elem ); if ( elem.nodeType === 1 && !dataPriv.get( elem, "hasDataAttrs" ) ) { i = attrs.length; while ( i-- ) { // Support: IE 11 only // The attrs elements can be null (#14894) if ( attrs[ i ] ) { name = attrs[ i ].name; if ( name.indexOf( "data-" ) === 0 ) { name = camelCase( name.slice( 5 ) ); dataAttr( elem, name, data[ name ] ); } } } dataPriv.set( elem, "hasDataAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each( function() { dataUser.set( this, key ); } ); } return access( this, function( value ) { var data; // The calling jQuery object (element matches) is not empty // (and therefore has an element appears at this[ 0 ]) and the // `value` parameter was not undefined. An empty jQuery object // will result in `undefined` for elem = this[ 0 ] which will // throw an exception if an attempt to read a data cache is made. if ( elem && value === undefined ) { // Attempt to get data from the cache // The key will always be camelCased in Data data = dataUser.get( elem, key ); if ( data !== undefined ) { return data; } // Attempt to "discover" the data in // HTML5 custom data-* attrs data = dataAttr( elem, key ); if ( data !== undefined ) { return data; } // We tried really hard, but the data doesn't exist. return; } // Set the data... this.each( function() { // We always store the camelCased key dataUser.set( this, key, value ); } ); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each( function() { dataUser.remove( this, key ); } ); } } ); jQuery.extend( { queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = dataPriv.get( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || Array.isArray( data ) ) { queue = dataPriv.access( elem, type, jQuery.makeArray( data ) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // Clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // Not public - generate a queueHooks object, or return the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return dataPriv.get( elem, key ) || dataPriv.access( elem, key, { empty: jQuery.Callbacks( "once memory" ).add( function() { dataPriv.remove( elem, [ type + "queue", key ] ); } ) } ); } } ); jQuery.fn.extend( { queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[ 0 ], type ); } return data === undefined ? this : this.each( function() { var queue = jQuery.queue( this, type, data ); // Ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[ 0 ] !== "inprogress" ) { jQuery.dequeue( this, type ); } } ); }, dequeue: function( type ) { return this.each( function() { jQuery.dequeue( this, type ); } ); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while ( i-- ) { tmp = dataPriv.get( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } } ); var pnum = ( /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/ ).source; var rcssNum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ); var cssExpand = [ "Top", "Right", "Bottom", "Left" ]; var documentElement = document.documentElement; var isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ); }, composed = { composed: true }; // Support: IE 9 - 11+, Edge 12 - 18+, iOS 10.0 - 10.2 only // Check attachment across shadow DOM boundaries when possible (gh-3504) // Support: iOS 10.0-10.2 only // Early iOS 10 versions support `attachShadow` but not `getRootNode`, // leading to errors. We need to check for `getRootNode`. if ( documentElement.getRootNode ) { isAttached = function( elem ) { return jQuery.contains( elem.ownerDocument, elem ) || elem.getRootNode( composed ) === elem.ownerDocument; }; } var isHiddenWithinTree = function( elem, el ) { // isHiddenWithinTree might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; // Inline style trumps all return elem.style.display === "none" || elem.style.display === "" && // Otherwise, check computed style // Support: Firefox <=43 - 45 // Disconnected elements can have computed display: none, so first confirm that elem is // in the document. isAttached( elem ) && jQuery.css( elem, "display" ) === "none"; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale, maxIterations = 20, currentValue = tween ? function() { return tween.cur(); } : function() { return jQuery.css( elem, prop, "" ); }, initial = currentValue(), unit = valueParts && valueParts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ), // Starting value computation is required for potential unit mismatches initialInUnit = elem.nodeType && ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Support: Firefox <=54 // Halve the iteration target value to prevent interference from CSS upper bounds (gh-2144) initial = initial / 2; // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; while ( maxIterations-- ) { // Evaluate and update our best guess (doubling guesses that zero out). // Finish if the scale equals or crosses 1 (making the old*new product non-positive). jQuery.style( elem, prop, initialInUnit + unit ); if ( ( 1 - scale ) * ( 1 - ( scale = currentValue() / initial || 0.5 ) ) <= 0 ) { maxIterations = 0; } initialInUnit = initialInUnit / scale; } initialInUnit = initialInUnit * 2; jQuery.style( elem, prop, initialInUnit + unit ); // Make sure we update the tween properties later on valueParts = valueParts || []; } if ( valueParts ) { initialInUnit = +initialInUnit || +initial || 0; // Apply relative offset (+=/-=) if specified adjusted = valueParts[ 1 ] ? initialInUnit + ( valueParts[ 1 ] + 1 ) * valueParts[ 2 ] : +valueParts[ 2 ]; if ( tween ) { tween.unit = unit; tween.start = initialInUnit; tween.end = adjusted; } } return adjusted; } var defaultDisplayMap = {}; function getDefaultDisplay( elem ) { var temp, doc = elem.ownerDocument, nodeName = elem.nodeName, display = defaultDisplayMap[ nodeName ]; if ( display ) { return display; } temp = doc.body.appendChild( doc.createElement( nodeName ) ); display = jQuery.css( temp, "display" ); temp.parentNode.removeChild( temp ); if ( display === "none" ) { display = "block"; } defaultDisplayMap[ nodeName ] = display; return display; } function showHide( elements, show ) { var display, elem, values = [], index = 0, length = elements.length; // Determine new display value for elements that need to change for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } display = elem.style.display; if ( show ) { // Since we force visibility upon cascade-hidden elements, an immediate (and slow) // check is required in this first loop unless we have a nonempty display value (either // inline or about-to-be-restored) if ( display === "none" ) { values[ index ] = dataPriv.get( elem, "display" ) || null; if ( !values[ index ] ) { elem.style.display = ""; } } if ( elem.style.display === "" && isHiddenWithinTree( elem ) ) { values[ index ] = getDefaultDisplay( elem ); } } else { if ( display !== "none" ) { values[ index ] = "none"; // Remember what we're overwriting dataPriv.set( elem, "display", display ); } } } // Set the display of the elements in a second loop to avoid constant reflow for ( index = 0; index < length; index++ ) { if ( values[ index ] != null ) { elements[ index ].style.display = values[ index ]; } } return elements; } jQuery.fn.extend( { show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each( function() { if ( isHiddenWithinTree( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } } ); } } ); var rcheckableType = ( /^(?:checkbox|radio)$/i ); var rtagName = ( /<([a-z][^\/\0>\x20\t\r\n\f]*)/i ); var rscriptType = ( /^$|^module$|\/(?:java|ecma)script/i ); ( function() { var fragment = document.createDocumentFragment(), div = fragment.appendChild( document.createElement( "div" ) ), input = document.createElement( "input" ); // Support: Android 4.0 - 4.3 only // Check state lost if the name is set (#11217) // Support: Windows Web Apps (WWA) // `name` and `type` must use .setAttribute for WWA (#14901) input.setAttribute( "type", "radio" ); input.setAttribute( "checked", "checked" ); input.setAttribute( "name", "t" ); div.appendChild( input ); // Support: Android <=4.1 only // Older WebKit doesn't clone checked state correctly in fragments support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE <=11 only // Make sure textarea (and checkbox) defaultValue is properly cloned div.innerHTML = "<textarea>x</textarea>"; support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue; // Support: IE <=9 only // IE <=9 replaces <option> tags with their contents when inserted outside of // the select element. div.innerHTML = "<option></option>"; support.option = !!div.lastChild; } )(); // We have to close these tags to support XHTML (#13200) var wrapMap = { // XHTML parsers do not magically insert elements in the // same way that tag soup parsers do. So we cannot shorten // this by omitting <tbody> or other required elements. thead: [ 1, "<table>", "</table>" ], col: [ 2, "<table><colgroup>", "</colgroup></table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], _default: [ 0, "", "" ] }; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; // Support: IE <=9 only if ( !support.option ) { wrapMap.optgroup = wrapMap.option = [ 1, "<select multiple='multiple'>", "</select>" ]; } function getAll( context, tag ) { // Support: IE <=9 - 11 only // Use typeof to avoid zero-argument method invocation on host objects (#15151) var ret; if ( typeof context.getElementsByTagName !== "undefined" ) { ret = context.getElementsByTagName( tag || "*" ); } else if ( typeof context.querySelectorAll !== "undefined" ) { ret = context.querySelectorAll( tag || "*" ); } else { ret = []; } if ( tag === undefined || tag && nodeName( context, tag ) ) { return jQuery.merge( [ context ], ret ); } return ret; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var i = 0, l = elems.length; for ( ; i < l; i++ ) { dataPriv.set( elems[ i ], "globalEval", !refElements || dataPriv.get( refElements[ i ], "globalEval" ) ); } } var rhtml = /<|&#?\w+;/; function buildFragment( elems, context, scripts, selection, ignored ) { var elem, tmp, tag, wrap, attached, j, fragment = context.createDocumentFragment(), nodes = [], i = 0, l = elems.length; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( toType( elem ) === "object" ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || fragment.appendChild( context.createElement( "div" ) ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[ 1 ] + jQuery.htmlPrefilter( elem ) + wrap[ 2 ]; // Descend through wrappers to the right content j = wrap[ 0 ]; while ( j-- ) { tmp = tmp.lastChild; } // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( nodes, tmp.childNodes ); // Remember the top-level container tmp = fragment.firstChild; // Ensure the created nodes are orphaned (#12392) tmp.textContent = ""; } } } // Remove wrapper from fragment fragment.textContent = ""; i = 0; while ( ( elem = nodes[ i++ ] ) ) { // Skip elements already in the context collection (trac-4087) if ( selection && jQuery.inArray( elem, selection ) > -1 ) { if ( ignored ) { ignored.push( elem ); } continue; } attached = isAttached( elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( attached ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } var rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 - 11+ // focus() and blur() are asynchronous, except when they are no-op. // So expect focus to be synchronous when the element is already active, // and blur to be synchronous when the element is not already active. // (focus and blur are always synchronous in other supported browsers, // this just defines when we can count on it). function expectSync( elem, type ) { return ( elem === safeActiveElement() ) === ( type === "focus" ); } // Support: IE <=9 only // Accessing document.activeElement can throw unexpectedly // https://bugs.jquery.com/ticket/13393 function safeActiveElement() { try { return document.activeElement; } catch ( err ) { } } function on( elem, types, selector, data, fn, one ) { var origFn, type; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { on( elem, type, selector, data, types[ type ], one ); } return elem; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return elem; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return elem.each( function() { jQuery.event.add( this, types, fn, data, selector ); } ); } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var handleObjIn, eventHandle, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.get( elem ); // Only attach events to objects that accept data if ( !acceptData( elem ) ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Ensure that invalid selectors throw exceptions at attach time // Evaluate against documentElement in case elem is a non-element node (e.g., document) if ( selector ) { jQuery.find.matchesSelector( documentElement, selector ); } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !( events = elemData.events ) ) { events = elemData.events = Object.create( null ); } if ( !( eventHandle = elemData.handle ) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== "undefined" && jQuery.event.triggered !== e.type ? jQuery.event.dispatch.apply( elem, arguments ) : undefined; }; } // Handle multiple events separated by a space types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // There *must* be a type, no attaching namespace-only handlers if ( !type ) { continue; } // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend( { type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join( "." ) }, handleObjIn ); // Init the event handler queue if we're the first if ( !( handlers = events[ type ] ) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, origCount, tmp, events, t, handleObj, special, handlers, type, namespaces, origType, elemData = dataPriv.hasData( elem ) && dataPriv.get( elem ); if ( !elemData || !( events = elemData.events ) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( rnothtmlwhite ) || [ "" ]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[ t ] ) || []; type = origType = tmp[ 1 ]; namespaces = ( tmp[ 2 ] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[ 2 ] && new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove data and the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { dataPriv.remove( elem, "handle events" ); } }, dispatch: function( nativeEvent ) { var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( nativeEvent ), handlers = ( dataPriv.get( this, "events" ) || Object.create( null ) )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[ 0 ] = event; for ( i = 1; i < arguments.length; i++ ) { args[ i ] = arguments[ i ]; } event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( ( matched = handlerQueue[ i++ ] ) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( ( handleObj = matched.handlers[ j++ ] ) && !event.isImmediatePropagationStopped() ) { // If the event is namespaced, then each handler is only invoked if it is // specially universal or its namespaces are a superset of the event's. if ( !event.rnamespace || handleObj.namespace === false || event.rnamespace.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle || handleObj.handler ).apply( matched.elem, args ); if ( ret !== undefined ) { if ( ( event.result = ret ) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var i, handleObj, sel, matchedHandlers, matchedSelectors, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers if ( delegateCount && // Support: IE <=9 // Black-hole SVG <use> instance trees (trac-13180) cur.nodeType && // Support: Firefox <=42 // Suppress spec-violating clicks indicating a non-primary pointer button (trac-3861) // https://www.w3.org/TR/DOM-Level-3-Events/#event-type-click // Support: IE 11 only // ...but not arrow key "clicks" of radio inputs, which can have `button` -1 (gh-2343) !( event.type === "click" && event.button >= 1 ) ) { for ( ; cur !== this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && !( event.type === "click" && cur.disabled === true ) ) { matchedHandlers = []; matchedSelectors = {}; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matchedSelectors[ sel ] === undefined ) { matchedSelectors[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) > -1 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matchedSelectors[ sel ] ) { matchedHandlers.push( handleObj ); } } if ( matchedHandlers.length ) { handlerQueue.push( { elem: cur, handlers: matchedHandlers } ); } } } } // Add the remaining (directly-bound) handlers cur = this; if ( delegateCount < handlers.length ) { handlerQueue.push( { elem: cur, handlers: handlers.slice( delegateCount ) } ); } return handlerQueue; }, addProp: function( name, hook ) { Object.defineProperty( jQuery.Event.prototype, name, { enumerable: true, configurable: true, get: isFunction( hook ) ? function() { if ( this.originalEvent ) { return hook( this.originalEvent ); } } : function() { if ( this.originalEvent ) { return this.originalEvent[ name ]; } }, set: function( value ) { Object.defineProperty( this, name, { enumerable: true, configurable: true, writable: true, value: value } ); } } ); }, fix: function( originalEvent ) { return originalEvent[ jQuery.expando ] ? originalEvent : new jQuery.Event( originalEvent ); }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // Utilize native event to ensure correct state for checkable inputs setup: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Claim the first handler if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { // dataPriv.set( el, "click", ... ) leverageNative( el, "click", returnTrue ); } // Return false to allow normal processing in the caller return false; }, trigger: function( data ) { // For mutual compressibility with _default, replace `this` access with a local var. // `|| data` is dead code meant only to preserve the variable through minification. var el = this || data; // Force setup before triggering a click if ( rcheckableType.test( el.type ) && el.click && nodeName( el, "input" ) ) { leverageNative( el, "click" ); } // Return non-false to allow normal event-path propagation return true; }, // For cross-browser consistency, suppress native .click() on links // Also prevent it if we're currently inside a leveraged native-event stack _default: function( event ) { var target = event.target; return rcheckableType.test( target.type ) && target.click && nodeName( target, "input" ) && dataPriv.get( target, "click" ) || nodeName( target, "a" ); } }, beforeunload: { postDispatch: function( event ) { // Support: Firefox 20+ // Firefox doesn't alert if the returnValue field is not set. if ( event.result !== undefined && event.originalEvent ) { event.originalEvent.returnValue = event.result; } } } } }; // Ensure the presence of an event listener that handles manually-triggered // synthetic events by interrupting progress until reinvoked in response to // *native* events that it fires directly, ensuring that state changes have // already occurred before other listeners are invoked. function leverageNative( el, type, expectSync ) { // Missing expectSync indicates a trigger call, which must force setup through jQuery.event.add if ( !expectSync ) { if ( dataPriv.get( el, type ) === undefined ) { jQuery.event.add( el, type, returnTrue ); } return; } // Register the controller as a special universal handler for all event namespaces dataPriv.set( el, type, false ); jQuery.event.add( el, type, { namespace: false, handler: function( event ) { var notAsync, result, saved = dataPriv.get( this, type ); if ( ( event.isTrigger & 1 ) && this[ type ] ) { // Interrupt processing of the outer synthetic .trigger()ed event // Saved data should be false in such cases, but might be a leftover capture object // from an async native handler (gh-4350) if ( !saved.length ) { // Store arguments for use when handling the inner native event // There will always be at least one argument (an event object), so this array // will not be confused with a leftover capture object. saved = slice.call( arguments ); dataPriv.set( this, type, saved ); // Trigger the native event and capture its result // Support: IE <=9 - 11+ // focus() and blur() are asynchronous notAsync = expectSync( this, type ); this[ type ](); result = dataPriv.get( this, type ); if ( saved !== result || notAsync ) { dataPriv.set( this, type, false ); } else { result = {}; } if ( saved !== result ) { // Cancel the outer synthetic event event.stopImmediatePropagation(); event.preventDefault(); // Support: Chrome 86+ // In Chrome, if an element having a focusout handler is blurred by // clicking outside of it, it invokes the handler synchronously. If // that handler calls `.remove()` on the element, the data is cleared, // leaving `result` undefined. We need to guard against this. return result && result.value; } // If this is an inner synthetic event for an event with a bubbling surrogate // (focus or blur), assume that the surrogate already propagated from triggering the // native event and prevent that from happening again here. // This technically gets the ordering wrong w.r.t. to `.trigger()` (in which the // bubbling surrogate propagates *after* the non-bubbling base), but that seems // less bad than duplication. } else if ( ( jQuery.event.special[ type ] || {} ).delegateType ) { event.stopPropagation(); } // If this is a native event triggered above, everything is now in order // Fire an inner synthetic event with the original arguments } else if ( saved.length ) { // ...and capture the result dataPriv.set( this, type, { value: jQuery.event.trigger( // Support: IE <=9 - 11+ // Extend with the prototype to reset the above stopImmediatePropagation() jQuery.extend( saved[ 0 ], jQuery.Event.prototype ), saved.slice( 1 ), this ) } ); // Abort handling of the native event event.stopImmediatePropagation(); } } } ); } jQuery.removeEvent = function( elem, type, handle ) { // This "if" is needed for plain objects if ( elem.removeEventListener ) { elem.removeEventListener( type, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !( this instanceof jQuery.Event ) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = src.defaultPrevented || src.defaultPrevented === undefined && // Support: Android <=2.3 only src.returnValue === false ? returnTrue : returnFalse; // Create target properties // Support: Safari <=6 - 7 only // Target should not be a text node (#504, #13143) this.target = ( src.target && src.target.nodeType === 3 ) ? src.target.parentNode : src.target; this.currentTarget = src.currentTarget; this.relatedTarget = src.relatedTarget; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || Date.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // https://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { constructor: jQuery.Event, isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, isSimulated: false, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( e && !this.isSimulated ) { e.preventDefault(); } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopPropagation(); } }, stopImmediatePropagation: function() { var e = this.originalEvent; this.isImmediatePropagationStopped = returnTrue; if ( e && !this.isSimulated ) { e.stopImmediatePropagation(); } this.stopPropagation(); } }; // Includes all common event props including KeyEvent and MouseEvent specific props jQuery.each( { altKey: true, bubbles: true, cancelable: true, changedTouches: true, ctrlKey: true, detail: true, eventPhase: true, metaKey: true, pageX: true, pageY: true, shiftKey: true, view: true, "char": true, code: true, charCode: true, key: true, keyCode: true, button: true, buttons: true, clientX: true, clientY: true, offsetX: true, offsetY: true, pointerId: true, pointerType: true, screenX: true, screenY: true, targetTouches: true, toElement: true, touches: true, which: true }, jQuery.event.addProp ); jQuery.each( { focus: "focusin", blur: "focusout" }, function( type, delegateType ) { jQuery.event.special[ type ] = { // Utilize native event if possible so blur/focus sequence is correct setup: function() { // Claim the first handler // dataPriv.set( this, "focus", ... ) // dataPriv.set( this, "blur", ... ) leverageNative( this, type, expectSync ); // Return false to allow normal processing in the caller return false; }, trigger: function() { // Force setup before trigger leverageNative( this, type ); // Return non-false to allow normal event-path propagation return true; }, // Suppress native focus or blur as it's already being fired // in leverageNative. _default: function() { return true; }, delegateType: delegateType }; } ); // Create mouseenter/leave events using mouseover/out and event-time checks // so that event delegation works in jQuery. // Do the same for pointerenter/pointerleave and pointerover/pointerout // // Support: Safari 7 only // Safari sends mouseenter too often; see: // https://bugs.chromium.org/p/chromium/issues/detail?id=470258 // for the description of the bug (it existed in older Chrome versions as well). jQuery.each( { mouseenter: "mouseover", mouseleave: "mouseout", pointerenter: "pointerover", pointerleave: "pointerout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mouseenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || ( related !== target && !jQuery.contains( target, related ) ) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; } ); jQuery.fn.extend( { on: function( types, selector, data, fn ) { return on( this, types, selector, data, fn ); }, one: function( types, selector, data, fn ) { return on( this, types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each( function() { jQuery.event.remove( this, types, fn, selector ); } ); } } ); var // Support: IE <=10 - 11, Edge 12 - 13 only // In IE/Edge using regex groups here causes severe slowdowns. // See https://connect.microsoft.com/IE/feedback/details/1736512/ rnoInnerhtml = /<script|<style|<link/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; // Prefer a tbody over its parent table for containing new rows function manipulationTarget( elem, content ) { if ( nodeName( elem, "table" ) && nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return jQuery( elem ).children( "tbody" )[ 0 ] || elem; } return elem; } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { elem.type = ( elem.getAttribute( "type" ) !== null ) + "/" + elem.type; return elem; } function restoreScript( elem ) { if ( ( elem.type || "" ).slice( 0, 5 ) === "true/" ) { elem.type = elem.type.slice( 5 ); } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.get( src ); events = pdataOld.events; if ( events ) { dataPriv.remove( dest, "handle events" ); for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } } // 2. Copy user data if ( dataUser.hasData( src ) ) { udataOld = dataUser.access( src ); udataCur = jQuery.extend( {}, udataOld ); dataUser.set( dest, udataCur ); } } // Fix IE bugs, see support tests function fixInput( src, dest ) { var nodeName = dest.nodeName.toLowerCase(); // Fails to persist the checked state of a cloned checkbox or radio button. if ( nodeName === "input" && rcheckableType.test( src.type ) ) { dest.checked = src.checked; // Fails to return the selected option to the default selected state when cloning options } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } function domManip( collection, args, callback, ignored ) { // Flatten any nested arrays args = flat( args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], valueIsFunction = isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( valueIsFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( valueIsFunction ) { args[ 0 ] = value.call( this, index, self.html() ); } domManip( self, args, callback, ignored ); } ); } if ( l ) { fragment = buildFragment( args, collection[ 0 ].ownerDocument, false, collection, ignored ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } // Require either new content or an interest in ignored elements to invoke the callback if ( first || ignored ) { scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item // instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { // Support: Android <=4.0 only, PhantomJS 1 only // push.apply(_, arraylike) throws on ancient WebKit jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( collection[ i ], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !dataPriv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src && ( node.type || "" ).toLowerCase() !== "module" ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl && !node.noModule ) { jQuery._evalUrl( node.src, { nonce: node.nonce || node.getAttribute( "nonce" ) }, doc ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), node, doc ); } } } } } } return collection; } function remove( elem, selector, keepData ) { var node, nodes = selector ? jQuery.filter( selector, elem ) : elem, i = 0; for ( ; ( node = nodes[ i ] ) != null; i++ ) { if ( !keepData && node.nodeType === 1 ) { jQuery.cleanData( getAll( node ) ); } if ( node.parentNode ) { if ( keepData && isAttached( node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html; }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = isAttached( elem ); // Fix IE cloning issues if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc( elem ) ) { // We eschew Sizzle here for performance reasons: https://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); for ( i = 0, l = srcElements.length; i < l; i++ ) { fixInput( srcElements[ i ], destElements[ i ] ); } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0, l = srcElements.length; i < l; i++ ) { cloneCopyEvent( srcElements[ i ], destElements[ i ] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } // Return the cloned set return clone; }, cleanData: function( elems ) { var data, elem, type, special = jQuery.event.special, i = 0; for ( ; ( elem = elems[ i ] ) !== undefined; i++ ) { if ( acceptData( elem ) ) { if ( ( data = elem[ dataPriv.expando ] ) ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataPriv.expando ] = undefined; } if ( elem[ dataUser.expando ] ) { // Support: Chrome <=35 - 45+ // Assign undefined instead of using delete, see Data#remove elem[ dataUser.expando ] = undefined; } } } } } ); jQuery.fn.extend( { detach: function( selector ) { return remove( this, selector, true ); }, remove: function( selector ) { return remove( this, selector ); }, text: function( value ) { return access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().each( function() { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.textContent = value; } } ); }, null, value, arguments.length ); }, append: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.appendChild( elem ); } } ); }, prepend: function() { return domManip( this, arguments, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { var target = manipulationTarget( this, elem ); target.insertBefore( elem, target.firstChild ); } } ); }, before: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } } ); }, after: function() { return domManip( this, arguments, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } } ); }, empty: function() { var elem, i = 0; for ( ; ( elem = this[ i ] ) != null; i++ ) { if ( elem.nodeType === 1 ) { // Prevent memory leaks jQuery.cleanData( getAll( elem, false ) ); // Remove any remaining nodes elem.textContent = ""; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function() { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); } ); }, html: function( value ) { return access( this, function( value ) { var elem = this[ 0 ] || {}, i = 0, l = this.length; if ( value === undefined && elem.nodeType === 1 ) { return elem.innerHTML; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && !wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) { value = jQuery.htmlPrefilter( value ); try { for ( ; i < l; i++ ) { elem = this[ i ] || {}; // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch ( e ) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function() { var ignored = []; // Make the changes, replacing each non-ignored context element with the new content return domManip( this, arguments, function( elem ) { var parent = this.parentNode; if ( jQuery.inArray( this, ignored ) < 0 ) { jQuery.cleanData( getAll( this ) ); if ( parent ) { parent.replaceChild( elem, this ); } } // Force callback invocation }, ignored ); } } ); jQuery.each( { appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, ret = [], insert = jQuery( selector ), last = insert.length - 1, i = 0; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone( true ); jQuery( insert[ i ] )[ original ]( elems ); // Support: Android <=4.0 only, PhantomJS 1 only // .get() because push.apply(_, arraylike) throws on ancient WebKit push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; } ); var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" ); var getStyles = function( elem ) { // Support: IE <=11 only, Firefox <=30 (#15098, #14150) // IE throws on elements created in popups // FF meanwhile throws on frame elements through "defaultView.getComputedStyle" var view = elem.ownerDocument.defaultView; if ( !view || !view.opener ) { view = window; } return view.getComputedStyle( elem ); }; var swap = function( elem, options, callback ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.call( elem ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; var rboxStyle = new RegExp( cssExpand.join( "|" ), "i" ); ( function() { // Executing both pixelPosition & boxSizingReliable tests require only one layout // so they're executed at the same time to save the second computation. function computeStyleTests() { // This is a singleton, we need to execute it only once if ( !div ) { return; } container.style.cssText = "position:absolute;left:-11111px;width:60px;" + "margin-top:1px;padding:0;border:0"; div.style.cssText = "position:relative;display:block;box-sizing:border-box;overflow:scroll;" + "margin:auto;border:1px;padding:1px;" + "width:60%;top:1%"; documentElement.appendChild( container ).appendChild( div ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = roundPixelMeasures( divStyle.marginLeft ) === 12; // Support: Android 4.0 - 4.3 only, Safari <=9.1 - 10.1, iOS <=7.0 - 9.3 // Some styles come back with percentage values, even though they shouldn't div.style.right = "60%"; pixelBoxStylesVal = roundPixelMeasures( divStyle.right ) === 36; // Support: IE 9 - 11 only // Detect misreporting of content dimensions for box-sizing:border-box elements boxSizingReliableVal = roundPixelMeasures( divStyle.width ) === 36; // Support: IE 9 only // Detect overflow:scroll screwiness (gh-3699) // Support: Chrome <=64 // Don't get tricked when zoom affects offsetWidth (gh-4029) div.style.position = "absolute"; scrollboxSizeVal = roundPixelMeasures( div.offsetWidth / 3 ) === 12; documentElement.removeChild( container ); // Nullify the div so it wouldn't be stored in the memory and // it will also be a sign that checks already performed div = null; } function roundPixelMeasures( measure ) { return Math.round( parseFloat( measure ) ); } var pixelPositionVal, boxSizingReliableVal, scrollboxSizeVal, pixelBoxStylesVal, reliableTrDimensionsVal, reliableMarginLeftVal, container = document.createElement( "div" ), div = document.createElement( "div" ); // Finish early in limited (non-browser) environments if ( !div.style ) { return; } // Support: IE <=9 - 11 only // Style of cloned element affects source element cloned (#8908) div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; jQuery.extend( support, { boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelBoxStyles: function() { computeStyleTests(); return pixelBoxStylesVal; }, pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; }, scrollboxSize: function() { computeStyleTests(); return scrollboxSizeVal; }, // Support: IE 9 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Behavior in IE 9 is more subtle than in newer versions & it passes // some versions of this test; make sure not to make it pass there! // // Support: Firefox 70+ // Only Firefox includes border widths // in computed dimensions. (gh-4529) reliableTrDimensions: function() { var table, tr, trChild, trStyle; if ( reliableTrDimensionsVal == null ) { table = document.createElement( "table" ); tr = document.createElement( "tr" ); trChild = document.createElement( "div" ); table.style.cssText = "position:absolute;left:-11111px;border-collapse:separate"; tr.style.cssText = "border:1px solid"; // Support: Chrome 86+ // Height set through cssText does not get applied. // Computed height then comes back as 0. tr.style.height = "1px"; trChild.style.height = "9px"; // Support: Android 8 Chrome 86+ // In our bodyBackground.html iframe, // display for all div elements is set to "inline", // which causes a problem only in Android 8 Chrome 86. // Ensuring the div is display: block // gets around this issue. trChild.style.display = "block"; documentElement .appendChild( table ) .appendChild( tr ) .appendChild( trChild ); trStyle = window.getComputedStyle( tr ); reliableTrDimensionsVal = ( parseInt( trStyle.height, 10 ) + parseInt( trStyle.borderTopWidth, 10 ) + parseInt( trStyle.borderBottomWidth, 10 ) ) === tr.offsetHeight; documentElement.removeChild( table ); } return reliableTrDimensionsVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, // Support: Firefox 51+ // Retrieving style before computed somehow // fixes an issue with getting wrong values // on detached elements style = elem.style; computed = computed || getStyles( elem ); // getPropertyValue is needed for: // .css('filter') (IE 9 only, #12537) // .css('--customProperty) (#3144) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !isAttached( elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Android Browser returns percentage for some values, // but width seems to be reliably pixels. // This is against the CSSOM draft spec: // https://drafts.csswg.org/cssom/#resolved-values if ( !support.pixelBoxStyles() && rnumnonpx.test( ret ) && rboxStyle.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret !== undefined ? // Support: IE <=9 - 11 only // IE returns zIndex value as an integer. ret + "" : ret; } function addGetHookIf( conditionFn, hookFn ) { // Define the hook, we'll check on the first run if it's really needed. return { get: function() { if ( conditionFn() ) { // Hook not needed (or it's not possible to use it due // to missing dependency), remove it. delete this.get; return; } // Hook needed; redefine it so that the support test is not executed again. return ( this.get = hookFn ).apply( this, arguments ); } }; } var cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style, vendorProps = {}; // Return a vendor-prefixed property or undefined function vendorPropName( name ) { // Check for vendor prefixed names var capName = name[ 0 ].toUpperCase() + name.slice( 1 ), i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in emptyStyle ) { return name; } } } // Return a potentially-mapped jQuery.cssProps or vendor prefixed property function finalPropName( name ) { var final = jQuery.cssProps[ name ] || vendorProps[ name ]; if ( final ) { return final; } if ( name in emptyStyle ) { return name; } return vendorProps[ name ] = vendorPropName( name ) || name; } var // Swappable if display is none or starts with table // except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rcustomProp = /^--/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }; function setPositiveNumber( _elem, value, subtract ) { // Any relative (+/-) values have already been // normalized at this point var matches = rcssNum.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 2 ] - ( subtract || 0 ) ) + ( matches[ 3 ] || "px" ) : value; } function boxModelAdjustment( elem, dimension, box, isBorderBox, styles, computedVal ) { var i = dimension === "width" ? 1 : 0, extra = 0, delta = 0; // Adjustment may not be necessary if ( box === ( isBorderBox ? "border" : "content" ) ) { return 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin if ( box === "margin" ) { delta += jQuery.css( elem, box + cssExpand[ i ], true, styles ); } // If we get here with a content-box, we're seeking "padding" or "border" or "margin" if ( !isBorderBox ) { // Add padding delta += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // For "border" or "margin", add border if ( box !== "padding" ) { delta += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); // But still keep track of it otherwise } else { extra += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } // If we get here with a border-box (content + padding + border), we're seeking "content" or // "padding" or "margin" } else { // For "content", subtract padding if ( box === "content" ) { delta -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // For "content" or "padding", subtract border if ( box !== "margin" ) { delta -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } // Account for positive content-box scroll gutter when requested by providing computedVal if ( !isBorderBox && computedVal >= 0 ) { // offsetWidth/offsetHeight is a rounded sum of content, padding, scroll gutter, and border // Assuming integer scroll gutter, subtract the rest and round down delta += Math.max( 0, Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - computedVal - delta - extra - 0.5 // If offsetWidth/offsetHeight is unknown, then we can't determine content-box scroll gutter // Use an explicit zero to avoid NaN (gh-3964) ) ) || 0; } return delta; } function getWidthOrHeight( elem, dimension, extra ) { // Start with computed style var styles = getStyles( elem ), // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-4322). // Fake content-box until we know it's needed to know the true value. boxSizingNeeded = !support.boxSizingReliable() || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", valueIsBorderBox = isBorderBox, val = curCSS( elem, dimension, styles ), offsetProp = "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ); // Support: Firefox <=54 // Return a confounding non-pixel value or feign ignorance, as appropriate. if ( rnumnonpx.test( val ) ) { if ( !extra ) { return val; } val = "auto"; } // Support: IE 9 - 11 only // Use offsetWidth/offsetHeight for when box sizing is unreliable. // In those cases, the computed value can be trusted to be border-box. if ( ( !support.boxSizingReliable() && isBorderBox || // Support: IE 10 - 11+, Edge 15 - 18+ // IE/Edge misreport `getComputedStyle` of table rows with width/height // set in CSS while `offset*` properties report correct values. // Interestingly, in some cases IE 9 doesn't suffer from this issue. !support.reliableTrDimensions() && nodeName( elem, "tr" ) || // Fall back to offsetWidth/offsetHeight when value is "auto" // This happens for inline elements with no explicit setting (gh-3571) val === "auto" || // Support: Android <=4.1 - 4.3 only // Also use offsetWidth/offsetHeight for misreported inline dimensions (gh-3602) !parseFloat( val ) && jQuery.css( elem, "display", false, styles ) === "inline" ) && // Make sure the element is visible & connected elem.getClientRects().length ) { isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Where available, offsetWidth/offsetHeight approximate border box dimensions. // Where not available (e.g., SVG), assume unreliable box-sizing and interpret the // retrieved value as a content box dimension. valueIsBorderBox = offsetProp in elem; if ( valueIsBorderBox ) { val = elem[ offsetProp ]; } } // Normalize "" and auto val = parseFloat( val ) || 0; // Adjust for the element's box model return ( val + boxModelAdjustment( elem, dimension, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles, // Provide the current computed size to request scroll gutter calculation (gh-3589) val ) ) + "px"; } jQuery.extend( { // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "animationIterationCount": true, "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "gridArea": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnStart": true, "gridRow": true, "gridRowEnd": true, "gridRowStart": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: {}, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ), style = elem.style; // Make sure that we're working with the right name. We don't // want to query the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && ( ret = rcssNum.exec( value ) ) && ret[ 1 ] ) { value = adjustCSS( elem, name, ret ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number was passed in, add the unit (except for certain CSS properties) // The isCustomProp check can be removed in jQuery 4.0 when we only auto-append // "px" to a few hardcoded values. if ( type === "number" && !isCustomProp ) { value += ret && ret[ 3 ] || ( jQuery.cssNumber[ origName ] ? "" : "px" ); } // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !( "set" in hooks ) || ( value = hooks.set( elem, value, extra ) ) !== undefined ) { if ( isCustomProp ) { style.setProperty( name, value ); } else { style[ name ] = value; } } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && ( ret = hooks.get( elem, false, extra ) ) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = camelCase( name ), isCustomProp = rcustomProp.test( name ); // Make sure that we're working with the right name. We don't // want to modify the value if it is a CSS custom property // since they are user-defined. if ( !isCustomProp ) { name = finalPropName( origName ); } // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || isFinite( num ) ? num || 0 : val; } return val; } } ); jQuery.each( [ "height", "width" ], function( _i, dimension ) { jQuery.cssHooks[ dimension ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && // Support: Safari 8+ // Table columns in Safari have non-zero offsetWidth & zero // getBoundingClientRect().width unless display is changed. // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. ( !elem.getClientRects().length || !elem.getBoundingClientRect().width ) ? swap( elem, cssShow, function() { return getWidthOrHeight( elem, dimension, extra ); } ) : getWidthOrHeight( elem, dimension, extra ); } }, set: function( elem, value, extra ) { var matches, styles = getStyles( elem ), // Only read styles.position if the test has a chance to fail // to avoid forcing a reflow. scrollboxSizeBuggy = !support.scrollboxSize() && styles.position === "absolute", // To avoid forcing a reflow, only fetch boxSizing if we need it (gh-3991) boxSizingNeeded = scrollboxSizeBuggy || extra, isBorderBox = boxSizingNeeded && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", subtract = extra ? boxModelAdjustment( elem, dimension, extra, isBorderBox, styles ) : 0; // Account for unreliable border-box dimensions by comparing offset* to computed and // faking a content-box to get border and padding (gh-3699) if ( isBorderBox && scrollboxSizeBuggy ) { subtract -= Math.ceil( elem[ "offset" + dimension[ 0 ].toUpperCase() + dimension.slice( 1 ) ] - parseFloat( styles[ dimension ] ) - boxModelAdjustment( elem, dimension, "border", false, styles ) - 0.5 ); } // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ dimension ] = value; value = jQuery.css( elem, dimension ); } return setPositiveNumber( elem, value, subtract ); } }; } ); jQuery.cssHooks.marginLeft = addGetHookIf( support.reliableMarginLeft, function( elem, computed ) { if ( computed ) { return ( parseFloat( curCSS( elem, "marginLeft" ) ) || elem.getBoundingClientRect().left - swap( elem, { marginLeft: 0 }, function() { return elem.getBoundingClientRect().left; } ) ) + "px"; } } ); // These hooks are used by animate to expand properties jQuery.each( { margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split( " " ) : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( prefix !== "margin" ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } } ); jQuery.fn.extend( { css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( Array.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); } } ); function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || jQuery.easing._default; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; // Use a property on the element directly when it is not a DOM element, // or when there is no matching style property that exists. if ( tween.elem.nodeType !== 1 || tween.elem[ tween.prop ] != null && tween.elem.style[ tween.prop ] == null ) { return tween.elem[ tween.prop ]; } // Passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails. // Simple values such as "10px" are parsed to Float; // complex values such as "rotate(1rad)" are returned as-is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // Use step hook for back compat. // Use cssHook if its there. // Use .style if available and use plain properties where available. if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.nodeType === 1 && ( jQuery.cssHooks[ tween.prop ] || tween.elem.style[ finalPropName( tween.prop ) ] != null ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Support: IE <=9 only // Panic based approach to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p * Math.PI ) / 2; }, _default: "swing" }; jQuery.fx = Tween.prototype.init; // Back compat <1.8 extension point jQuery.fx.step = {}; var fxNow, inProgress, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function schedule() { if ( inProgress ) { if ( document.hidden === false && window.requestAnimationFrame ) { window.requestAnimationFrame( schedule ); } else { window.setTimeout( schedule, jQuery.fx.interval ); } jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = Date.now() ); } // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, i = 0, attrs = { height: type }; // If we include width, step value is 1 to do all cssExpand values, // otherwise step value is 2 to skip over Left and Right includeWidth = includeWidth ? 1 : 0; for ( ; i < 4; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } function createTween( value, prop, animation ) { var tween, collection = ( Animation.tweeners[ prop ] || [] ).concat( Animation.tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( ( tween = collection[ index ].call( animation, prop, value ) ) ) { // We're done with this property return tween; } } } function defaultPrefilter( elem, props, opts ) { var prop, value, toggle, hooks, oldfire, propTween, restoreDisplay, display, isBox = "width" in props || "height" in props, anim = this, orig = {}, style = elem.style, hidden = elem.nodeType && isHiddenWithinTree( elem ), dataShow = dataPriv.get( elem, "fxshow" ); // Queue-skipping animations hijack the fx hooks if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always( function() { // Ensure the complete handler is called before this completes anim.always( function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } } ); } ); } // Detect show/hide animations for ( prop in props ) { value = props[ prop ]; if ( rfxtypes.test( value ) ) { delete props[ prop ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { // Pretend to be hidden if this is a "show" and // there is still data from a stopped show/hide if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) { hidden = true; // Ignore all other no-op show/hide data } else { continue; } } orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop ); } } // Bail out if this is a no-op like .hide().hide() propTween = !jQuery.isEmptyObject( props ); if ( !propTween && jQuery.isEmptyObject( orig ) ) { return; } // Restrict "overflow" and "display" styles during box animations if ( isBox && elem.nodeType === 1 ) { // Support: IE <=9 - 11, Edge 12 - 15 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY and Edge just mirrors // the overflowX value there. opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Identify a display type, preferring old show/hide data over the CSS cascade restoreDisplay = dataShow && dataShow.display; if ( restoreDisplay == null ) { restoreDisplay = dataPriv.get( elem, "display" ); } display = jQuery.css( elem, "display" ); if ( display === "none" ) { if ( restoreDisplay ) { display = restoreDisplay; } else { // Get nonempty value(s) by temporarily forcing visibility showHide( [ elem ], true ); restoreDisplay = elem.style.display || restoreDisplay; display = jQuery.css( elem, "display" ); showHide( [ elem ] ); } } // Animate inline elements as inline-block if ( display === "inline" || display === "inline-block" && restoreDisplay != null ) { if ( jQuery.css( elem, "float" ) === "none" ) { // Restore the original display value at the end of pure show/hide animations if ( !propTween ) { anim.done( function() { style.display = restoreDisplay; } ); if ( restoreDisplay == null ) { display = style.display; restoreDisplay = display === "none" ? "" : display; } } style.display = "inline-block"; } } } if ( opts.overflow ) { style.overflow = "hidden"; anim.always( function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; } ); } // Implement show/hide animations propTween = false; for ( prop in orig ) { // General show/hide setup for this element animation if ( !propTween ) { if ( dataShow ) { if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } } else { dataShow = dataPriv.access( elem, "fxshow", { display: restoreDisplay } ); } // Store hidden/visible for toggle so `.stop().toggle()` "reverses" if ( toggle ) { dataShow.hidden = !hidden; } // Show elements before animating them if ( hidden ) { showHide( [ elem ], true ); } /* eslint-disable no-loop-func */ anim.done( function() { /* eslint-enable no-loop-func */ // The final step of a "hide" animation is actually hiding the element if ( !hidden ) { showHide( [ elem ] ); } dataPriv.remove( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } } ); } // Per-property setup propTween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = propTween.start; if ( hidden ) { propTween.end = propTween.start; propTween.start = 0; } } } } function propFilter( props, specialEasing ) { var index, name, easing, value, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( Array.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // Not quite $.extend, this won't overwrite existing keys. // Reusing 'index' because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = Animation.prefilters.length, deferred = jQuery.Deferred().always( function() { // Don't match elem in the :animated selector delete tick.elem; } ), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // Support: Android 2.3 only // Archaic crash bug won't allow us to use `1 - ( 0.5 || 0 )` (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ] ); // If there's more to do, yield if ( percent < 1 && length ) { return remaining; } // If this was an empty animation, synthesize a final progress notification if ( !length ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); } // Resolve the animation and report its conclusion deferred.resolveWith( elem, [ animation ] ); return false; }, animation = deferred.promise( { elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {}, easing: jQuery.easing._default }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // If we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length; index++ ) { animation.tweens[ index ].run( 1 ); } // Resolve when we played the last frame; otherwise, reject if ( gotoEnd ) { deferred.notifyWith( elem, [ animation, 1, 0 ] ); deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } } ), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length; index++ ) { result = Animation.prefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { if ( isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = result.stop.bind( result ); } return result; } } jQuery.map( props, createTween, animation ); if ( isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } // Attach callbacks from options animation .progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); return animation; } jQuery.Animation = jQuery.extend( Animation, { tweeners: { "*": [ function( prop, value ) { var tween = this.createTween( prop, value ); adjustCSS( tween.elem, prop, rcssNum.exec( value ), tween ); return tween; } ] }, tweener: function( props, callback ) { if ( isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.match( rnothtmlwhite ); } var prop, index = 0, length = props.length; for ( ; index < length; index++ ) { prop = props[ index ]; Animation.tweeners[ prop ] = Animation.tweeners[ prop ] || []; Animation.tweeners[ prop ].unshift( callback ); } }, prefilters: [ defaultPrefilter ], prefilter: function( callback, prepend ) { if ( prepend ) { Animation.prefilters.unshift( callback ); } else { Animation.prefilters.push( callback ); } } } ); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !isFunction( easing ) && easing }; // Go to the end state if fx are off if ( jQuery.fx.off ) { opt.duration = 0; } else { if ( typeof opt.duration !== "number" ) { if ( opt.duration in jQuery.fx.speeds ) { opt.duration = jQuery.fx.speeds[ opt.duration ]; } else { opt.duration = jQuery.fx.speeds._default; } } } // Normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.fn.extend( { fadeTo: function( speed, to, easing, callback ) { // Show any hidden elements after setting opacity to 0 return this.filter( isHiddenWithinTree ).css( "opacity", 0 ).show() // Animate to the value specified .end().animate( { opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); // Empty animations, or finishing resolves immediately if ( empty || dataPriv.get( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue ) { this.queue( type || "fx", [] ); } return this.each( function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = dataPriv.get( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && ( type == null || timers[ index ].queue === type ) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // Start the next in the queue if the last step wasn't forced. // Timers currently will call their complete callbacks, which // will dequeue but only if they were gotoEnd. if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } } ); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each( function() { var index, data = dataPriv.get( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // Enable finishing flag on private data data.finish = true; // Empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.stop ) { hooks.stop.call( this, true ); } // Look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // Look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // Turn off finishing flag delete data.finish; } ); } } ); jQuery.each( [ "toggle", "show", "hide" ], function( _i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; } ); // Generate shortcuts for custom animations jQuery.each( { slideDown: genFx( "show" ), slideUp: genFx( "hide" ), slideToggle: genFx( "toggle" ), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; } ); jQuery.timers = []; jQuery.fx.tick = function() { var timer, i = 0, timers = jQuery.timers; fxNow = Date.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Run the timer and safely remove it when done (allowing for external removal) if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { jQuery.timers.push( timer ); jQuery.fx.start(); }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( inProgress ) { return; } inProgress = true; schedule(); }; jQuery.fx.stop = function() { inProgress = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Based off of the plugin by Clint Helfers, with permission. // https://web.archive.org/web/20100324014747/http://blindsignals.com/index.php/2009/07/jquery-delay/ jQuery.fn.delay = function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = window.setTimeout( next, time ); hooks.stop = function() { window.clearTimeout( timeout ); }; } ); }; ( function() { var input = document.createElement( "input" ), select = document.createElement( "select" ), opt = select.appendChild( document.createElement( "option" ) ); input.type = "checkbox"; // Support: Android <=4.3 only // Default value for a checkbox should be "on" support.checkOn = input.value !== ""; // Support: IE <=11 only // Must access selectedIndex to make default options select support.optSelected = opt.selected; // Support: IE <=11 only // An input loses its value after becoming a radio input = document.createElement( "input" ); input.value = "t"; input.type = "radio"; support.radioValue = input.value === "t"; } )(); var boolHook, attrHandle = jQuery.expr.attrHandle; jQuery.fn.extend( { attr: function( name, value ) { return access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each( function() { jQuery.removeAttr( this, name ); } ); } } ); jQuery.extend( { attr: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set attributes on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === "undefined" ) { return jQuery.prop( elem, name, value ); } // Attribute hooks are determined by the lowercase version // Grab necessary hook if one is defined if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { hooks = jQuery.attrHooks[ name.toLowerCase() ] || ( jQuery.expr.match.bool.test( name ) ? boolHook : undefined ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); return; } if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } elem.setAttribute( name, value + "" ); return value; } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } ret = jQuery.find.attr( elem, name ); // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; }, attrHooks: { type: { set: function( elem, value ) { if ( !support.radioValue && value === "radio" && nodeName( elem, "input" ) ) { var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, removeAttr: function( elem, value ) { var name, i = 0, // Attribute names can contain non-HTML whitespace characters // https://html.spec.whatwg.org/multipage/syntax.html#attributes-2 attrNames = value && value.match( rnothtmlwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( ( name = attrNames[ i++ ] ) ) { elem.removeAttribute( name ); } } } } ); // Hooks for boolean attributes boolHook = { set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else { elem.setAttribute( name, name ); } return name; } }; jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( _i, name ) { var getter = attrHandle[ name ] || jQuery.find.attr; attrHandle[ name ] = function( elem, name, isXML ) { var ret, handle, lowercaseName = name.toLowerCase(); if ( !isXML ) { // Avoid an infinite loop by temporarily removing this function from the getter handle = attrHandle[ lowercaseName ]; attrHandle[ lowercaseName ] = ret; ret = getter( elem, name, isXML ) != null ? lowercaseName : null; attrHandle[ lowercaseName ] = handle; } return ret; }; } ); var rfocusable = /^(?:input|select|textarea|button)$/i, rclickable = /^(?:a|area)$/i; jQuery.fn.extend( { prop: function( name, value ) { return access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { return this.each( function() { delete this[ jQuery.propFix[ name ] || name ]; } ); } } ); jQuery.extend( { prop: function( elem, name, value ) { var ret, hooks, nType = elem.nodeType; // Don't get/set properties on text, comment and attribute nodes if ( nType === 3 || nType === 8 || nType === 2 ) { return; } if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && ( ret = hooks.set( elem, value, name ) ) !== undefined ) { return ret; } return ( elem[ name ] = value ); } if ( hooks && "get" in hooks && ( ret = hooks.get( elem, name ) ) !== null ) { return ret; } return elem[ name ]; }, propHooks: { tabIndex: { get: function( elem ) { // Support: IE <=9 - 11 only // elem.tabIndex doesn't always return the // correct value when it hasn't been explicitly set // https://web.archive.org/web/20141116233347/http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ // Use proper attribute retrieval(#12072) var tabindex = jQuery.find.attr( elem, "tabindex" ); if ( tabindex ) { return parseInt( tabindex, 10 ); } if ( rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ) { return 0; } return -1; } } }, propFix: { "for": "htmlFor", "class": "className" } } ); // Support: IE <=11 only // Accessing the selectedIndex property // forces the browser to respect setting selected // on the option // The getter ensures a default option is selected // when in an optgroup // eslint rule "no-unused-expressions" is disabled for this code // since it considers such accessions noop if ( !support.optSelected ) { jQuery.propHooks.selected = { get: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent && parent.parentNode ) { parent.parentNode.selectedIndex; } return null; }, set: function( elem ) { /* eslint no-unused-expressions: "off" */ var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } } }; } jQuery.each( [ "tabIndex", "readOnly", "maxLength", "cellSpacing", "cellPadding", "rowSpan", "colSpan", "useMap", "frameBorder", "contentEditable" ], function() { jQuery.propFix[ this.toLowerCase() ] = this; } ); // Strip and collapse whitespace according to HTML spec // https://infra.spec.whatwg.org/#strip-and-collapse-ascii-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } function classesToArray( value ) { if ( Array.isArray( value ) ) { return value; } if ( typeof value === "string" ) { return value.match( rnothtmlwhite ) || []; } return []; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, removeClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } classes = classesToArray( value ); if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); if ( cur ) { j = 0; while ( ( clazz = classes[ j++ ] ) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) > -1 ) { cur = cur.replace( " " + clazz + " ", " " ); } } // Only assign if different to avoid unneeded rendering. finalValue = stripAndCollapse( cur ); if ( curValue !== finalValue ) { elem.setAttribute( "class", finalValue ); } } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isValidValue = type === "string" || Array.isArray( value ); if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( isFunction( value ) ) { return this.each( function( i ) { jQuery( this ).toggleClass( value.call( this, i, getClass( this ), stateVal ), stateVal ); } ); } return this.each( function() { var className, i, self, classNames; if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { // Check each className given, space separated list if ( self.hasClass( className ) ) { self.removeClass( className ); } else { self.addClass( className ); } } // Toggle whole class name } else if ( value === undefined || type === "boolean" ) { className = getClass( this ); if ( className ) { // Store className if set dataPriv.set( this, "__className__", className ); } // If the element has a class name or if we're passed `false`, // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. if ( this.setAttribute ) { this.setAttribute( "class", className || value === false ? "" : dataPriv.get( this, "__className__" ) || "" ); } } } ); }, hasClass: function( selector ) { var className, elem, i = 0; className = " " + selector + " "; while ( ( elem = this[ i++ ] ) ) { if ( elem.nodeType === 1 && ( " " + stripAndCollapse( getClass( elem ) ) + " " ).indexOf( className ) > -1 ) { return true; } } return false; } } ); var rreturn = /\r/g; jQuery.fn.extend( { val: function( value ) { var hooks, ret, valueIsFunction, elem = this[ 0 ]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && ( ret = hooks.get( elem, "value" ) ) !== undefined ) { return ret; } ret = elem.value; // Handle most common string cases if ( typeof ret === "string" ) { return ret.replace( rreturn, "" ); } // Handle cases where value is null/undef or number return ret == null ? "" : ret; } return; } valueIsFunction = isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( valueIsFunction ) { val = value.call( this, i, jQuery( this ).val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( Array.isArray( val ) ) { val = jQuery.map( val, function( value ) { return value == null ? "" : value + ""; } ); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } } ); } } ); jQuery.extend( { valHooks: { option: { get: function( elem ) { var val = jQuery.find.attr( elem, "value" ); return val != null ? val : // Support: IE <=10 - 11 only // option.text throws exceptions (#14686, #14858) // Strip and collapse whitespace // https://html.spec.whatwg.org/#strip-and-collapse-whitespace stripAndCollapse( jQuery.text( elem ) ); } }, select: { get: function( elem ) { var value, option, i, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one", values = one ? null : [], max = one ? index + 1 : options.length; if ( index < 0 ) { i = max; } else { i = one ? index : 0; } // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // Support: IE <=9 only // IE8-9 doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup !option.disabled && ( !option.parentNode.disabled || !nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var optionSet, option, options = elem.options, values = jQuery.makeArray( value ), i = options.length; while ( i-- ) { option = options[ i ]; /* eslint-disable no-cond-assign */ if ( option.selected = jQuery.inArray( jQuery.valHooks.option.get( option ), values ) > -1 ) { optionSet = true; } /* eslint-enable no-cond-assign */ } // Force browsers to behave consistently when non-matching value is set if ( !optionSet ) { elem.selectedIndex = -1; } return values; } } } } ); // Radios and checkboxes getter/setter jQuery.each( [ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { set: function( elem, value ) { if ( Array.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery( elem ).val(), value ) > -1 ); } } }; if ( !support.checkOn ) { jQuery.valHooks[ this ].get = function( elem ) { return elem.getAttribute( "value" ) === null ? "on" : elem.value; }; } } ); // Return jQuery for attributes-only inclusion support.focusin = "onfocusin" in window; var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, stopPropagationCallback = function( e ) { e.stopPropagation(); }; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, lastElement, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = lastElement = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf( "." ) > -1 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split( "." ); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf( ":" ) < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true) event.isTrigger = onlyHandlers ? 2 : 3; event.namespace = namespaces.join( "." ); event.rnamespace = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === ( elem.ownerDocument || document ) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) { lastElement = cur; event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || Object.create( null ) )[ event.type ] && dataPriv.get( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && handle.apply && acceptData( cur ) ) { event.result = handle.apply( cur, data ); if ( event.result === false ) { event.preventDefault(); } } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( ( !special._default || special._default.apply( eventPath.pop(), data ) === false ) && acceptData( elem ) ) { // Call a native DOM method on the target with the same name as the event. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && isFunction( elem[ type ] ) && !isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; if ( event.isPropagationStopped() ) { lastElement.addEventListener( type, stopPropagationCallback ); } elem[ type ](); if ( event.isPropagationStopped() ) { lastElement.removeEventListener( type, stopPropagationCallback ); } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, // Piggyback on a donor event to simulate a different one // Used only for `focus(in | out)` events simulate: function( type, elem, event ) { var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true } ); jQuery.event.trigger( e, null, elem ); } } ); jQuery.fn.extend( { trigger: function( type, data ) { return this.each( function() { jQuery.event.trigger( type, data, this ); } ); }, triggerHandler: function( type, data ) { var elem = this[ 0 ]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } } ); // Support: Firefox <=44 // Firefox doesn't have focus(in | out) events // Related ticket - https://bugzilla.mozilla.org/show_bug.cgi?id=687787 // // Support: Chrome <=48 - 49, Safari <=9.0 - 9.1 // focus(in | out) events fire after focus & blur events, // which is spec violation - http://www.w3.org/TR/DOM-Level-3-Events/#events-focusevent-event-order // Related ticket - https://bugs.chromium.org/p/chromium/issues/detail?id=449857 if ( !support.focusin ) { jQuery.each( { focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler on the document while someone wants focusin/focusout var handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ) ); }; jQuery.event.special[ fix ] = { setup: function() { // Handle: regular nodes (via `this.ownerDocument`), window // (via `this.document`) & document (via `this`). var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ); if ( !attaches ) { doc.addEventListener( orig, handler, true ); } dataPriv.access( doc, fix, ( attaches || 0 ) + 1 ); }, teardown: function() { var doc = this.ownerDocument || this.document || this, attaches = dataPriv.access( doc, fix ) - 1; if ( !attaches ) { doc.removeEventListener( orig, handler, true ); dataPriv.remove( doc, fix ); } else { dataPriv.access( doc, fix, attaches ); } } }; } ); } var location = window.location; var nonce = { guid: Date.now() }; var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml, parserErrorElem; if ( !data || typeof data !== "string" ) { return null; } // Support: IE 9 - 11 only // IE throws on parseFromString with invalid input. try { xml = ( new window.DOMParser() ).parseFromString( data, "text/xml" ); } catch ( e ) {} parserErrorElem = xml && xml.getElementsByTagName( "parsererror" )[ 0 ]; if ( !xml || parserErrorElem ) { jQuery.error( "Invalid XML: " + ( parserErrorElem ? jQuery.map( parserErrorElem.childNodes, function( el ) { return el.textContent; } ).join( "\n" ) : data ) ); } return xml; }; var rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; function buildParams( prefix, obj, traditional, add ) { var name; if ( Array.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" && v != null ? i : "" ) + "]", v, traditional, add ); } } ); } else if ( !traditional && toType( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } // Serialize an array of form elements or a set of // key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, valueOrFunction ) { // If value is a function, invoke it and use its return value var value = isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; if ( a == null ) { return ""; } // If an array was passed in, assume that it is an array of form elements. if ( Array.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); } ); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ); }; jQuery.fn.extend( { serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map( function() { // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; } ).filter( function() { var type = this.type; // Use .is( ":disabled" ) so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !rcheckableType.test( type ) ); } ).map( function( _i, elem ) { var val = jQuery( this ).val(); if ( val == null ) { return null; } if ( Array.isArray( val ) ) { return jQuery.map( val, function( val ) { return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ); } return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; } ).get(); } } ); var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg, // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat( "*" ), // Anchor tag for parsing the document origin originAnchor = document.createElement( "a" ); originAnchor.href = location.href; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === "+" ) { dataType = dataType.slice( 1 ) || "*"; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( "Content-Type" ); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There's only work to do if current dataType is non-auto if ( current === "*" ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( " " ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } } } return { state: "success", data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: "GET", isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, 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" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": JSON.parse, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( "once memory" ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { responseHeaders[ match[ 1 ].toLowerCase() + " " ] = ( responseHeaders[ match[ 1 ].toLowerCase() + " " ] || [] ) .concat( match[ 2 ] ); } } match = responseHeaders[ key.toLowerCase() + " " ]; } return match == null ? null : match.join( ", " ); }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + "" ) .replace( rprotocol, location.protocol + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || "*" ).toLowerCase().match( rnothtmlwhite ) || [ "" ]; // A cross-domain request is in order when the origin doesn't match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( "a" ); // Support: IE <=8 - 11, Edge 12 - 15 // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 - 11 only // Anchor's host property isn't correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + "//" + originAnchor.host !== urlAnchor.protocol + "//" + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don't fire events if jQuery.event is undefined in an AMD-usage scenario (#15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( "ajaxStart" ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, "" ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available and should be processed, append data to url if ( s.data && ( s.processData || typeof s.data === "string" ) ) { cacheURL += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data; // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, "$1" ); uncached = ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ( nonce.guid++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change '%20' to '+' if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || "" ).indexOf( "application/x-www-form-urlencoded" ) === 0 ) { s.data = s.data.replace( r20, "+" ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( "timeout" ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( -1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Use a noop converter for missing script but not if jsonp if ( !isSuccess && jQuery.inArray( "script", s.dataTypes ) > -1 && jQuery.inArray( "json", s.dataTypes ) < 0 ) { s.converters[ "text script" ] = function() {}; } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( "Last-Modified" ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( "etag" ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === "HEAD" ) { statusText = "nocontent"; // if not modified } else if ( status === 304 ) { statusText = "notmodified"; // If we have data, let's convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger( "ajaxStop" ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); } } ); jQuery.each( [ "get", "post" ], function( _i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted if ( isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery.ajaxPrefilter( function( s ) { var i; for ( i in s.headers ) { if ( i.toLowerCase() === "content-type" ) { s.contentType = s.headers[ i ] || ""; } } } ); jQuery._evalUrl = function( url, options, doc ) { return jQuery.ajax( { url: url, // Make this explicit, since user can override this through ajaxSetup (#11264) type: "GET", dataType: "script", cache: true, async: false, global: false, // Only evaluate the response if it is successful (gh-4126) // dataFilter is not invoked for failure responses, so using it instead // of the default converter is kludgy but it works. converters: { "text script": function() {} }, dataFilter: function( response ) { jQuery.globalEval( response, options, doc ); } } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( isFunction( html ) ) { html = html.call( this[ 0 ] ); } // The elements to wrap the target around wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true ); if ( this[ 0 ].parentNode ) { wrap.insertBefore( this[ 0 ] ); } wrap.map( function() { var elem = this; while ( elem.firstElementChild ) { elem = elem.firstElementChild; } return elem; } ).append( this ); } return this; }, wrapInner: function( html ) { if ( isFunction( html ) ) { return this.each( function( i ) { jQuery( this ).wrapInner( html.call( this, i ) ); } ); } return this.each( function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } } ); }, wrap: function( html ) { var htmlIsFunction = isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( htmlIsFunction ? html.call( this, i ) : html ); } ); }, unwrap: function( selector ) { this.parent( selector ).not( "body" ).each( function() { jQuery( this ).replaceWith( this.childNodes ); } ); return this; } } ); jQuery.expr.pseudos.hidden = function( elem ) { return !jQuery.expr.pseudos.visible( elem ); }; jQuery.expr.pseudos.visible = function( elem ) { return !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length ); }; jQuery.ajaxSettings.xhr = function() { try { return new window.XMLHttpRequest(); } catch ( e ) {} }; var xhrSuccessStatus = { // File protocol always yields status code 0, assume 200 0: 200, // Support: IE <=9 only // #1450: sometimes IE returns 1223 when it should be 204 1223: 204 }, xhrSupported = jQuery.ajaxSettings.xhr(); support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); support.ajax = xhrSupported = !!xhrSupported; jQuery.ajaxTransport( function( options ) { var callback, errorCallback; // Cross domain only allowed if supported through XMLHttpRequest if ( support.cors || xhrSupported && !options.crossDomain ) { return { send: function( headers, complete ) { var i, xhr = options.xhr(); xhr.open( options.type, options.url, options.async, options.username, options.password ); // Apply custom fields if provided if ( options.xhrFields ) { for ( i in options.xhrFields ) { xhr[ i ] = options.xhrFields[ i ]; } } // Override mime type if needed if ( options.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( options.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !options.crossDomain && !headers[ "X-Requested-With" ] ) { headers[ "X-Requested-With" ] = "XMLHttpRequest"; } // Set headers for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } // Callback callback = function( type ) { return function() { if ( callback ) { callback = errorCallback = xhr.onload = xhr.onerror = xhr.onabort = xhr.ontimeout = xhr.onreadystatechange = null; if ( type === "abort" ) { xhr.abort(); } else if ( type === "error" ) { // Support: IE <=9 only // On a manual native abort, IE9 throws // errors on any property access that is not readyState if ( typeof xhr.status !== "number" ) { complete( 0, "error" ); } else { complete( // File: protocol always yields status 0; see #8605, #14207 xhr.status, xhr.statusText ); } } else { complete( xhrSuccessStatus[ xhr.status ] || xhr.status, xhr.statusText, // Support: IE <=9 only // IE9 has no XHR2 but throws on binary (trac-11426) // For XHR2 non-text, let the caller handle it (gh-2498) ( xhr.responseType || "text" ) !== "text" || typeof xhr.responseText !== "string" ? { binary: xhr.response } : { text: xhr.responseText }, xhr.getAllResponseHeaders() ); } } }; }; // Listen to events xhr.onload = callback(); errorCallback = xhr.onerror = xhr.ontimeout = callback( "error" ); // Support: IE 9 only // Use onreadystatechange to replace onabort // to handle uncaught aborts if ( xhr.onabort !== undefined ) { xhr.onabort = errorCallback; } else { xhr.onreadystatechange = function() { // Check readyState before timeout as it changes if ( xhr.readyState === 4 ) { // Allow onerror to be called first, // but that will not handle a native abort // Also, save errorCallback to a variable // as xhr.onerror cannot be accessed window.setTimeout( function() { if ( callback ) { errorCallback(); } } ); } }; } // Create the abort callback callback = callback( "abort" ); try { // Do send the request (this may raise an exception) xhr.send( options.hasContent && options.data || null ); } catch ( e ) { // #14683: Only rethrow if this hasn't been notified as an error yet if ( callback ) { throw e; } } }, abort: function() { if ( callback ) { callback(); } } }; } } ); // Prevent auto-execution of scripts when no explicit dataType was provided (See gh-2432) jQuery.ajaxPrefilter( function( s ) { if ( s.crossDomain ) { s.contents.script = false; } } ); // Install script dataType jQuery.ajaxSetup( { accepts: { script: "text/javascript, application/javascript, " + "application/ecmascript, application/x-ecmascript" }, contents: { script: /\b(?:java|ecma)script\b/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } } ); // Handle cache's special case and crossDomain jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; } } ); // Bind script tag hack transport jQuery.ajaxTransport( "script", function( s ) { // This transport only deals with cross domain or forced-by-attrs requests if ( s.crossDomain || s.scriptAttrs ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ) .attr( s.scriptAttrs || {} ) .prop( { charset: s.scriptCharset, src: s.url } ) .on( "load error", callback = function( evt ) { script.remove(); callback = null; if ( evt ) { complete( evt.type === "error" ? 404 : 200, evt.type ); } } ); // Use native DOM manipulation to avoid our domManip AJAX trickery document.head.appendChild( script[ 0 ] ); }, abort: function() { if ( callback ) { callback(); } } }; } } ); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup( { jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce.guid++ ) ); this[ callback ] = true; return callback; } } ); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && ( s.contentType || "" ) .indexOf( "application/x-www-form-urlencoded" ) === 0 && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters[ "script json" ] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // Force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always( function() { // If previous value didn't exist - remove it if ( overwritten === undefined ) { jQuery( window ).removeProp( callbackName ); // Otherwise restore preexisting value } else { window[ callbackName ] = overwritten; } // Save back as free if ( s[ callbackName ] ) { // Make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // Save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; } ); // Delegate to script return "script"; } } ); // Support: Safari 8 only // In Safari 8 documents created via document.implementation.createHTMLDocument // collapse sibling forms: the second one becomes a child of the first one. // Because of that, this security measure has to be disabled in Safari 8. // https://bugs.webkit.org/show_bug.cgi?id=137337 support.createHTMLDocument = ( function() { var body = document.implementation.createHTMLDocument( "" ).body; body.innerHTML = "<form></form><form></form>"; return body.childNodes.length === 2; } )(); // Argument "data" should be string of html // context (optional): If specified, the fragment will be created in this context, // defaults to document // keepScripts (optional): If true, will include scripts passed in the html string jQuery.parseHTML = function( data, context, keepScripts ) { if ( typeof data !== "string" ) { return []; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } var base, parsed, scripts; if ( !context ) { // Stop scripts or inline event handlers from being executed immediately // by using document.implementation if ( support.createHTMLDocument ) { context = document.implementation.createHTMLDocument( "" ); // Set the base href for the created document // so any parsed elements with URLs // are based on the document's URL (gh-2965) base = context.createElement( "base" ); base.href = document.location.href; context.head.appendChild( base ); } else { context = document; } } parsed = rsingleTag.exec( data ); scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[ 1 ] ) ]; } parsed = buildFragment( [ data ], context, scripts ); if ( scripts && scripts.length ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }; /** * Load a url into a page */ jQuery.fn.load = function( url, params, callback ) { var selector, type, response, self = this, off = url.indexOf( " " ); if ( off > -1 ) { selector = stripAndCollapse( url.slice( off ) ); url = url.slice( 0, off ); } // If it's a function if ( isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax( { url: url, // If "type" variable is undefined, then "GET" method will be used. // Make value of this field explicit since // user can override it through ajaxSetup method type: type || "GET", dataType: "html", data: params } ).done( function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery( "<div>" ).append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); // If the request succeeds, this function gets "data", "status", "jqXHR" // but they are ignored because response was set above. // If it fails, this function gets "jqXHR", "status", "error" } ).always( callback && function( jqXHR, status ) { self.each( function() { callback.apply( this, response || [ jqXHR.responseText, status, jqXHR ] ); } ); } ); } return this; }; jQuery.expr.pseudos.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; jQuery.offset = { setOffset: function( elem, options, i ) { var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition, position = jQuery.css( elem, "position" ), curElem = jQuery( elem ), props = {}; // Set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } curOffset = curElem.offset(); curCSSTop = jQuery.css( elem, "top" ); curCSSLeft = jQuery.css( elem, "left" ); calculatePosition = ( position === "absolute" || position === "fixed" ) && ( curCSSTop + curCSSLeft ).indexOf( "auto" ) > -1; // Need to be able to calculate position if either // top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( isFunction( options ) ) { // Use jQuery.extend here to allow modification of coordinates argument (gh-1848) options = options.call( elem, i, jQuery.extend( {}, curOffset ) ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend( { // offset() relates an element's border box to the document origin offset: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var rect, win, elem = this[ 0 ]; if ( !elem ) { return; } // Return zeros for disconnected and hidden (display: none) elements (gh-2310) // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } // Get document-relative position by adding viewport scroll to viewport-relative gBCR rect = elem.getBoundingClientRect(); win = elem.ownerDocument.defaultView; return { top: rect.top + win.pageYOffset, left: rect.left + win.pageXOffset }; }, // position() relates an element's margin box to its offset parent's padding box // This corresponds to the behavior of CSS absolute positioning position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, doc, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // position:fixed elements are offset from the viewport, which itself always has zero offset if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume position:fixed implies availability of getBoundingClientRect offset = elem.getBoundingClientRect(); } else { offset = this.offset(); // Account for the *real* offset parent, which can be the document or its root element // when a statically positioned element is identified doc = elem.ownerDocument; offsetParent = elem.offsetParent || doc.documentElement; while ( offsetParent && ( offsetParent === doc.body || offsetParent === doc.documentElement ) && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.parentNode; } if ( offsetParent && offsetParent !== elem && offsetParent.nodeType === 1 ) { // Incorporate borders into its offset, since they are outside its content origin parentOffset = jQuery( offsetParent ).offset(); parentOffset.top += jQuery.css( offsetParent, "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent, "borderLeftWidth", true ); } } // Subtract parent offsets and element margins return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true ) }; }, // This method will return documentElement in the following cases: // 1) For the element inside the iframe without offsetParent, this method will return // documentElement of the parent window // 2) For the hidden or detached element // 3) For body or html element, i.e. in case of the html node - it will return itself // // but those exceptions were never presented as a real life use-cases // and might be considered as more preferable results. // // This logic, however, is not guaranteed and can change at any point in the future offsetParent: function() { return this.map( function() { var offsetParent = this.offsetParent; while ( offsetParent && jQuery.css( offsetParent, "position" ) === "static" ) { offsetParent = offsetParent.offsetParent; } return offsetParent || documentElement; } ); } } ); // Create scrollLeft and scrollTop methods jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) { var top = "pageYOffset" === prop; jQuery.fn[ method ] = function( val ) { return access( this, function( elem, method, val ) { // Coalesce documents and windows var win; if ( isWindow( elem ) ) { win = elem; } else if ( elem.nodeType === 9 ) { win = elem.defaultView; } if ( val === undefined ) { return win ? win[ prop ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : win.pageXOffset, top ? val : win.pageYOffset ); } else { elem[ method ] = val; } }, method, val, arguments.length ); }; } ); // Support: Safari <=7 - 9.1, Chrome <=37 - 49 // Add the top/left cssHooks using jQuery.fn.position // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // Blink bug: https://bugs.chromium.org/p/chromium/issues/detail?id=589347 // getComputedStyle returns percent when specified for top/left/bottom/right; // rather than make the css module depend on the offset module, just check for it here jQuery.each( [ "top", "left" ], function( _i, prop ) { jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition, function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // If curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } ); } ); // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // Margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return access( this, function( elem, type, value ) { var doc; if ( isWindow( elem ) ) { // $( window ).outerWidth/Height return w/h including scrollbars (gh-1729) return funcName.indexOf( "outer" ) === 0 ? elem[ "inner" + name ] : elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], // whichever is greatest return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable ); }; } ); } ); jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( _i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.fn.extend( { bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); jQuery.each( ( "blur focus focusin focusout resize scroll click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup contextmenu" ).split( " " ), function( _i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; } ); // Support: Android <=4.0 only // Make sure we trim BOM and NBSP var rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; // Bind a function to a context, optionally partially applying any // arguments. // jQuery.proxy is deprecated to promote standards (specifically Function#bind) // However, it is not slated for removal any time soon jQuery.proxy = function( fn, context ) { var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !isFunction( fn ) ) { return undefined; } // Simulated bind args = slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }; jQuery.holdReady = function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }; jQuery.isArray = Array.isArray; jQuery.parseJSON = JSON.parse; jQuery.nodeName = nodeName; jQuery.isFunction = isFunction; jQuery.isWindow = isWindow; jQuery.camelCase = camelCase; jQuery.type = toType; jQuery.now = Date.now; jQuery.isNumeric = function( obj ) { // As of jQuery 3.0, isNumeric is limited to // strings and numbers (primitives or objects) // that can be coerced to finite numbers (gh-2662) var type = jQuery.type( obj ); return ( type === "number" || type === "string" ) && // parseFloat NaNs numeric-cast false positives ("") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN !isNaN( obj - parseFloat( obj ) ); }; jQuery.trim = function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }; // Register as a named AMD module, since jQuery can be concatenated with other // files that may use define, but not via a proper concatenation script that // understands anonymous AMD modules. A named AMD is safest and most robust // way to register. Lowercase jquery is used because AMD module names are // derived from file names, and jQuery is normally delivered in a lowercase // file name. Do this after creating the global so that if an AMD module wants // to call noConflict to hide this version of jQuery, it will work. // Note that for maximum portability, libraries that are not jQuery should // declare themselves as anonymous modules, and avoid setting a global if an // AMD loader is present. jQuery is a special case. For more information, see // https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon if ( typeof define === "function" && define.amd ) { define( "jquery", [], function() { return jQuery; } ); } var // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$; jQuery.noConflict = function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }; // Expose jQuery and $ identifiers, even in AMD // (#7102#comment:10, https://github.com/jquery/jquery/pull/557) // and CommonJS for browser emulators (#13566) if ( typeof noGlobal === "undefined" ) { window.jQuery = window.$ = jQuery; } return jQuery; } ); /* jquery.nicescroll 3.6.8 InuYaksa*2015 MIT http://nicescroll.areaaperta.com */(function(f){"function"===typeof define&&define.amd?define(["jquery"],f):"object"===typeof exports?module.exports=f(require("jquery")):f(jQuery)})(function(f){var B=!1,F=!1,O=0,P=2E3,A=0,J=["webkit","ms","moz","o"],v=window.requestAnimationFrame||!1,w=window.cancelAnimationFrame||!1;if(!v)for(var Q in J){var G=J[Q];if(v=window[G+"RequestAnimationFrame"]){w=window[G+"CancelAnimationFrame"]||window[G+"CancelRequestAnimationFrame"];break}}var x=window.MutationObserver||window.WebKitMutationObserver|| !1,K={zindex:"auto",cursoropacitymin:0,cursoropacitymax:1,cursorcolor:"#424242",cursorwidth:"6px",cursorborder:"1px solid #fff",cursorborderradius:"5px",scrollspeed:60,mousescrollstep:24,touchbehavior:!1,hwacceleration:!0,usetransition:!0,boxzoom:!1,dblclickzoom:!0,gesturezoom:!0,grabcursorenabled:!0,autohidemode:!0,background:"",iframeautoresize:!0,cursorminheight:32,preservenativescrolling:!0,railoffset:!1,railhoffset:!1,bouncescroll:!0,spacebarenabled:!0,railpadding:{top:0,right:0,left:0,bottom:0}, disableoutline:!0,horizrailenabled:!0,railalign:"right",railvalign:"bottom",enabletranslate3d:!0,enablemousewheel:!0,enablekeyboard:!0,smoothscroll:!0,sensitiverail:!0,enablemouselockapi:!0,cursorfixedheight:!1,directionlockdeadzone:6,hidecursordelay:400,nativeparentscrolling:!0,enablescrollonselection:!0,overflowx:!0,overflowy:!0,cursordragspeed:.3,rtlmode:"auto",cursordragontouch:!1,oneaxismousemode:"auto",scriptpath:function(){var f=document.getElementsByTagName("script"),f=f.length?f[f.length- 1].src.split("?")[0]:"";return 0<f.split("/").length?f.split("/").slice(0,-1).join("/")+"/":""}(),preventmultitouchscrolling:!0,disablemutationobserver:!1},H=!1,R=function(){if(H)return H;var f=document.createElement("DIV"),c=f.style,k=navigator.userAgent,l=navigator.platform,d={haspointerlock:"pointerLockElement"in document||"webkitPointerLockElement"in document||"mozPointerLockElement"in document};d.isopera="opera"in window;d.isopera12=d.isopera&&"getUserMedia"in navigator;d.isoperamini="[object OperaMini]"=== Object.prototype.toString.call(window.operamini);d.isie="all"in document&&"attachEvent"in f&&!d.isopera;d.isieold=d.isie&&!("msInterpolationMode"in c);d.isie7=d.isie&&!d.isieold&&(!("documentMode"in document)||7==document.documentMode);d.isie8=d.isie&&"documentMode"in document&&8==document.documentMode;d.isie9=d.isie&&"performance"in window&&9==document.documentMode;d.isie10=d.isie&&"performance"in window&&10==document.documentMode;d.isie11="msRequestFullscreen"in f&&11<=document.documentMode;d.isieedge12= navigator.userAgent.match(/Edge\/12\./);d.isieedge="msOverflowStyle"in f;d.ismodernie=d.isie11||d.isieedge;d.isie9mobile=/iemobile.9/i.test(k);d.isie9mobile&&(d.isie9=!1);d.isie7mobile=!d.isie9mobile&&d.isie7&&/iemobile/i.test(k);d.ismozilla="MozAppearance"in c;d.iswebkit="WebkitAppearance"in c;d.ischrome="chrome"in window;d.ischrome38=d.ischrome&&"touchAction"in c;d.ischrome22=!d.ischrome38&&d.ischrome&&d.haspointerlock;d.ischrome26=!d.ischrome38&&d.ischrome&&"transition"in c;d.cantouch="ontouchstart"in document.documentElement||"ontouchstart"in window;d.hasw3ctouch=(window.PointerEvent||!1)&&(0<navigator.MaxTouchPoints||0<navigator.msMaxTouchPoints);d.hasmstouch=!d.hasw3ctouch&&(window.MSPointerEvent||!1);d.ismac=/^mac$/i.test(l);d.isios=d.cantouch&&/iphone|ipad|ipod/i.test(l);d.isios4=d.isios&&!("seal"in Object);d.isios7=d.isios&&"webkitHidden"in document;d.isios8=d.isios&&"hidden"in document;d.isandroid=/android/i.test(k);d.haseventlistener="addEventListener"in f;d.trstyle=!1;d.hastransform=!1; d.hastranslate3d=!1;d.transitionstyle=!1;d.hastransition=!1;d.transitionend=!1;l=["transform","msTransform","webkitTransform","MozTransform","OTransform"];for(k=0;k<l.length;k++)if(void 0!==c[l[k]]){d.trstyle=l[k];break}d.hastransform=!!d.trstyle;d.hastransform&&(c[d.trstyle]="translate3d(1px,2px,3px)",d.hastranslate3d=/translate3d/.test(c[d.trstyle]));d.transitionstyle=!1;d.prefixstyle="";d.transitionend=!1;for(var l="transition webkitTransition msTransition MozTransition OTransition OTransition KhtmlTransition".split(" "), q=" -webkit- -ms- -moz- -o- -o -khtml-".split(" "),t="transitionend webkitTransitionEnd msTransitionEnd transitionend otransitionend oTransitionEnd KhtmlTransitionEnd".split(" "),k=0;k<l.length;k++)if(l[k]in c){d.transitionstyle=l[k];d.prefixstyle=q[k];d.transitionend=t[k];break}d.ischrome26&&(d.prefixstyle=q[1]);d.hastransition=d.transitionstyle;a:{k=["grab","-webkit-grab","-moz-grab"];if(d.ischrome&&!d.ischrome38||d.isie)k=[];for(l=0;l<k.length;l++)if(q=k[l],c.cursor=q,c.cursor==q){c=q;break a}c= "url(//patriciaportfolio.googlecode.com/files/openhand.cur),n-resize"}d.cursorgrabvalue=c;d.hasmousecapture="setCapture"in f;d.hasMutationObserver=!1!==x;return H=d},S=function(h,c){function k(){var b=a.doc.css(e.trstyle);return b&&"matrix"==b.substr(0,6)?b.replace(/^.*\((.*)\)$/g,"$1").replace(/px/g,"").split(/, +/):!1}function l(){var b=a.win;if("zIndex"in b)return b.zIndex();for(;0<b.length&&9!=b[0].nodeType;){var g=b.css("zIndex");if(!isNaN(g)&&0!=g)return parseInt(g);b=b.parent()}return!1}function d(b, g,u){g=b.css(g);b=parseFloat(g);return isNaN(b)?(b=z[g]||0,u=3==b?u?a.win.outerHeight()-a.win.innerHeight():a.win.outerWidth()-a.win.innerWidth():1,a.isie8&&b&&(b+=1),u?b:0):b}function q(b,g,u,c){a._bind(b,g,function(a){a=a?a:window.event;var c={original:a,target:a.target||a.srcElement,type:"wheel",deltaMode:"MozMousePixelScroll"==a.type?0:1,deltaX:0,deltaZ:0,preventDefault:function(){a.preventDefault?a.preventDefault():a.returnValue=!1;return!1},stopImmediatePropagation:function(){a.stopImmediatePropagation? a.stopImmediatePropagation():a.cancelBubble=!0}};"mousewheel"==g?(a.wheelDeltaX&&(c.deltaX=-.025*a.wheelDeltaX),a.wheelDeltaY&&(c.deltaY=-.025*a.wheelDeltaY),c.deltaY||c.deltaX||(c.deltaY=-.025*a.wheelDelta)):c.deltaY=a.detail;return u.call(b,c)},c)}function t(b,g,c){var d,e;0==b.deltaMode?(d=-Math.floor(a.opt.mousescrollstep/54*b.deltaX),e=-Math.floor(a.opt.mousescrollstep/54*b.deltaY)):1==b.deltaMode&&(d=-Math.floor(b.deltaX*a.opt.mousescrollstep),e=-Math.floor(b.deltaY*a.opt.mousescrollstep)); g&&a.opt.oneaxismousemode&&0==d&&e&&(d=e,e=0,c&&(0>d?a.getScrollLeft()>=a.page.maxw:0>=a.getScrollLeft())&&(e=d,d=0));a.isrtlmode&&(d=-d);d&&(a.scrollmom&&a.scrollmom.stop(),a.lastdeltax+=d,a.debounced("mousewheelx",function(){var b=a.lastdeltax;a.lastdeltax=0;a.rail.drag||a.doScrollLeftBy(b)},15));if(e){if(a.opt.nativeparentscrolling&&c&&!a.ispage&&!a.zoomactive)if(0>e){if(a.getScrollTop()>=a.page.maxh)return!0}else if(0>=a.getScrollTop())return!0;a.scrollmom&&a.scrollmom.stop();a.lastdeltay+=e; a.synched("mousewheely",function(){var b=a.lastdeltay;a.lastdeltay=0;a.rail.drag||a.doScrollBy(b)},15)}b.stopImmediatePropagation();return b.preventDefault()}var a=this;this.version="3.6.8";this.name="nicescroll";this.me=c;this.opt={doc:f("body"),win:!1};f.extend(this.opt,K);this.opt.snapbackspeed=80;if(h)for(var r in a.opt)void 0!==h[r]&&(a.opt[r]=h[r]);a.opt.disablemutationobserver&&(x=!1);this.iddoc=(this.doc=a.opt.doc)&&this.doc[0]?this.doc[0].id||"":"";this.ispage=/^BODY|HTML/.test(a.opt.win? a.opt.win[0].nodeName:this.doc[0].nodeName);this.haswrapper=!1!==a.opt.win;this.win=a.opt.win||(this.ispage?f(window):this.doc);this.docscroll=this.ispage&&!this.haswrapper?f(window):this.win;this.body=f("body");this.iframe=this.isfixed=this.viewport=!1;this.isiframe="IFRAME"==this.doc[0].nodeName&&"IFRAME"==this.win[0].nodeName;this.istextarea="TEXTAREA"==this.win[0].nodeName;this.forcescreen=!1;this.canshowonmouseevent="scroll"!=a.opt.autohidemode;this.page=this.view=this.onzoomout=this.onzoomin= this.onscrollcancel=this.onscrollend=this.onscrollstart=this.onclick=this.ongesturezoom=this.onkeypress=this.onmousewheel=this.onmousemove=this.onmouseup=this.onmousedown=!1;this.scroll={x:0,y:0};this.scrollratio={x:0,y:0};this.cursorheight=20;this.scrollvaluemax=0;if("auto"==this.opt.rtlmode){r=this.win[0]==window?this.body:this.win;var p=r.css("writing-mode")||r.css("-webkit-writing-mode")||r.css("-ms-writing-mode")||r.css("-moz-writing-mode");"horizontal-tb"==p||"lr-tb"==p||""==p?(this.isrtlmode= "rtl"==r.css("direction"),this.isvertical=!1):(this.isrtlmode="vertical-rl"==p||"tb"==p||"tb-rl"==p||"rl-tb"==p,this.isvertical="vertical-rl"==p||"tb"==p||"tb-rl"==p)}else this.isrtlmode=!0===this.opt.rtlmode,this.isvertical=!1;this.observerbody=this.observerremover=this.observer=this.scrollmom=this.scrollrunning=!1;do this.id="ascrail"+P++;while(document.getElementById(this.id));this.hasmousefocus=this.hasfocus=this.zoomactive=this.zoom=this.selectiondrag=this.cursorfreezed=this.cursor=this.rail= !1;this.visibility=!0;this.hidden=this.locked=this.railslocked=!1;this.cursoractive=!0;this.wheelprevented=!1;this.overflowx=a.opt.overflowx;this.overflowy=a.opt.overflowy;this.nativescrollingarea=!1;this.checkarea=0;this.events=[];this.saved={};this.delaylist={};this.synclist={};this.lastdeltay=this.lastdeltax=0;this.detected=R();var e=f.extend({},this.detected);this.ishwscroll=(this.canhwscroll=e.hastransform&&a.opt.hwacceleration)&&a.haswrapper;this.hasreversehr=this.isrtlmode?this.isvertical? !(e.iswebkit||e.isie||e.isie11):!(e.iswebkit||e.isie&&!e.isie10&&!e.isie11):!1;this.istouchcapable=!1;e.cantouch||!e.hasw3ctouch&&!e.hasmstouch?!e.cantouch||e.isios||e.isandroid||!e.iswebkit&&!e.ismozilla||(this.istouchcapable=!0):this.istouchcapable=!0;a.opt.enablemouselockapi||(e.hasmousecapture=!1,e.haspointerlock=!1);this.debounced=function(b,g,c){a&&(a.delaylist[b]||(g.call(a),a.delaylist[b]={h:v(function(){a.delaylist[b].fn.call(a);a.delaylist[b]=!1},c)}),a.delaylist[b].fn=g)};var I=!1;this.synched= function(b,g){a.synclist[b]=g;(function(){I||(v(function(){if(a){I=!1;for(var b in a.synclist){var g=a.synclist[b];g&&g.call(a);a.synclist[b]=!1}}}),I=!0)})();return b};this.unsynched=function(b){a.synclist[b]&&(a.synclist[b]=!1)};this.css=function(b,g){for(var c in g)a.saved.css.push([b,c,b.css(c)]),b.css(c,g[c])};this.scrollTop=function(b){return void 0===b?a.getScrollTop():a.setScrollTop(b)};this.scrollLeft=function(b){return void 0===b?a.getScrollLeft():a.setScrollLeft(b)};var D=function(a,g, c,d,e,f,k){this.st=a;this.ed=g;this.spd=c;this.p1=d||0;this.p2=e||1;this.p3=f||0;this.p4=k||1;this.ts=(new Date).getTime();this.df=this.ed-this.st};D.prototype={B2:function(a){return 3*a*a*(1-a)},B3:function(a){return 3*a*(1-a)*(1-a)},B4:function(a){return(1-a)*(1-a)*(1-a)},getNow:function(){var a=1-((new Date).getTime()-this.ts)/this.spd,g=this.B2(a)+this.B3(a)+this.B4(a);return 0>a?this.ed:this.st+Math.round(this.df*g)},update:function(a,g){this.st=this.getNow();this.ed=a;this.spd=g;this.ts=(new Date).getTime(); this.df=this.ed-this.st;return this}};if(this.ishwscroll){this.doc.translate={x:0,y:0,tx:"0px",ty:"0px"};e.hastranslate3d&&e.isios&&this.doc.css("-webkit-backface-visibility","hidden");this.getScrollTop=function(b){if(!b){if(b=k())return 16==b.length?-b[13]:-b[5];if(a.timerscroll&&a.timerscroll.bz)return a.timerscroll.bz.getNow()}return a.doc.translate.y};this.getScrollLeft=function(b){if(!b){if(b=k())return 16==b.length?-b[12]:-b[4];if(a.timerscroll&&a.timerscroll.bh)return a.timerscroll.bh.getNow()}return a.doc.translate.x}; this.notifyScrollEvent=function(a){var g=document.createEvent("UIEvents");g.initUIEvent("scroll",!1,!0,window,1);g.niceevent=!0;a.dispatchEvent(g)};var y=this.isrtlmode?1:-1;e.hastranslate3d&&a.opt.enabletranslate3d?(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle, "translate3d("+a.doc.translate.tx+","+a.doc.translate.ty+",0px)");g||a.notifyScrollEvent(a.win[0])}):(this.setScrollTop=function(b,g){a.doc.translate.y=b;a.doc.translate.ty=-1*b+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])},this.setScrollLeft=function(b,g){a.doc.translate.x=b;a.doc.translate.tx=b*y+"px";a.doc.css(e.trstyle,"translate("+a.doc.translate.tx+","+a.doc.translate.ty+")");g||a.notifyScrollEvent(a.win[0])})}else this.getScrollTop= function(){return a.docscroll.scrollTop()},this.setScrollTop=function(b){return setTimeout(function(){a&&a.docscroll.scrollTop(b)},1)},this.getScrollLeft=function(){return a.hasreversehr?a.detected.ismozilla?a.page.maxw-Math.abs(a.docscroll.scrollLeft()):a.page.maxw-a.docscroll.scrollLeft():a.docscroll.scrollLeft()},this.setScrollLeft=function(b){return setTimeout(function(){if(a)return a.hasreversehr&&(b=a.detected.ismozilla?-(a.page.maxw-b):a.page.maxw-b),a.docscroll.scrollLeft(b)},1)};this.getTarget= function(a){return a?a.target?a.target:a.srcElement?a.srcElement:!1:!1};this.hasParent=function(a,g){if(!a)return!1;for(var c=a.target||a.srcElement||a||!1;c&&c.id!=g;)c=c.parentNode||!1;return!1!==c};var z={thin:1,medium:3,thick:5};this.getDocumentScrollOffset=function(){return{top:window.pageYOffset||document.documentElement.scrollTop,left:window.pageXOffset||document.documentElement.scrollLeft}};this.getOffset=function(){if(a.isfixed){var b=a.win.offset(),g=a.getDocumentScrollOffset();b.top-=g.top; b.left-=g.left;return b}b=a.win.offset();if(!a.viewport)return b;g=a.viewport.offset();return{top:b.top-g.top,left:b.left-g.left}};this.updateScrollBar=function(b){var g,c,e;if(a.ishwscroll)a.rail.css({height:a.win.innerHeight()-(a.opt.railpadding.top+a.opt.railpadding.bottom)}),a.railh&&a.railh.css({width:a.win.innerWidth()-(a.opt.railpadding.left+a.opt.railpadding.right)});else{var f=a.getOffset();g=f.top;c=f.left-(a.opt.railpadding.left+a.opt.railpadding.right);g+=d(a.win,"border-top-width",!0); c+=a.rail.align?a.win.outerWidth()-d(a.win,"border-right-width")-a.rail.width:d(a.win,"border-left-width");if(e=a.opt.railoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);a.railslocked||a.rail.css({top:g,left:c,height:(b?b.h:a.win.innerHeight())-(a.opt.railpadding.top+a.opt.railpadding.bottom)});a.zoom&&a.zoom.css({top:g+1,left:1==a.rail.align?c-20:c+a.rail.width+4});if(a.railh&&!a.railslocked){g=f.top;c=f.left;if(e=a.opt.railhoffset)e.top&&(g+=e.top),e.left&&(c+=e.left);b=a.railh.align?g+d(a.win,"border-top-width", !0)+a.win.innerHeight()-a.railh.height:g+d(a.win,"border-top-width",!0);c+=d(a.win,"border-left-width");a.railh.css({top:b-(a.opt.railpadding.top+a.opt.railpadding.bottom),left:c,width:a.railh.width})}}};this.doRailClick=function(b,g,c){var d;a.railslocked||(a.cancelEvent(b),g?(g=c?a.doScrollLeft:a.doScrollTop,d=c?(b.pageX-a.railh.offset().left-a.cursorwidth/2)*a.scrollratio.x:(b.pageY-a.rail.offset().top-a.cursorheight/2)*a.scrollratio.y,g(d)):(g=c?a.doScrollLeftBy:a.doScrollBy,d=c?a.scroll.x:a.scroll.y, b=c?b.pageX-a.railh.offset().left:b.pageY-a.rail.offset().top,c=c?a.view.w:a.view.h,g(d>=b?c:-c)))};a.hasanimationframe=v;a.hascancelanimationframe=w;a.hasanimationframe?a.hascancelanimationframe||(w=function(){a.cancelAnimationFrame=!0}):(v=function(a){return setTimeout(a,15-Math.floor(+new Date/1E3)%16)},w=clearTimeout);this.init=function(){a.saved.css=[];if(e.isie7mobile||e.isoperamini)return!0;e.hasmstouch&&a.css(a.ispage?f("html"):a.win,{_touchaction:"none"});var b=e.ismodernie||e.isie10?{"-ms-overflow-style":"none"}: {"overflow-y":"hidden"};a.zindex="auto";a.zindex=a.ispage||"auto"!=a.opt.zindex?a.opt.zindex:l()||"auto";!a.ispage&&"auto"!=a.zindex&&a.zindex>A&&(A=a.zindex);a.isie&&0==a.zindex&&"auto"==a.opt.zindex&&(a.zindex="auto");if(!a.ispage||!e.cantouch&&!e.isieold&&!e.isie9mobile){var c=a.docscroll;a.ispage&&(c=a.haswrapper?a.win:a.doc);e.isie9mobile||a.css(c,b);a.ispage&&e.isie7&&("BODY"==a.doc[0].nodeName?a.css(f("html"),{"overflow-y":"hidden"}):"HTML"==a.doc[0].nodeName&&a.css(f("body"),b));!e.isios|| a.ispage||a.haswrapper||a.css(f("body"),{"-webkit-overflow-scrolling":"touch"});var d=f(document.createElement("div"));d.css({position:"relative",top:0,"float":"right",width:a.opt.cursorwidth,height:0,"background-color":a.opt.cursorcolor,border:a.opt.cursorborder,"background-clip":"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius,"border-radius":a.opt.cursorborderradius});d.hborder=parseFloat(d.outerHeight()-d.innerHeight());d.addClass("nicescroll-cursors"); a.cursor=d;var m=f(document.createElement("div"));m.attr("id",a.id);m.addClass("nicescroll-rails nicescroll-rails-vr");var k,h,p=["left","right","top","bottom"],L;for(L in p)h=p[L],(k=a.opt.railpadding[h])?m.css("padding-"+h,k+"px"):a.opt.railpadding[h]=0;m.append(d);m.width=Math.max(parseFloat(a.opt.cursorwidth),d.outerWidth());m.css({width:m.width+"px",zIndex:a.zindex,background:a.opt.background,cursor:"default"});m.visibility=!0;m.scrollable=!0;m.align="left"==a.opt.railalign?0:1;a.rail=m;d=a.rail.drag= !1;!a.opt.boxzoom||a.ispage||e.isieold||(d=document.createElement("div"),a.bind(d,"click",a.doZoom),a.bind(d,"mouseenter",function(){a.zoom.css("opacity",a.opt.cursoropacitymax)}),a.bind(d,"mouseleave",function(){a.zoom.css("opacity",a.opt.cursoropacitymin)}),a.zoom=f(d),a.zoom.css({cursor:"pointer",zIndex:a.zindex,backgroundImage:"url("+a.opt.scriptpath+"zoomico.png)",height:18,width:18,backgroundPosition:"0px 0px"}),a.opt.dblclickzoom&&a.bind(a.win,"dblclick",a.doZoom),e.cantouch&&a.opt.gesturezoom&& (a.ongesturezoom=function(b){1.5<b.scale&&a.doZoomIn(b);.8>b.scale&&a.doZoomOut(b);return a.cancelEvent(b)},a.bind(a.win,"gestureend",a.ongesturezoom)));a.railh=!1;var n;a.opt.horizrailenabled&&(a.css(c,{overflowX:"hidden"}),d=f(document.createElement("div")),d.css({position:"absolute",top:0,height:a.opt.cursorwidth,width:0,backgroundColor:a.opt.cursorcolor,border:a.opt.cursorborder,backgroundClip:"padding-box","-webkit-border-radius":a.opt.cursorborderradius,"-moz-border-radius":a.opt.cursorborderradius, "border-radius":a.opt.cursorborderradius}),e.isieold&&d.css("overflow","hidden"),d.wborder=parseFloat(d.outerWidth()-d.innerWidth()),d.addClass("nicescroll-cursors"),a.cursorh=d,n=f(document.createElement("div")),n.attr("id",a.id+"-hr"),n.addClass("nicescroll-rails nicescroll-rails-hr"),n.height=Math.max(parseFloat(a.opt.cursorwidth),d.outerHeight()),n.css({height:n.height+"px",zIndex:a.zindex,background:a.opt.background}),n.append(d),n.visibility=!0,n.scrollable=!0,n.align="top"==a.opt.railvalign? 0:1,a.railh=n,a.railh.drag=!1);a.ispage?(m.css({position:"fixed",top:0,height:"100%"}),m.align?m.css({right:0}):m.css({left:0}),a.body.append(m),a.railh&&(n.css({position:"fixed",left:0,width:"100%"}),n.align?n.css({bottom:0}):n.css({top:0}),a.body.append(n))):(a.ishwscroll?("static"==a.win.css("position")&&a.css(a.win,{position:"relative"}),c="HTML"==a.win[0].nodeName?a.body:a.win,f(c).scrollTop(0).scrollLeft(0),a.zoom&&(a.zoom.css({position:"absolute",top:1,right:0,"margin-right":m.width+4}),c.append(a.zoom)), m.css({position:"absolute",top:0}),m.align?m.css({right:0}):m.css({left:0}),c.append(m),n&&(n.css({position:"absolute",left:0,bottom:0}),n.align?n.css({bottom:0}):n.css({top:0}),c.append(n))):(a.isfixed="fixed"==a.win.css("position"),c=a.isfixed?"fixed":"absolute",a.isfixed||(a.viewport=a.getViewport(a.win[0])),a.viewport&&(a.body=a.viewport,0==/fixed|absolute/.test(a.viewport.css("position"))&&a.css(a.viewport,{position:"relative"})),m.css({position:c}),a.zoom&&a.zoom.css({position:c}),a.updateScrollBar(), a.body.append(m),a.zoom&&a.body.append(a.zoom),a.railh&&(n.css({position:c}),a.body.append(n))),e.isios&&a.css(a.win,{"-webkit-tap-highlight-color":"rgba(0,0,0,0)","-webkit-touch-callout":"none"}),e.isie&&a.opt.disableoutline&&a.win.attr("hideFocus","true"),e.iswebkit&&a.opt.disableoutline&&a.win.css("outline","none"));!1===a.opt.autohidemode?(a.autohidedom=!1,a.rail.css({opacity:a.opt.cursoropacitymax}),a.railh&&a.railh.css({opacity:a.opt.cursoropacitymax})):!0===a.opt.autohidemode||"leave"===a.opt.autohidemode? (a.autohidedom=f().add(a.rail),e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursor)),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh)),a.railh&&e.isie8&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"scroll"==a.opt.autohidemode?(a.autohidedom=f().add(a.rail),a.railh&&(a.autohidedom=a.autohidedom.add(a.railh))):"cursor"==a.opt.autohidemode?(a.autohidedom=f().add(a.cursor),a.railh&&(a.autohidedom=a.autohidedom.add(a.cursorh))):"hidden"==a.opt.autohidemode&&(a.autohidedom=!1,a.hide(),a.railslocked= !1);if(e.isie9mobile)a.scrollmom=new M(a),a.onmangotouch=function(){var b=a.getScrollTop(),c=a.getScrollLeft();if(b==a.scrollmom.lastscrolly&&c==a.scrollmom.lastscrollx)return!0;var g=b-a.mangotouch.sy,d=c-a.mangotouch.sx;if(0!=Math.round(Math.sqrt(Math.pow(d,2)+Math.pow(g,2)))){var e=0>g?-1:1,f=0>d?-1:1,u=+new Date;a.mangotouch.lazy&&clearTimeout(a.mangotouch.lazy);80<u-a.mangotouch.tm||a.mangotouch.dry!=e||a.mangotouch.drx!=f?(a.scrollmom.stop(),a.scrollmom.reset(c,b),a.mangotouch.sy=b,a.mangotouch.ly= b,a.mangotouch.sx=c,a.mangotouch.lx=c,a.mangotouch.dry=e,a.mangotouch.drx=f,a.mangotouch.tm=u):(a.scrollmom.stop(),a.scrollmom.update(a.mangotouch.sx-d,a.mangotouch.sy-g),a.mangotouch.tm=u,g=Math.max(Math.abs(a.mangotouch.ly-b),Math.abs(a.mangotouch.lx-c)),a.mangotouch.ly=b,a.mangotouch.lx=c,2<g&&(a.mangotouch.lazy=setTimeout(function(){a.mangotouch.lazy=!1;a.mangotouch.dry=0;a.mangotouch.drx=0;a.mangotouch.tm=0;a.scrollmom.doMomentum(30)},100)))}},m=a.getScrollTop(),n=a.getScrollLeft(),a.mangotouch= {sy:m,ly:m,dry:0,sx:n,lx:n,drx:0,lazy:!1,tm:0},a.bind(a.docscroll,"scroll",a.onmangotouch);else{if(e.cantouch||a.istouchcapable||a.opt.touchbehavior||e.hasmstouch){a.scrollmom=new M(a);a.ontouchstart=function(b){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;a.hasmoving=!1;if(!a.railslocked){var c;if(e.hasmstouch)for(c=b.target?b.target:!1;c;){var g=f(c).getNiceScroll();if(0<g.length&&g[0].me==a.me)break;if(0<g.length)return!1;if("DIV"==c.nodeName&&c.id==a.id)break;c=c.parentNode? c.parentNode:!1}a.cancelScroll();if((c=a.getTarget(b))&&/INPUT/i.test(c.nodeName)&&/range/i.test(c.type))return a.stopPropagation(b);!("clientX"in b)&&"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);a.forcescreen&&(g=b,b={original:b.original?b.original:b},b.clientX=g.screenX,b.clientY=g.screenY);a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,st:a.getScrollTop(),sl:a.getScrollLeft(),pt:2,dl:!1};if(a.ispage||!a.opt.directionlockdeadzone)a.rail.drag.dl= "f";else{var g=f(window).width(),d=f(window).height(),d=Math.max(0,Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)-d),g=Math.max(0,Math.max(document.body.scrollWidth,document.documentElement.scrollWidth)-g);a.rail.drag.ck=!a.rail.scrollable&&a.railh.scrollable?0<d?"v":!1:a.rail.scrollable&&!a.railh.scrollable?0<g?"h":!1:!1;a.rail.drag.ck||(a.rail.drag.dl="f")}a.opt.touchbehavior&&a.isiframe&&e.isie&&(g=a.win.position(),a.rail.drag.x+=g.left,a.rail.drag.y+=g.top);a.hasmoving= !1;a.lastmouseup=!1;a.scrollmom.reset(b.clientX,b.clientY);if(!e.cantouch&&!this.istouchcapable&&!b.pointerType){if(!c||!/INPUT|SELECT|TEXTAREA/i.test(c.nodeName))return!a.ispage&&e.hasmousecapture&&c.setCapture(),a.opt.touchbehavior?(c.onclick&&!c._onclick&&(c._onclick=c.onclick,c.onclick=function(b){if(a.hasmoving)return!1;c._onclick.call(this,b)}),a.cancelEvent(b)):a.stopPropagation(b);/SUBMIT|CANCEL|BUTTON/i.test(f(c).attr("type"))&&(pc={tg:c,click:!1},a.preventclick=pc)}}};a.ontouchend=function(b){if(!a.rail.drag)return!0; if(2==a.rail.drag.pt){if(b.pointerType&&2!=b.pointerType&&"touch"!=b.pointerType)return!1;a.scrollmom.doMomentum();a.rail.drag=!1;if(a.hasmoving&&(a.lastmouseup=!0,a.hideCursor(),e.hasmousecapture&&document.releaseCapture(),!e.cantouch))return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmouseup(b)};var q=a.opt.touchbehavior&&a.isiframe&&!e.hasmousecapture;a.ontouchmove=function(b,c){if(!a.rail.drag||b.targetTouches&&a.opt.preventmultitouchscrolling&&1<b.targetTouches.length||b.pointerType&& 2!=b.pointerType&&"touch"!=b.pointerType)return!1;if(2==a.rail.drag.pt){if(e.cantouch&&e.isios&&void 0===b.original)return!0;a.hasmoving=!0;a.preventclick&&!a.preventclick.click&&(a.preventclick.click=a.preventclick.tg.onclick||!1,a.preventclick.tg.onclick=a.onpreventclick);b=f.extend({original:b},b);"changedTouches"in b&&(b.clientX=b.changedTouches[0].clientX,b.clientY=b.changedTouches[0].clientY);if(a.forcescreen){var g=b;b={original:b.original?b.original:b};b.clientX=g.screenX;b.clientY=g.screenY}var d, g=d=0;q&&!c&&(d=a.win.position(),g=-d.left,d=-d.top);var u=b.clientY+d;d=u-a.rail.drag.y;var m=b.clientX+g,k=m-a.rail.drag.x,h=a.rail.drag.st-d;a.ishwscroll&&a.opt.bouncescroll?0>h?h=Math.round(h/2):h>a.page.maxh&&(h=a.page.maxh+Math.round((h-a.page.maxh)/2)):(0>h&&(u=h=0),h>a.page.maxh&&(h=a.page.maxh,u=0));var l;a.railh&&a.railh.scrollable&&(l=a.isrtlmode?k-a.rail.drag.sl:a.rail.drag.sl-k,a.ishwscroll&&a.opt.bouncescroll?0>l?l=Math.round(l/2):l>a.page.maxw&&(l=a.page.maxw+Math.round((l-a.page.maxw)/ 2)):(0>l&&(m=l=0),l>a.page.maxw&&(l=a.page.maxw,m=0)));g=!1;if(a.rail.drag.dl)g=!0,"v"==a.rail.drag.dl?l=a.rail.drag.sl:"h"==a.rail.drag.dl&&(h=a.rail.drag.st);else{d=Math.abs(d);var k=Math.abs(k),C=a.opt.directionlockdeadzone;if("v"==a.rail.drag.ck){if(d>C&&k<=.3*d)return a.rail.drag=!1,!0;k>C&&(a.rail.drag.dl="f",f("body").scrollTop(f("body").scrollTop()))}else if("h"==a.rail.drag.ck){if(k>C&&d<=.3*k)return a.rail.drag=!1,!0;d>C&&(a.rail.drag.dl="f",f("body").scrollLeft(f("body").scrollLeft()))}}a.synched("touchmove", function(){a.rail.drag&&2==a.rail.drag.pt&&(a.prepareTransition&&a.prepareTransition(0),a.rail.scrollable&&a.setScrollTop(h),a.scrollmom.update(m,u),a.railh&&a.railh.scrollable?(a.setScrollLeft(l),a.showCursor(h,l)):a.showCursor(h),e.isie10&&document.selection.clear())});e.ischrome&&a.istouchcapable&&(g=!1);if(g)return a.cancelEvent(b)}else if(1==a.rail.drag.pt)return a.onmousemove(b)}}a.onmousedown=function(b,c){if(!a.rail.drag||1==a.rail.drag.pt){if(a.railslocked)return a.cancelEvent(b);a.cancelScroll(); a.rail.drag={x:b.clientX,y:b.clientY,sx:a.scroll.x,sy:a.scroll.y,pt:1,hr:!!c};var g=a.getTarget(b);!a.ispage&&e.hasmousecapture&&g.setCapture();a.isiframe&&!e.hasmousecapture&&(a.saved.csspointerevents=a.doc.css("pointer-events"),a.css(a.doc,{"pointer-events":"none"}));a.hasmoving=!1;return a.cancelEvent(b)}};a.onmouseup=function(b){if(a.rail.drag){if(1!=a.rail.drag.pt)return!0;e.hasmousecapture&&document.releaseCapture();a.isiframe&&!e.hasmousecapture&&a.doc.css("pointer-events",a.saved.csspointerevents); a.rail.drag=!1;a.hasmoving&&a.triggerScrollEnd();return a.cancelEvent(b)}};a.onmousemove=function(b){if(a.rail.drag){if(1==a.rail.drag.pt){if(e.ischrome&&0==b.which)return a.onmouseup(b);a.cursorfreezed=!0;a.hasmoving=!0;if(a.rail.drag.hr){a.scroll.x=a.rail.drag.sx+(b.clientX-a.rail.drag.x);0>a.scroll.x&&(a.scroll.x=0);var c=a.scrollvaluemaxw;a.scroll.x>c&&(a.scroll.x=c)}else a.scroll.y=a.rail.drag.sy+(b.clientY-a.rail.drag.y),0>a.scroll.y&&(a.scroll.y=0),c=a.scrollvaluemax,a.scroll.y>c&&(a.scroll.y= c);a.synched("mousemove",function(){a.rail.drag&&1==a.rail.drag.pt&&(a.showCursor(),a.rail.drag.hr?a.hasreversehr?a.doScrollLeft(a.scrollvaluemaxw-Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollLeft(Math.round(a.scroll.x*a.scrollratio.x),a.opt.cursordragspeed):a.doScrollTop(Math.round(a.scroll.y*a.scrollratio.y),a.opt.cursordragspeed))});return a.cancelEvent(b)}}else a.checkarea=0};if(e.cantouch||a.opt.touchbehavior)a.onpreventclick=function(b){if(a.preventclick)return a.preventclick.tg.onclick= a.preventclick.click,a.preventclick=!1,a.cancelEvent(b)},a.bind(a.win,"mousedown",a.ontouchstart),a.onclick=e.isios?!1:function(b){return a.lastmouseup?(a.lastmouseup=!1,a.cancelEvent(b)):!0},a.opt.grabcursorenabled&&e.cursorgrabvalue&&(a.css(a.ispage?a.doc:a.win,{cursor:e.cursorgrabvalue}),a.css(a.rail,{cursor:e.cursorgrabvalue}));else{var r=function(b){if(a.selectiondrag){if(b){var c=a.win.outerHeight();b=b.pageY-a.selectiondrag.top;0<b&&b<c&&(b=0);b>=c&&(b-=c);a.selectiondrag.df=b}0!=a.selectiondrag.df&& (a.doScrollBy(2*-Math.floor(a.selectiondrag.df/6)),a.debounced("doselectionscroll",function(){r()},50))}};a.hasTextSelected="getSelection"in document?function(){return 0<document.getSelection().rangeCount}:"selection"in document?function(){return"None"!=document.selection.type}:function(){return!1};a.onselectionstart=function(b){a.ispage||(a.selectiondrag=a.win.offset())};a.onselectionend=function(b){a.selectiondrag=!1};a.onselectiondrag=function(b){a.selectiondrag&&a.hasTextSelected()&&a.debounced("selectionscroll", function(){r(b)},250)}}e.hasw3ctouch?(a.css(a.rail,{"touch-action":"none"}),a.css(a.cursor,{"touch-action":"none"}),a.bind(a.win,"pointerdown",a.ontouchstart),a.bind(document,"pointerup",a.ontouchend),a.bind(document,"pointermove",a.ontouchmove)):e.hasmstouch?(a.css(a.rail,{"-ms-touch-action":"none"}),a.css(a.cursor,{"-ms-touch-action":"none"}),a.bind(a.win,"MSPointerDown",a.ontouchstart),a.bind(document,"MSPointerUp",a.ontouchend),a.bind(document,"MSPointerMove",a.ontouchmove),a.bind(a.cursor,"MSGestureHold", function(a){a.preventDefault()}),a.bind(a.cursor,"contextmenu",function(a){a.preventDefault()})):this.istouchcapable&&(a.bind(a.win,"touchstart",a.ontouchstart),a.bind(document,"touchend",a.ontouchend),a.bind(document,"touchcancel",a.ontouchend),a.bind(document,"touchmove",a.ontouchmove));if(a.opt.cursordragontouch||!e.cantouch&&!a.opt.touchbehavior)a.rail.css({cursor:"default"}),a.railh&&a.railh.css({cursor:"default"}),a.jqbind(a.rail,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1; a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.rail,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.rail,"click",function(b){a.doRailClick(b,!1,!1)}),a.bind(a.rail,"dblclick",function(b){a.doRailClick(b,!0,!1)}),a.bind(a.cursor,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursor,"dblclick",function(b){a.cancelEvent(b)})),a.railh&&(a.jqbind(a.railh,"mouseenter",function(){if(!a.ispage&&!a.win.is(":visible"))return!1;a.canshowonmouseevent&& a.showCursor();a.rail.active=!0}),a.jqbind(a.railh,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()}),a.opt.sensitiverail&&(a.bind(a.railh,"click",function(b){a.doRailClick(b,!1,!0)}),a.bind(a.railh,"dblclick",function(b){a.doRailClick(b,!0,!0)}),a.bind(a.cursorh,"click",function(b){a.cancelEvent(b)}),a.bind(a.cursorh,"dblclick",function(b){a.cancelEvent(b)})));e.cantouch||a.opt.touchbehavior?(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.ontouchend),a.bind(document,"mousemove", a.ontouchmove),a.onclick&&a.bind(document,"click",a.onclick),a.opt.cursordragontouch?(a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.cursorh&&a.bind(a.cursorh,"mousedown",function(b){a.onmousedown(b,!0)}),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onmouseup)):(a.bind(a.rail,"mousedown",function(a){a.preventDefault()}),a.railh&&a.bind(a.railh,"mousedown",function(a){a.preventDefault()}))):(a.bind(e.hasmousecapture?a.win:document,"mouseup",a.onmouseup),a.bind(document, "mousemove",a.onmousemove),a.onclick&&a.bind(document,"click",a.onclick),a.bind(a.cursor,"mousedown",a.onmousedown),a.bind(a.cursor,"mouseup",a.onmouseup),a.railh&&(a.bind(a.cursorh,"mousedown",function(b){a.onmousedown(b,!0)}),a.bind(a.cursorh,"mouseup",a.onmouseup)),!a.ispage&&a.opt.enablescrollonselection&&(a.bind(a.win[0],"mousedown",a.onselectionstart),a.bind(document,"mouseup",a.onselectionend),a.bind(a.cursor,"mouseup",a.onselectionend),a.cursorh&&a.bind(a.cursorh,"mouseup",a.onselectionend), a.bind(document,"mousemove",a.onselectiondrag)),a.zoom&&(a.jqbind(a.zoom,"mouseenter",function(){a.canshowonmouseevent&&a.showCursor();a.rail.active=!0}),a.jqbind(a.zoom,"mouseleave",function(){a.rail.active=!1;a.rail.drag||a.hideCursor()})));a.opt.enablemousewheel&&(a.isiframe||a.mousewheel(e.isie&&a.ispage?document:a.win,a.onmousewheel),a.mousewheel(a.rail,a.onmousewheel),a.railh&&a.mousewheel(a.railh,a.onmousewheelhr));a.ispage||e.cantouch||/HTML|^BODY/.test(a.win[0].nodeName)||(a.win.attr("tabindex")|| a.win.attr({tabindex:O++}),a.jqbind(a.win,"focus",function(b){B=a.getTarget(b).id||!0;a.hasfocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,"blur",function(b){B=!1;a.hasfocus=!1}),a.jqbind(a.win,"mouseenter",function(b){F=a.getTarget(b).id||!0;a.hasmousefocus=!0;a.canshowonmouseevent&&a.noticeCursor()}),a.jqbind(a.win,"mouseleave",function(){F=!1;a.hasmousefocus=!1;a.rail.drag||a.hideCursor()}))}a.onkeypress=function(b){if(a.railslocked&&0==a.page.maxh)return!0;b=b?b:window.e;var c= a.getTarget(b);if(c&&/INPUT|TEXTAREA|SELECT|OPTION/.test(c.nodeName)&&(!c.getAttribute("type")&&!c.type||!/submit|button|cancel/i.tp)||f(c).attr("contenteditable"))return!0;if(a.hasfocus||a.hasmousefocus&&!B||a.ispage&&!B&&!F){c=b.keyCode;if(a.railslocked&&27!=c)return a.cancelEvent(b);var g=b.ctrlKey||!1,d=b.shiftKey||!1,e=!1;switch(c){case 38:case 63233:a.doScrollBy(72);e=!0;break;case 40:case 63235:a.doScrollBy(-72);e=!0;break;case 37:case 63232:a.railh&&(g?a.doScrollLeft(0):a.doScrollLeftBy(72), e=!0);break;case 39:case 63234:a.railh&&(g?a.doScrollLeft(a.page.maxw):a.doScrollLeftBy(-72),e=!0);break;case 33:case 63276:a.doScrollBy(a.view.h);e=!0;break;case 34:case 63277:a.doScrollBy(-a.view.h);e=!0;break;case 36:case 63273:a.railh&&g?a.doScrollPos(0,0):a.doScrollTo(0);e=!0;break;case 35:case 63275:a.railh&&g?a.doScrollPos(a.page.maxw,a.page.maxh):a.doScrollTo(a.page.maxh);e=!0;break;case 32:a.opt.spacebarenabled&&(d?a.doScrollBy(a.view.h):a.doScrollBy(-a.view.h),e=!0);break;case 27:a.zoomactive&& (a.doZoom(),e=!0)}if(e)return a.cancelEvent(b)}};a.opt.enablekeyboard&&a.bind(document,e.isopera&&!e.isopera12?"keypress":"keydown",a.onkeypress);a.bind(document,"keydown",function(b){b.ctrlKey&&(a.wheelprevented=!0)});a.bind(document,"keyup",function(b){b.ctrlKey||(a.wheelprevented=!1)});a.bind(window,"blur",function(b){a.wheelprevented=!1});a.bind(window,"resize",a.lazyResize);a.bind(window,"orientationchange",a.lazyResize);a.bind(window,"load",a.lazyResize);if(e.ischrome&&!a.ispage&&!a.haswrapper){var t= a.win.attr("style"),m=parseFloat(a.win.css("width"))+1;a.win.css("width",m);a.synched("chromefix",function(){a.win.attr("style",t)})}a.onAttributeChange=function(b){a.lazyResize(a.isieold?250:30)};a.isie11||!1===x||(a.observerbody=new x(function(b){b.forEach(function(b){if("attributes"==b.type)return f("body").hasClass("modal-open")&&f("body").hasClass("modal-dialog")&&!f.contains(f(".modal-dialog")[0],a.doc[0])?a.hide():a.show()});if(document.body.scrollHeight!=a.page.maxh)return a.lazyResize(30)}), a.observerbody.observe(document.body,{childList:!0,subtree:!0,characterData:!1,attributes:!0,attributeFilter:["class"]}));a.ispage||a.haswrapper||(!1!==x?(a.observer=new x(function(b){b.forEach(a.onAttributeChange)}),a.observer.observe(a.win[0],{childList:!0,characterData:!1,attributes:!0,subtree:!1}),a.observerremover=new x(function(b){b.forEach(function(b){if(0<b.removedNodes.length)for(var c in b.removedNodes)if(a&&b.removedNodes[c]==a.win[0])return a.remove()})}),a.observerremover.observe(a.win[0].parentNode, {childList:!0,characterData:!1,attributes:!1,subtree:!1})):(a.bind(a.win,e.isie&&!e.isie9?"propertychange":"DOMAttrModified",a.onAttributeChange),e.isie9&&a.win[0].attachEvent("onpropertychange",a.onAttributeChange),a.bind(a.win,"DOMNodeRemoved",function(b){b.target==a.win[0]&&a.remove()})));!a.ispage&&a.opt.boxzoom&&a.bind(window,"resize",a.resizeZoom);a.istextarea&&(a.bind(a.win,"keydown",a.lazyResize),a.bind(a.win,"mouseup",a.lazyResize));a.lazyResize(30)}if("IFRAME"==this.doc[0].nodeName){var N= function(){a.iframexd=!1;var c;try{c="contentDocument"in this?this.contentDocument:this.contentWindow.document}catch(g){a.iframexd=!0,c=!1}if(a.iframexd)return"console"in window&&console.log("NiceScroll error: policy restriced iframe"),!0;a.forcescreen=!0;a.isiframe&&(a.iframe={doc:f(c),html:a.doc.contents().find("html")[0],body:a.doc.contents().find("body")[0]},a.getContentSize=function(){return{w:Math.max(a.iframe.html.scrollWidth,a.iframe.body.scrollWidth),h:Math.max(a.iframe.html.scrollHeight, a.iframe.body.scrollHeight)}},a.docscroll=f(a.iframe.body));if(!e.isios&&a.opt.iframeautoresize&&!a.isiframe){a.win.scrollTop(0);a.doc.height("");var d=Math.max(c.getElementsByTagName("html")[0].scrollHeight,c.body.scrollHeight);a.doc.height(d)}a.lazyResize(30);e.isie7&&a.css(f(a.iframe.html),b);a.css(f(a.iframe.body),b);e.isios&&a.haswrapper&&a.css(f(c.body),{"-webkit-transform":"translate3d(0,0,0)"});"contentWindow"in this?a.bind(this.contentWindow,"scroll",a.onscroll):a.bind(c,"scroll",a.onscroll); a.opt.enablemousewheel&&a.mousewheel(c,a.onmousewheel);a.opt.enablekeyboard&&a.bind(c,e.isopera?"keypress":"keydown",a.onkeypress);if(e.cantouch||a.opt.touchbehavior)a.bind(c,"mousedown",a.ontouchstart),a.bind(c,"mousemove",function(b){return a.ontouchmove(b,!0)}),a.opt.grabcursorenabled&&e.cursorgrabvalue&&a.css(f(c.body),{cursor:e.cursorgrabvalue});a.bind(c,"mouseup",a.ontouchend);a.zoom&&(a.opt.dblclickzoom&&a.bind(c,"dblclick",a.doZoom),a.ongesturezoom&&a.bind(c,"gestureend",a.ongesturezoom))}; this.doc[0].readyState&&"complete"==this.doc[0].readyState&&setTimeout(function(){N.call(a.doc[0],!1)},500);a.bind(this.doc,"load",N)}};this.showCursor=function(b,c){a.cursortimeout&&(clearTimeout(a.cursortimeout),a.cursortimeout=0);if(a.rail){a.autohidedom&&(a.autohidedom.stop().css({opacity:a.opt.cursoropacitymax}),a.cursoractive=!0);a.rail.drag&&1==a.rail.drag.pt||(void 0!==b&&!1!==b&&(a.scroll.y=Math.round(1*b/a.scrollratio.y)),void 0!==c&&(a.scroll.x=Math.round(1*c/a.scrollratio.x)));a.cursor.css({height:a.cursorheight, top:a.scroll.y});if(a.cursorh){var d=a.hasreversehr?a.scrollvaluemaxw-a.scroll.x:a.scroll.x;!a.rail.align&&a.rail.visibility?a.cursorh.css({width:a.cursorwidth,left:d+a.rail.width}):a.cursorh.css({width:a.cursorwidth,left:d});a.cursoractive=!0}a.zoom&&a.zoom.stop().css({opacity:a.opt.cursoropacitymax})}};this.hideCursor=function(b){a.cursortimeout||!a.rail||!a.autohidedom||a.hasmousefocus&&"leave"==a.opt.autohidemode||(a.cursortimeout=setTimeout(function(){a.rail.active&&a.showonmouseevent||(a.autohidedom.stop().animate({opacity:a.opt.cursoropacitymin}), a.zoom&&a.zoom.stop().animate({opacity:a.opt.cursoropacitymin}),a.cursoractive=!1);a.cursortimeout=0},b||a.opt.hidecursordelay))};this.noticeCursor=function(b,c,d){a.showCursor(c,d);a.rail.active||a.hideCursor(b)};this.getContentSize=a.ispage?function(){return{w:Math.max(document.body.scrollWidth,document.documentElement.scrollWidth),h:Math.max(document.body.scrollHeight,document.documentElement.scrollHeight)}}:a.haswrapper?function(){return{w:a.doc.outerWidth()+parseInt(a.win.css("paddingLeft"))+ parseInt(a.win.css("paddingRight")),h:a.doc.outerHeight()+parseInt(a.win.css("paddingTop"))+parseInt(a.win.css("paddingBottom"))}}:function(){return{w:a.docscroll[0].scrollWidth,h:a.docscroll[0].scrollHeight}};this.onResize=function(b,c){if(!a||!a.win)return!1;if(!a.haswrapper&&!a.ispage){if("none"==a.win.css("display"))return a.visibility&&a.hideRail().hideRailHr(),!1;a.hidden||a.visibility||a.showRail().showRailHr()}var d=a.page.maxh,e=a.page.maxw,f=a.view.h,k=a.view.w;a.view={w:a.ispage?a.win.width(): parseInt(a.win[0].clientWidth),h:a.ispage?a.win.height():parseInt(a.win[0].clientHeight)};a.page=c?c:a.getContentSize();a.page.maxh=Math.max(0,a.page.h-a.view.h);a.page.maxw=Math.max(0,a.page.w-a.view.w);if(a.page.maxh==d&&a.page.maxw==e&&a.view.w==k&&a.view.h==f){if(a.ispage)return a;d=a.win.offset();if(a.lastposition&&(e=a.lastposition,e.top==d.top&&e.left==d.left))return a;a.lastposition=d}0==a.page.maxh?(a.hideRail(),a.scrollvaluemax=0,a.scroll.y=0,a.scrollratio.y=0,a.cursorheight=0,a.setScrollTop(0), a.rail&&(a.rail.scrollable=!1)):(a.page.maxh-=a.opt.railpadding.top+a.opt.railpadding.bottom,a.rail.scrollable=!0);0==a.page.maxw?(a.hideRailHr(),a.scrollvaluemaxw=0,a.scroll.x=0,a.scrollratio.x=0,a.cursorwidth=0,a.setScrollLeft(0),a.railh&&(a.railh.scrollable=!1)):(a.page.maxw-=a.opt.railpadding.left+a.opt.railpadding.right,a.railh&&(a.railh.scrollable=a.opt.horizrailenabled));a.railslocked=a.locked||0==a.page.maxh&&0==a.page.maxw;if(a.railslocked)return a.ispage||a.updateScrollBar(a.view),!1;a.hidden|| a.visibility?!a.railh||a.hidden||a.railh.visibility||a.showRailHr():a.showRail().showRailHr();a.istextarea&&a.win.css("resize")&&"none"!=a.win.css("resize")&&(a.view.h-=20);a.cursorheight=Math.min(a.view.h,Math.round(a.view.h/a.page.h*a.view.h));a.cursorheight=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight,a.cursorheight);a.cursorwidth=Math.min(a.view.w,Math.round(a.view.w/a.page.w*a.view.w));a.cursorwidth=a.opt.cursorfixedheight?a.opt.cursorfixedheight:Math.max(a.opt.cursorminheight, a.cursorwidth);a.scrollvaluemax=a.view.h-a.cursorheight-a.cursor.hborder-(a.opt.railpadding.top+a.opt.railpadding.bottom);a.railh&&(a.railh.width=0<a.page.maxh?a.view.w-a.rail.width:a.view.w,a.scrollvaluemaxw=a.railh.width-a.cursorwidth-a.cursorh.wborder-(a.opt.railpadding.left+a.opt.railpadding.right));a.ispage||a.updateScrollBar(a.view);a.scrollratio={x:a.page.maxw/a.scrollvaluemaxw,y:a.page.maxh/a.scrollvaluemax};a.getScrollTop()>a.page.maxh?a.doScrollTop(a.page.maxh):(a.scroll.y=Math.round(a.getScrollTop()* (1/a.scrollratio.y)),a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x)),a.cursoractive&&a.noticeCursor());a.scroll.y&&0==a.getScrollTop()&&a.doScrollTo(Math.floor(a.scroll.y*a.scrollratio.y));return a};this.resize=a.onResize;this.hlazyresize=0;this.lazyResize=function(b){a.haswrapper||a.hide();a.hlazyresize&&clearTimeout(a.hlazyresize);a.hlazyresize=setTimeout(function(){a&&a.show().resize()},240);return a};this.jqbind=function(b,c,d){a.events.push({e:b,n:c,f:d,q:!0});f(b).bind(c,d)};this.mousewheel= function(b,c,d){b="jquery"in b?b[0]:b;if("onwheel"in document.createElement("div"))a._bind(b,"wheel",c,d||!1);else{var e=void 0!==document.onmousewheel?"mousewheel":"DOMMouseScroll";q(b,e,c,d||!1);"DOMMouseScroll"==e&&q(b,"MozMousePixelScroll",c,d||!1)}};e.haseventlistener?(this.bind=function(b,c,d,e){a._bind("jquery"in b?b[0]:b,c,d,e||!1)},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.addEventListener(c,d,e||!1)},this.cancelEvent=function(a){if(!a)return!1;a=a.original?a.original: a;a.cancelable&&a.preventDefault();a.stopPropagation();a.preventManipulation&&a.preventManipulation();return!1},this.stopPropagation=function(a){if(!a)return!1;a=a.original?a.original:a;a.stopPropagation();return!1},this._unbind=function(a,c,d,e){a.removeEventListener(c,d,e)}):(this.bind=function(b,c,d,e){var f="jquery"in b?b[0]:b;a._bind(f,c,function(b){(b=b||window.event||!1)&&b.srcElement&&(b.target=b.srcElement);"pageY"in b||(b.pageX=b.clientX+document.documentElement.scrollLeft,b.pageY=b.clientY+ document.documentElement.scrollTop);return!1===d.call(f,b)||!1===e?a.cancelEvent(b):!0})},this._bind=function(b,c,d,e){a.events.push({e:b,n:c,f:d,b:e,q:!1});b.attachEvent?b.attachEvent("on"+c,d):b["on"+c]=d},this.cancelEvent=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;a.cancel=!0;return a.returnValue=!1},this.stopPropagation=function(a){a=window.event||!1;if(!a)return!1;a.cancelBubble=!0;return!1},this._unbind=function(a,c,d,e){a.detachEvent?a.detachEvent("on"+c,d):a["on"+c]=!1}); this.unbindAll=function(){for(var b=0;b<a.events.length;b++){var c=a.events[b];c.q?c.e.unbind(c.n,c.f):a._unbind(c.e,c.n,c.f,c.b)}};this.showRail=function(){0==a.page.maxh||!a.ispage&&"none"==a.win.css("display")||(a.visibility=!0,a.rail.visibility=!0,a.rail.css("display","block"));return a};this.showRailHr=function(){if(!a.railh)return a;0==a.page.maxw||!a.ispage&&"none"==a.win.css("display")||(a.railh.visibility=!0,a.railh.css("display","block"));return a};this.hideRail=function(){a.visibility= !1;a.rail.visibility=!1;a.rail.css("display","none");return a};this.hideRailHr=function(){if(!a.railh)return a;a.railh.visibility=!1;a.railh.css("display","none");return a};this.show=function(){a.hidden=!1;a.railslocked=!1;return a.showRail().showRailHr()};this.hide=function(){a.hidden=!0;a.railslocked=!0;return a.hideRail().hideRailHr()};this.toggle=function(){return a.hidden?a.show():a.hide()};this.remove=function(){a.stop();a.cursortimeout&&clearTimeout(a.cursortimeout);for(var b in a.delaylist)a.delaylist[b]&& w(a.delaylist[b].h);a.doZoomOut();a.unbindAll();e.isie9&&a.win[0].detachEvent("onpropertychange",a.onAttributeChange);!1!==a.observer&&a.observer.disconnect();!1!==a.observerremover&&a.observerremover.disconnect();!1!==a.observerbody&&a.observerbody.disconnect();a.events=null;a.cursor&&a.cursor.remove();a.cursorh&&a.cursorh.remove();a.rail&&a.rail.remove();a.railh&&a.railh.remove();a.zoom&&a.zoom.remove();for(b=0;b<a.saved.css.length;b++){var c=a.saved.css[b];c[0].css(c[1],void 0===c[2]?"":c[2])}a.saved= !1;a.me.data("__nicescroll","");var d=f.nicescroll;d.each(function(b){if(this&&this.id===a.id){delete d[b];for(var c=++b;c<d.length;c++,b++)d[b]=d[c];d.length--;d.length&&delete d[d.length]}});for(var k in a)a[k]=null,delete a[k];a=null};this.scrollstart=function(b){this.onscrollstart=b;return a};this.scrollend=function(b){this.onscrollend=b;return a};this.scrollcancel=function(b){this.onscrollcancel=b;return a};this.zoomin=function(b){this.onzoomin=b;return a};this.zoomout=function(b){this.onzoomout= b;return a};this.isScrollable=function(a){a=a.target?a.target:a;if("OPTION"==a.nodeName)return!0;for(;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a),c=c.css("overflowY")||c.css("overflowX")||c.css("overflow")||"";if(/scroll|auto/.test(c))return a.clientHeight!=a.scrollHeight;a=a.parentNode?a.parentNode:!1}return!1};this.getViewport=function(a){for(a=a&&a.parentNode?a.parentNode:!1;a&&1==a.nodeType&&!/^BODY|HTML/.test(a.nodeName);){var c=f(a);if(/fixed|absolute/.test(c.css("position")))return c; var d=c.css("overflowY")||c.css("overflowX")||c.css("overflow")||"";if(/scroll|auto/.test(d)&&a.clientHeight!=a.scrollHeight||0<c.getNiceScroll().length)return c;a=a.parentNode?a.parentNode:!1}return!1};this.triggerScrollEnd=function(){if(a.onscrollend){var b=a.getScrollLeft(),c=a.getScrollTop();a.onscrollend.call(a,{type:"scrollend",current:{x:b,y:c},end:{x:b,y:c}})}};this.onmousewheel=function(b){if(!a.wheelprevented){if(a.railslocked)return a.debounced("checkunlock",a.resize,250),!0;if(a.rail.drag)return a.cancelEvent(b); "auto"==a.opt.oneaxismousemode&&0!=b.deltaX&&(a.opt.oneaxismousemode=!1);if(a.opt.oneaxismousemode&&0==b.deltaX&&!a.rail.scrollable)return a.railh&&a.railh.scrollable?a.onmousewheelhr(b):!0;var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;if(a.nativescrollingarea)return!0;if(b=t(b,!1,d))a.checkarea=0;return b}};this.onmousewheelhr=function(b){if(!a.wheelprevented){if(a.railslocked||!a.railh.scrollable)return!0;if(a.rail.drag)return a.cancelEvent(b); var c=+new Date,d=!1;a.opt.preservenativescrolling&&a.checkarea+600<c&&(a.nativescrollingarea=a.isScrollable(b),d=!0);a.checkarea=c;return a.nativescrollingarea?!0:a.railslocked?a.cancelEvent(b):t(b,!0,d)}};this.stop=function(){a.cancelScroll();a.scrollmon&&a.scrollmon.stop();a.cursorfreezed=!1;a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.noticeCursor();return a};this.getTransitionSpeed=function(b){b=Math.min(Math.round(10*a.opt.scrollspeed),Math.round(b/20*a.opt.scrollspeed));return 20< b?b:0};a.opt.smoothscroll?a.ishwscroll&&e.hastransition&&a.opt.usetransition&&a.opt.smoothscroll?(this.prepareTransition=function(b,c){var d=c?20<b?b:0:a.getTransitionSpeed(b),f=d?e.prefixstyle+"transform "+d+"ms ease-out":"";a.lasttransitionstyle&&a.lasttransitionstyle==f||(a.lasttransitionstyle=f,a.doc.css(e.transitionstyle,f));return d},this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning? a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var f=a.getScrollTop(),k=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();0==a.opt.bouncescroll&&(0>c?c=0:c>a.page.maxh&&(c=a.page.maxh),0>b?b=0:b>a.page.maxw&&(b=a.page.maxw));if(a.scrollrunning&&b==a.newscrollx&&c==a.newscrolly)return!1;a.newscrolly=c;a.newscrollx=b;a.newscrollspeed=d||!1;if(a.timer)return!1;a.timer=setTimeout(function(){var d=a.getScrollTop(),f=a.getScrollLeft(), k=Math.round(Math.sqrt(Math.pow(b-f,2)+Math.pow(c-d,2))),k=a.newscrollspeed&&1<a.newscrollspeed?a.newscrollspeed:a.getTransitionSpeed(k);a.newscrollspeed&&1>=a.newscrollspeed&&(k*=a.newscrollspeed);a.prepareTransition(k,!0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);0<k&&(!a.scrollrunning&&a.onscrollstart&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:f,y:d},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:k}),e.transitionend?a.scrollendtrapped||(a.scrollendtrapped= !0,a.bind(a.doc,e.transitionend,a.onScrollTransitionEnd,!1)):(a.scrollendtrapped&&clearTimeout(a.scrollendtrapped),a.scrollendtrapped=setTimeout(a.onScrollTransitionEnd,k)),a.timerscroll={bz:new D(d,a.newscrolly,k,0,0,.58,1),bh:new D(f,a.newscrollx,k,0,0,.58,1)},a.cursorfreezed||(a.timerscroll.tm=setInterval(function(){a.showCursor(a.getScrollTop(),a.getScrollLeft())},60)));a.synched("doScroll-set",function(){a.timer=0;a.scrollendtrapped&&(a.scrollrunning=!0);a.setScrollTop(a.newscrolly);a.setScrollLeft(a.newscrollx); if(!a.scrollendtrapped)a.onScrollTransitionEnd()})},50)},this.cancelScroll=function(){if(!a.scrollendtrapped)return!0;var b=a.getScrollTop(),c=a.getScrollLeft();a.scrollrunning=!1;e.transitionend||clearTimeout(e.transitionend);a.scrollendtrapped=!1;a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);a.prepareTransition(0);a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;a.cursorfreezed=!1;a.showCursor(b,c);return a}, this.onScrollTransitionEnd=function(){a.scrollendtrapped&&a._unbind(a.doc[0],e.transitionend,a.onScrollTransitionEnd);a.scrollendtrapped=!1;a.prepareTransition(0);a.timerscroll&&a.timerscroll.tm&&clearInterval(a.timerscroll.tm);a.timerscroll=!1;var b=a.getScrollTop(),c=a.getScrollLeft();a.setScrollTop(b);a.railh&&a.setScrollLeft(c);a.noticeCursor(!1,b,c);a.cursorfreezed=!1;0>b?b=0:b>a.page.maxh&&(b=a.page.maxh);0>c?c=0:c>a.page.maxw&&(c=a.page.maxw);if(b!=a.newscrolly||c!=a.newscrollx)return a.doScrollPos(c, b,a.opt.snapbackspeed);a.onscrollend&&a.scrollrunning&&a.triggerScrollEnd();a.scrollrunning=!1}):(this.doScrollLeft=function(b,c){var d=a.scrollrunning?a.newscrolly:a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.scrollrunning?a.newscrollx:a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){function e(){if(a.cancelAnimationFrame)return!0;a.scrollrunning=!0;if(p=1-p)return a.timer=v(e)||1;var b=0,c,d,f=d=a.getScrollTop();if(a.dst.ay){f=a.bzscroll? a.dst.py+a.bzscroll.getNow()*a.dst.ay:a.newscrolly;c=f-d;if(0>c&&f<a.newscrolly||0<c&&f>a.newscrolly)f=a.newscrolly;a.setScrollTop(f);f==a.newscrolly&&(b=1)}else b=1;d=c=a.getScrollLeft();if(a.dst.ax){d=a.bzscroll?a.dst.px+a.bzscroll.getNow()*a.dst.ax:a.newscrollx;c=d-c;if(0>c&&d<a.newscrollx||0<c&&d>a.newscrollx)d=a.newscrollx;a.setScrollLeft(d);d==a.newscrollx&&(b+=1)}else b+=1;2==b?(a.timer=0,a.cursorfreezed=!1,a.bzscroll=!1,a.scrollrunning=!1,0>f?f=0:f>a.page.maxh&&(f=Math.max(0,a.page.maxh)), 0>d?d=0:d>a.page.maxw&&(d=a.page.maxw),d!=a.newscrollx||f!=a.newscrolly?a.doScrollPos(d,f):a.onscrollend&&a.triggerScrollEnd()):a.timer=v(e)||1}c=void 0===c||!1===c?a.getScrollTop(!0):c;if(a.timer&&a.newscrolly==c&&a.newscrollx==b)return!0;a.timer&&w(a.timer);a.timer=0;var f=a.getScrollTop(),k=a.getScrollLeft();(0>(a.newscrolly-f)*(c-f)||0>(a.newscrollx-k)*(b-k))&&a.cancelScroll();a.newscrolly=c;a.newscrollx=b;a.bouncescroll&&a.rail.visibility||(0>a.newscrolly?a.newscrolly=0:a.newscrolly>a.page.maxh&& (a.newscrolly=a.page.maxh));a.bouncescroll&&a.railh.visibility||(0>a.newscrollx?a.newscrollx=0:a.newscrollx>a.page.maxw&&(a.newscrollx=a.page.maxw));a.dst={};a.dst.x=b-k;a.dst.y=c-f;a.dst.px=k;a.dst.py=f;var h=Math.round(Math.sqrt(Math.pow(a.dst.x,2)+Math.pow(a.dst.y,2)));a.dst.ax=a.dst.x/h;a.dst.ay=a.dst.y/h;var l=0,n=h;0==a.dst.x?(l=f,n=c,a.dst.ay=1,a.dst.py=0):0==a.dst.y&&(l=k,n=b,a.dst.ax=1,a.dst.px=0);h=a.getTransitionSpeed(h);d&&1>=d&&(h*=d);a.bzscroll=0<h?a.bzscroll?a.bzscroll.update(n,h): new D(l,n,h,0,1,0,1):!1;if(!a.timer){(f==a.page.maxh&&c>=a.page.maxh||k==a.page.maxw&&b>=a.page.maxw)&&a.checkContentSize();var p=1;a.cancelAnimationFrame=!1;a.timer=1;a.onscrollstart&&!a.scrollrunning&&a.onscrollstart.call(a,{type:"scrollstart",current:{x:k,y:f},request:{x:b,y:c},end:{x:a.newscrollx,y:a.newscrolly},speed:h});e();(f==a.page.maxh&&c>=f||k==a.page.maxw&&b>=k)&&a.checkContentSize();a.noticeCursor()}},this.cancelScroll=function(){a.timer&&w(a.timer);a.timer=0;a.bzscroll=!1;a.scrollrunning= !1;return a}):(this.doScrollLeft=function(b,c){var d=a.getScrollTop();a.doScrollPos(b,d,c)},this.doScrollTop=function(b,c){var d=a.getScrollLeft();a.doScrollPos(d,b,c)},this.doScrollPos=function(b,c,d){var e=b>a.page.maxw?a.page.maxw:b;0>e&&(e=0);var f=c>a.page.maxh?a.page.maxh:c;0>f&&(f=0);a.synched("scroll",function(){a.setScrollTop(f);a.setScrollLeft(e)})},this.cancelScroll=function(){});this.doScrollBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.y-b)*a.scrollratio.y):(a.timer?a.newscrolly: a.getScrollTop(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.h/2);d<-e?d=-e:d>a.page.maxh+e&&(d=a.page.maxh+e)}a.cursorfreezed=!1;e=a.getScrollTop(!0);if(0>d&&0>=e)return a.noticeCursor();if(d>a.page.maxh&&e>=a.page.maxh)return a.checkContentSize(),a.noticeCursor();a.doScrollTop(d)};this.doScrollLeftBy=function(b,c){var d=0,d=c?Math.floor((a.scroll.x-b)*a.scrollratio.x):(a.timer?a.newscrollx:a.getScrollLeft(!0))-b;if(a.bouncescroll){var e=Math.round(a.view.w/2);d<-e?d=-e:d>a.page.maxw+e&&(d=a.page.maxw+ e)}a.cursorfreezed=!1;e=a.getScrollLeft(!0);if(0>d&&0>=e||d>a.page.maxw&&e>=a.page.maxw)return a.noticeCursor();a.doScrollLeft(d)};this.doScrollTo=function(b,c){a.cursorfreezed=!1;a.doScrollTop(b)};this.checkContentSize=function(){var b=a.getContentSize();b.h==a.page.h&&b.w==a.page.w||a.resize(!1,b)};a.onscroll=function(b){a.rail.drag||a.cursorfreezed||a.synched("scroll",function(){a.scroll.y=Math.round(a.getScrollTop()*(1/a.scrollratio.y));a.railh&&(a.scroll.x=Math.round(a.getScrollLeft()*(1/a.scrollratio.x))); a.noticeCursor()})};a.bind(a.docscroll,"scroll",a.onscroll);this.doZoomIn=function(b){if(!a.zoomactive){a.zoomactive=!0;a.zoomrestore={style:{}};var c="position top left zIndex backgroundColor marginTop marginBottom marginLeft marginRight".split(" "),d=a.win[0].style,k;for(k in c){var h=c[k];a.zoomrestore.style[h]=void 0!==d[h]?d[h]:""}a.zoomrestore.style.width=a.win.css("width");a.zoomrestore.style.height=a.win.css("height");a.zoomrestore.padding={w:a.win.outerWidth()-a.win.width(),h:a.win.outerHeight()- a.win.height()};e.isios4&&(a.zoomrestore.scrollTop=f(window).scrollTop(),f(window).scrollTop(0));a.win.css({position:e.isios4?"absolute":"fixed",top:0,left:0,zIndex:A+100,margin:0});c=a.win.css("backgroundColor");(""==c||/transparent|rgba\(0, 0, 0, 0\)|rgba\(0,0,0,0\)/.test(c))&&a.win.css("backgroundColor","#fff");a.rail.css({zIndex:A+101});a.zoom.css({zIndex:A+102});a.zoom.css("backgroundPosition","0px -18px");a.resizeZoom();a.onzoomin&&a.onzoomin.call(a);return a.cancelEvent(b)}};this.doZoomOut= function(b){if(a.zoomactive)return a.zoomactive=!1,a.win.css("margin",""),a.win.css(a.zoomrestore.style),e.isios4&&f(window).scrollTop(a.zoomrestore.scrollTop),a.rail.css({"z-index":a.zindex}),a.zoom.css({"z-index":a.zindex}),a.zoomrestore=!1,a.zoom.css("backgroundPosition","0px 0px"),a.onResize(),a.onzoomout&&a.onzoomout.call(a),a.cancelEvent(b)};this.doZoom=function(b){return a.zoomactive?a.doZoomOut(b):a.doZoomIn(b)};this.resizeZoom=function(){if(a.zoomactive){var b=a.getScrollTop();a.win.css({width:f(window).width()- a.zoomrestore.padding.w+"px",height:f(window).height()-a.zoomrestore.padding.h+"px"});a.onResize();a.setScrollTop(Math.min(a.page.maxh,b))}};this.init();f.nicescroll.push(this)},M=function(f){var c=this;this.nc=f;this.steptime=this.lasttime=this.speedy=this.speedx=this.lasty=this.lastx=0;this.snapy=this.snapx=!1;this.demuly=this.demulx=0;this.lastscrolly=this.lastscrollx=-1;this.timer=this.chky=this.chkx=0;this.time=function(){return+new Date};this.reset=function(f,h){c.stop();var d=c.time();c.steptime= 0;c.lasttime=d;c.speedx=0;c.speedy=0;c.lastx=f;c.lasty=h;c.lastscrollx=-1;c.lastscrolly=-1};this.update=function(f,h){var d=c.time();c.steptime=d-c.lasttime;c.lasttime=d;var d=h-c.lasty,q=f-c.lastx,t=c.nc.getScrollTop(),a=c.nc.getScrollLeft(),t=t+d,a=a+q;c.snapx=0>a||a>c.nc.page.maxw;c.snapy=0>t||t>c.nc.page.maxh;c.speedx=q;c.speedy=d;c.lastx=f;c.lasty=h};this.stop=function(){c.nc.unsynched("domomentum2d");c.timer&&clearTimeout(c.timer);c.timer=0;c.lastscrollx=-1;c.lastscrolly=-1};this.doSnapy=function(f, h){var d=!1;0>h?(h=0,d=!0):h>c.nc.page.maxh&&(h=c.nc.page.maxh,d=!0);0>f?(f=0,d=!0):f>c.nc.page.maxw&&(f=c.nc.page.maxw,d=!0);d?c.nc.doScrollPos(f,h,c.nc.opt.snapbackspeed):c.nc.triggerScrollEnd()};this.doMomentum=function(f){var h=c.time(),d=f?h+f:c.lasttime;f=c.nc.getScrollLeft();var q=c.nc.getScrollTop(),t=c.nc.page.maxh,a=c.nc.page.maxw;c.speedx=0<a?Math.min(60,c.speedx):0;c.speedy=0<t?Math.min(60,c.speedy):0;d=d&&60>=h-d;if(0>q||q>t||0>f||f>a)d=!1;f=c.speedx&&d?c.speedx:!1;if(c.speedy&&d&&c.speedy|| f){var r=Math.max(16,c.steptime);50<r&&(f=r/50,c.speedx*=f,c.speedy*=f,r=50);c.demulxy=0;c.lastscrollx=c.nc.getScrollLeft();c.chkx=c.lastscrollx;c.lastscrolly=c.nc.getScrollTop();c.chky=c.lastscrolly;var p=c.lastscrollx,e=c.lastscrolly,v=function(){var d=600<c.time()-h?.04:.02;c.speedx&&(p=Math.floor(c.lastscrollx-c.speedx*(1-c.demulxy)),c.lastscrollx=p,0>p||p>a)&&(d=.1);c.speedy&&(e=Math.floor(c.lastscrolly-c.speedy*(1-c.demulxy)),c.lastscrolly=e,0>e||e>t)&&(d=.1);c.demulxy=Math.min(1,c.demulxy+ d);c.nc.synched("domomentum2d",function(){c.speedx&&(c.nc.getScrollLeft(),c.chkx=p,c.nc.setScrollLeft(p));c.speedy&&(c.nc.getScrollTop(),c.chky=e,c.nc.setScrollTop(e));c.timer||(c.nc.hideCursor(),c.doSnapy(p,e))});1>c.demulxy?c.timer=setTimeout(v,r):(c.stop(),c.nc.hideCursor(),c.doSnapy(p,e))};v()}else c.doSnapy(c.nc.getScrollLeft(),c.nc.getScrollTop())}},y=f.fn.scrollTop;f.cssHooks.pageYOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll?c.getScrollTop():y.call(h)},set:function(h, c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollTop(parseInt(c)):y.call(h,c);return this}};f.fn.scrollTop=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollTop():y.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollTop(parseInt(h)):y.call(f(this),h)})};var z=f.fn.scrollLeft;f.cssHooks.pageXOffset={get:function(h,c,k){return(c=f.data(h,"__nicescroll")||!1)&&c.ishwscroll? c.getScrollLeft():z.call(h)},set:function(h,c){var k=f.data(h,"__nicescroll")||!1;k&&k.ishwscroll?k.setScrollLeft(parseInt(c)):z.call(h,c);return this}};f.fn.scrollLeft=function(h){if(void 0===h){var c=this[0]?f.data(this[0],"__nicescroll")||!1:!1;return c&&c.ishwscroll?c.getScrollLeft():z.call(this)}return this.each(function(){var c=f.data(this,"__nicescroll")||!1;c&&c.ishwscroll?c.setScrollLeft(parseInt(h)):z.call(f(this),h)})};var E=function(h){var c=this;this.length=0;this.name="nicescrollarray"; this.each=function(d){f.each(c,d);return c};this.push=function(d){c[c.length]=d;c.length++};this.eq=function(d){return c[d]};if(h)for(var k=0;k<h.length;k++){var l=f.data(h[k],"__nicescroll")||!1;l&&(this[this.length]=l,this.length++)}return this};(function(f,c,k){for(var l=0;l<c.length;l++)k(f,c[l])})(E.prototype,"show hide toggle onResize resize remove stop doScrollPos".split(" "),function(f,c){f[c]=function(){var f=arguments;return this.each(function(){this[c].apply(this,f)})}});f.fn.getNiceScroll= function(h){return void 0===h?new E(this):this[h]&&f.data(this[h],"__nicescroll")||!1};f.expr[":"].nicescroll=function(h){return void 0!==f.data(h,"__nicescroll")};f.fn.niceScroll=function(h,c){void 0!==c||"object"!=typeof h||"jquery"in h||(c=h,h=!1);c=f.extend({},c);var k=new E;void 0===c&&(c={});h&&(c.doc=f(h),c.win=f(this));var l=!("doc"in c);l||"win"in c||(c.win=f(this));this.each(function(){var d=f(this).data("__nicescroll")||!1;d||(c.doc=l?f(this):c.doc,d=new S(c,f(this)),f(this).data("__nicescroll", d));k.push(d)});return 1==k.length?k[0]:k};window.NiceScroll={getjQuery:function(){return f}};f.nicescroll||(f.nicescroll=new E,f.nicescroll.options=K)}); /*! * Bootstrap v3.1.1 (http://getbootstrap.com) * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ if (typeof jQuery === 'undefined') { throw new Error('Bootstrap\'s JavaScript requires jQuery') } /* ======================================================================== * Bootstrap: transition.js v3.1.1 * http://getbootstrap.com/javascript/#transitions * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/) // ============================================================ function transitionEnd() { var el = document.createElement('bootstrap') var transEndEventNames = { 'WebkitTransition' : 'webkitTransitionEnd', 'MozTransition' : 'transitionend', 'OTransition' : 'oTransitionEnd otransitionend', 'transition' : 'transitionend' } for (var name in transEndEventNames) { if (el.style[name] !== undefined) { return { end: transEndEventNames[name] } } } return false // explicit for ie8 ( ._.) } // http://blog.alexmaccaw.com/css-transitions $.fn.emulateTransitionEnd = function (duration) { var called = false, $el = this $(this).one($.support.transition.end, function () { called = true }) var callback = function () { if (!called) $($el).trigger($.support.transition.end) } setTimeout(callback, duration) return this } $(function () { $.support.transition = transitionEnd() }) }(jQuery); /* ======================================================================== * Bootstrap: alert.js v3.1.1 * http://getbootstrap.com/javascript/#alerts * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // ALERT CLASS DEFINITION // ====================== var dismiss = '[data-dismiss="alert"]' var Alert = function (el) { $(el).on('click', dismiss, this.close) } Alert.prototype.close = function (e) { var $this = $(this) var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7 } var $parent = $(selector) if (e) e.preventDefault() if (!$parent.length) { $parent = $this.hasClass('alert') ? $this : $this.parent() } $parent.trigger(e = $.Event('close.bs.alert')) if (e.isDefaultPrevented()) return $parent.removeClass('in') function removeElement() { $parent.trigger('closed.bs.alert').remove() } $.support.transition && $parent.hasClass('fade') ? $parent .one($.support.transition.end, removeElement) .emulateTransitionEnd(150) : removeElement() } // ALERT PLUGIN DEFINITION // ======================= var old = $.fn.alert $.fn.alert = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.alert') if (!data) $this.data('bs.alert', (data = new Alert(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.alert.Constructor = Alert // ALERT NO CONFLICT // ================= $.fn.alert.noConflict = function () { $.fn.alert = old return this } // ALERT DATA-API // ============== $(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close) }(jQuery); /* ======================================================================== * Bootstrap: button.js v3.1.1 * http://getbootstrap.com/javascript/#buttons * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // BUTTON PUBLIC CLASS DEFINITION // ============================== var Button = function (element, options) { this.$element = $(element) this.options = $.extend({}, Button.DEFAULTS, options) this.isLoading = false } Button.DEFAULTS = { loadingText: 'loading...' } Button.prototype.setState = function (state) { var d = 'disabled' var $el = this.$element var val = $el.is('input') ? 'val' : 'html' var data = $el.data() state = state + 'Text' if (!data.resetText) $el.data('resetText', $el[val]()) $el[val](data[state] || this.options[state]) // push to event loop to allow forms to submit setTimeout($.proxy(function () { if (state == 'loadingText') { this.isLoading = true $el.addClass(d).attr(d, d) } else if (this.isLoading) { this.isLoading = false $el.removeClass(d).removeAttr(d) } }, this), 0) } Button.prototype.toggle = function () { var changed = true var $parent = this.$element.closest('[data-toggle="buttons"]') if ($parent.length) { var $input = this.$element.find('input') if ($input.prop('type') == 'radio') { if ($input.prop('checked') && this.$element.hasClass('active')) changed = false else $parent.find('.active').removeClass('active') } if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change') } if (changed) this.$element.toggleClass('active') } // BUTTON PLUGIN DEFINITION // ======================== var old = $.fn.button $.fn.button = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.button') var options = typeof option == 'object' && option if (!data) $this.data('bs.button', (data = new Button(this, options))) if (option == 'toggle') data.toggle() else if (option) data.setState(option) }) } $.fn.button.Constructor = Button // BUTTON NO CONFLICT // ================== $.fn.button.noConflict = function () { $.fn.button = old return this } // BUTTON DATA-API // =============== $(document).on('click.bs.button.data-api', '[data-toggle^=button]', function (e) { var $btn = $(e.target) if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn') $btn.button('toggle') e.preventDefault() }) }(jQuery); /* ======================================================================== * Bootstrap: carousel.js v3.1.1 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // CAROUSEL CLASS DEFINITION // ========================= var Carousel = function (element, options) { this.$element = $(element) this.$indicators = this.$element.find('.carousel-indicators') this.options = options this.paused = this.sliding = this.interval = this.$active = this.$items = null this.options.pause == 'hover' && this.$element .on('mouseenter', $.proxy(this.pause, this)) .on('mouseleave', $.proxy(this.cycle, this)) } Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true } Carousel.prototype.cycle = function (e) { e || (this.paused = false) this.interval && clearInterval(this.interval) this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this } Carousel.prototype.getActiveIndex = function () { this.$active = this.$element.find('.item.active') this.$items = this.$active.parent().children() return this.$items.index(this.$active) } Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getActiveIndex() if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', $(this.$items[pos])) } Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || $active[type]() var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var fallback = type == 'next' ? 'first' : 'last' var that = this if (!$next.length) { if (!this.options.wrap) return $next = this.$element.find('.item')[fallback]() } if ($next.hasClass('active')) return this.sliding = false var e = $.Event('slide.bs.carousel', { relatedTarget: $next[0], direction: direction }) this.$element.trigger(e) if (e.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') this.$element.one('slid.bs.carousel', function () { var $nextIndicator = $(that.$indicators.children()[that.getActiveIndex()]) $nextIndicator && $nextIndicator.addClass('active') }) } if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one($.support.transition.end, function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger('slid.bs.carousel') }, 0) }) .emulateTransitionEnd($active.css('transition-duration').slice(0, -1) * 1000) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger('slid.bs.carousel') } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== var old = $.fn.carousel $.fn.carousel = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= $(document).on('click.bs.carousel.data-api', '[data-slide], [data-slide-to]', function (e) { var $this = $(this), href var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false $target.carousel(options) if (slideIndex = $this.attr('data-slide-to')) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() }) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) $carousel.carousel($carousel.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: collapse.js v3.1.1 * http://getbootstrap.com/javascript/#collapse * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // COLLAPSE PUBLIC CLASS DEFINITION // ================================ var Collapse = function (element, options) { this.$element = $(element) this.options = $.extend({}, Collapse.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Collapse.DEFAULTS = { toggle: true } Collapse.prototype.dimension = function () { var hasWidth = this.$element.hasClass('width') return hasWidth ? 'width' : 'height' } Collapse.prototype.show = function () { if (this.transitioning || this.$element.hasClass('in')) return var startEvent = $.Event('show.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var actives = this.$parent && this.$parent.find('> .panel > .in') if (actives && actives.length) { var hasData = actives.data('bs.collapse') if (hasData && hasData.transitioning) return actives.collapse('hide') hasData || actives.data('bs.collapse', null) } var dimension = this.dimension() this.$element .removeClass('collapse') .addClass('collapsing') [dimension](0) this.transitioning = 1 var complete = function () { this.$element .removeClass('collapsing') .addClass('collapse in') [dimension]('auto') this.transitioning = 0 this.$element.trigger('shown.bs.collapse') } if (!$.support.transition) return complete.call(this) var scrollSize = $.camelCase(['scroll', dimension].join('-')) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) [dimension](this.$element[0][scrollSize]) } Collapse.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('in')) return var startEvent = $.Event('hide.bs.collapse') this.$element.trigger(startEvent) if (startEvent.isDefaultPrevented()) return var dimension = this.dimension() this.$element [dimension](this.$element[dimension]()) [0].offsetHeight this.$element .addClass('collapsing') .removeClass('collapse') .removeClass('in') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.collapse') .removeClass('collapsing') .addClass('collapse') } if (!$.support.transition) return complete.call(this) this.$element [dimension](0) .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(350) } Collapse.prototype.toggle = function () { this[this.$element.hasClass('in') ? 'hide' : 'show']() } // COLLAPSE PLUGIN DEFINITION // ========================== var old = $.fn.collapse $.fn.collapse = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.collapse') var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.collapse', (data = new Collapse(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.collapse.Constructor = Collapse // COLLAPSE NO CONFLICT // ==================== $.fn.collapse.noConflict = function () { $.fn.collapse = old return this } // COLLAPSE DATA-API // ================= $(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7 var $target = $(target) var data = $target.data('bs.collapse') var option = data ? 'toggle' : $this.data() var parent = $this.attr('data-parent') var $parent = parent && $(parent) if (!data || !data.transitioning) { if ($parent) $parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed') $this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed') } $target.collapse(option) }) }(jQuery); /* ======================================================================== * Bootstrap: dropdown.js v3.1.1 * http://getbootstrap.com/javascript/#dropdowns * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // DROPDOWN CLASS DEFINITION // ========================= var backdrop = '.dropdown-backdrop' var toggle = '[data-toggle=dropdown]' var Dropdown = function (element) { $(element).on('click.bs.dropdown', this.toggle) } Dropdown.prototype.toggle = function (e) { var $this = $(this) if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') clearMenus() if (!isActive) { if ('ontouchstart' in document.documentElement && !$parent.closest('.navbar-nav').length) { // if mobile we use a backdrop because click events don't delegate $('<div class="dropdown-backdrop"/>').insertAfter($(this)).on('click', clearMenus) } var relatedTarget = { relatedTarget: this } $parent.trigger(e = $.Event('show.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent .toggleClass('open') .trigger('shown.bs.dropdown', relatedTarget) $this.focus() } return false } Dropdown.prototype.keydown = function (e) { if (!/(38|40|27)/.test(e.keyCode)) return var $this = $(this) e.preventDefault() e.stopPropagation() if ($this.is('.disabled, :disabled')) return var $parent = getParent($this) var isActive = $parent.hasClass('open') if (!isActive || (isActive && e.keyCode == 27)) { if (e.which == 27) $parent.find(toggle).focus() return $this.click() } var desc = ' li:not(.divider):visible a' var $items = $parent.find('[role=menu]' + desc + ', [role=listbox]' + desc) if (!$items.length) return var index = $items.index($items.filter(':focus')) if (e.keyCode == 38 && index > 0) index-- // up if (e.keyCode == 40 && index < $items.length - 1) index++ // down if (!~index) index = 0 $items.eq(index).focus() } function clearMenus(e) { $(backdrop).remove() $(toggle).each(function () { var $parent = getParent($(this)) var relatedTarget = { relatedTarget: this } if (!$parent.hasClass('open')) return $parent.trigger(e = $.Event('hide.bs.dropdown', relatedTarget)) if (e.isDefaultPrevented()) return $parent.removeClass('open').trigger('hidden.bs.dropdown', relatedTarget) }) } function getParent($this) { var selector = $this.attr('data-target') if (!selector) { selector = $this.attr('href') selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } var $parent = selector && $(selector) return $parent && $parent.length ? $parent : $this.parent() } // DROPDOWN PLUGIN DEFINITION // ========================== var old = $.fn.dropdown $.fn.dropdown = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.dropdown') if (!data) $this.data('bs.dropdown', (data = new Dropdown(this))) if (typeof option == 'string') data[option].call($this) }) } $.fn.dropdown.Constructor = Dropdown // DROPDOWN NO CONFLICT // ==================== $.fn.dropdown.noConflict = function () { $.fn.dropdown = old return this } // APPLY TO STANDARD DROPDOWN ELEMENTS // =================================== $(document) .on('click.bs.dropdown.data-api', clearMenus) .on('click.bs.dropdown.data-api', '.dropdown form', function (e) { e.stopPropagation() }) .on('click.bs.dropdown.data-api', toggle, Dropdown.prototype.toggle) .on('keydown.bs.dropdown.data-api', toggle + ', [role=menu], [role=listbox]', Dropdown.prototype.keydown) }(jQuery); /* ======================================================================== * Bootstrap: modal.js v3.1.1 * http://getbootstrap.com/javascript/#modals * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // MODAL CLASS DEFINITION // ====================== var Modal = function (element, options) { this.options = options this.$element = $(element) this.$backdrop = this.isShown = null if (this.options.remote) { this.$element .find('.modal-content') .load(this.options.remote, $.proxy(function () { this.$element.trigger('loaded.bs.modal') }, this)) } } Modal.DEFAULTS = { backdrop: true, keyboard: true, show: true } Modal.prototype.toggle = function (_relatedTarget) { return this[!this.isShown ? 'show' : 'hide'](_relatedTarget) } Modal.prototype.show = function (_relatedTarget) { var that = this var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget }) this.$element.trigger(e) if (this.isShown || e.isDefaultPrevented()) return this.isShown = true this.escape() this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this)) this.backdrop(function () { var transition = $.support.transition && that.$element.hasClass('fade') if (!that.$element.parent().length) { that.$element.appendTo(document.body) // don't move modals dom position } that.$element .show() .scrollTop(0) if (transition) { that.$element[0].offsetWidth // force reflow } that.$element .addClass('in') .attr('aria-hidden', false) that.enforceFocus() var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$element.find('.modal-dialog') // wait for modal to slide in .one($.support.transition.end, function () { that.$element.focus().trigger(e) }) .emulateTransitionEnd(300) : that.$element.focus().trigger(e) }) } Modal.prototype.hide = function (e) { if (e) e.preventDefault() e = $.Event('hide.bs.modal') this.$element.trigger(e) if (!this.isShown || e.isDefaultPrevented()) return this.isShown = false this.escape() $(document).off('focusin.bs.modal') this.$element .removeClass('in') .attr('aria-hidden', true) .off('click.dismiss.bs.modal') $.support.transition && this.$element.hasClass('fade') ? this.$element .one($.support.transition.end, $.proxy(this.hideModal, this)) .emulateTransitionEnd(300) : this.hideModal() } Modal.prototype.enforceFocus = function () { $(document) .off('focusin.bs.modal') // guard against infinite focus loop .on('focusin.bs.modal', $.proxy(function (e) { if (this.$element[0] !== e.target && !this.$element.has(e.target).length) { this.$element.focus() } }, this)) } Modal.prototype.escape = function () { if (this.isShown && this.options.keyboard) { this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) { e.which == 27 && this.hide() }, this)) } else if (!this.isShown) { this.$element.off('keyup.dismiss.bs.modal') } } Modal.prototype.hideModal = function () { var that = this this.$element.hide() this.backdrop(function () { that.removeBackdrop() that.$element.trigger('hidden.bs.modal') }) } Modal.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove() this.$backdrop = null } Modal.prototype.backdrop = function (callback) { var animate = this.$element.hasClass('fade') ? 'fade' : '' if (this.isShown && this.options.backdrop) { var doAnimate = $.support.transition && animate this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />') .appendTo(document.body) this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) { if (e.target !== e.currentTarget) return this.options.backdrop == 'static' ? this.$element[0].focus.call(this.$element[0]) : this.hide.call(this) }, this)) if (doAnimate) this.$backdrop[0].offsetWidth // force reflow this.$backdrop.addClass('in') if (!callback) return doAnimate ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass('in') $.support.transition && this.$element.hasClass('fade') ? this.$backdrop .one($.support.transition.end, callback) .emulateTransitionEnd(150) : callback() } else if (callback) { callback() } } // MODAL PLUGIN DEFINITION // ======================= var old = $.fn.modal $.fn.modal = function (option, _relatedTarget) { return this.each(function () { var $this = $(this) var data = $this.data('bs.modal') var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option) if (!data) $this.data('bs.modal', (data = new Modal(this, options))) if (typeof option == 'string') data[option](_relatedTarget) else if (options.show) data.show(_relatedTarget) }) } $.fn.modal.Constructor = Modal // MODAL NO CONFLICT // ================= $.fn.modal.noConflict = function () { $.fn.modal = old return this } // MODAL DATA-API // ============== $(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) { var $this = $(this) var href = $this.attr('href') var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7 var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data()) if ($this.is('a')) e.preventDefault() $target .modal(option, this) .one('hide', function () { $this.is(':visible') && $this.focus() }) }) $(document) .on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') }) .on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') }) }(jQuery); /* ======================================================================== * Bootstrap: tooltip.js v3.1.1 * http://getbootstrap.com/javascript/#tooltip * Inspired by the original jQuery.tipsy by Jason Frame * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) { this.type = this.options = this.enabled = this.timeout = this.hoverState = this.$element = null this.init('tooltip', element, options) } Tooltip.DEFAULTS = { animation: true, placement: 'top', selector: false, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: 'hover focus', title: '', delay: 0, html: false, container: false } Tooltip.prototype.init = function (type, element, options) { this.enabled = true this.type = type this.$element = $(element) this.options = this.getOptions(options) var triggers = this.options.trigger.split(' ') for (var i = triggers.length; i--;) { var trigger = triggers[i] if (trigger == 'click') { this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this)) } else if (trigger != 'manual') { var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin' var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout' this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this)) this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this)) } } this.options.selector ? (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) : this.fixTitle() } Tooltip.prototype.getDefaults = function () { return Tooltip.DEFAULTS } Tooltip.prototype.getOptions = function (options) { options = $.extend({}, this.getDefaults(), this.$element.data(), options) if (options.delay && typeof options.delay == 'number') { options.delay = { show: options.delay, hide: options.delay } } return options } Tooltip.prototype.getDelegateOptions = function () { var options = {} var defaults = this.getDefaults() this._options && $.each(this._options, function (key, value) { if (defaults[key] != value) options[key] = value }) return options } Tooltip.prototype.enter = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'in' if (!self.options.delay || !self.options.delay.show) return self.show() self.timeout = setTimeout(function () { if (self.hoverState == 'in') self.show() }, self.options.delay.show) } Tooltip.prototype.leave = function (obj) { var self = obj instanceof this.constructor ? obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) clearTimeout(self.timeout) self.hoverState = 'out' if (!self.options.delay || !self.options.delay.hide) return self.hide() self.timeout = setTimeout(function () { if (self.hoverState == 'out') self.hide() }, self.options.delay.hide) } Tooltip.prototype.show = function () { var e = $.Event('show.bs.' + this.type) if (this.hasContent() && this.enabled) { this.$element.trigger(e) if (e.isDefaultPrevented()) return var that = this; var $tip = this.tip() this.setContent() if (this.options.animation) $tip.addClass('fade') var placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement var autoToken = /\s?auto?\s?/i var autoPlace = autoToken.test(placement) if (autoPlace) placement = placement.replace(autoToken, '') || 'top' $tip .detach() .css({ top: 0, left: 0, display: 'block' }) .addClass(placement) this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element) var pos = this.getPosition() var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (autoPlace) { var $parent = this.$element.parent() var orgPlacement = placement var docScroll = document.documentElement.scrollTop || document.body.scrollTop var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth() var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight() var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' : placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' : placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' : placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' : placement $tip .removeClass(orgPlacement) .addClass(placement) } var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight) this.applyPlacement(calculatedOffset, placement) this.hoverState = null var complete = function() { that.$element.trigger('shown.bs.' + that.type) } $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() } } Tooltip.prototype.applyPlacement = function (offset, placement) { var replace var $tip = this.tip() var width = $tip[0].offsetWidth var height = $tip[0].offsetHeight // manually read margins because getBoundingClientRect includes difference var marginTop = parseInt($tip.css('margin-top'), 10) var marginLeft = parseInt($tip.css('margin-left'), 10) // we must check for NaN for ie 8/9 if (isNaN(marginTop)) marginTop = 0 if (isNaN(marginLeft)) marginLeft = 0 offset.top = offset.top + marginTop offset.left = offset.left + marginLeft // $.fn.offset doesn't round pixel values // so we use setOffset directly with our own function B-0 $.offset.setOffset($tip[0], $.extend({ using: function (props) { $tip.css({ top: Math.round(props.top), left: Math.round(props.left) }) } }, offset), 0) $tip.addClass('in') // check to see if placing tip in new offset caused the tip to resize itself var actualWidth = $tip[0].offsetWidth var actualHeight = $tip[0].offsetHeight if (placement == 'top' && actualHeight != height) { replace = true offset.top = offset.top + height - actualHeight } if (/bottom|top/.test(placement)) { var delta = 0 if (offset.left < 0) { delta = offset.left * -2 offset.left = 0 $tip.offset(offset) actualWidth = $tip[0].offsetWidth actualHeight = $tip[0].offsetHeight } this.replaceArrow(delta - width + actualWidth, actualWidth, 'left') } else { this.replaceArrow(actualHeight - height, actualHeight, 'top') } if (replace) $tip.offset(offset) } Tooltip.prototype.replaceArrow = function (delta, dimension, position) { this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + '%') : '') } Tooltip.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title) $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function () { var that = this var $tip = this.tip() var e = $.Event('hide.bs.' + this.type) function complete() { if (that.hoverState != 'in') $tip.detach() that.$element.trigger('hidden.bs.' + that.type) } this.$element.trigger(e) if (e.isDefaultPrevented()) return $tip.removeClass('in') $.support.transition && this.$tip.hasClass('fade') ? $tip .one($.support.transition.end, complete) .emulateTransitionEnd(150) : complete() this.hoverState = null return this } Tooltip.prototype.fixTitle = function () { var $e = this.$element if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') { $e.attr('data-original-title', $e.attr('title') || '').attr('title', '') } } Tooltip.prototype.hasContent = function () { return this.getTitle() } Tooltip.prototype.getPosition = function () { var el = this.$element[0] return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : { width: el.offsetWidth, height: el.offsetHeight }, this.$element.offset()) } Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) { return placement == 'bottom' ? { top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'top' ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } : placement == 'left' ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } : /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width } } Tooltip.prototype.getTitle = function () { var title var $e = this.$element var o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } Tooltip.prototype.tip = function () { return this.$tip = this.$tip || $(this.options.template) } Tooltip.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow') } Tooltip.prototype.validate = function () { if (!this.$element[0].parentNode) { this.hide() this.$element = null this.options = null } } Tooltip.prototype.enable = function () { this.enabled = true } Tooltip.prototype.disable = function () { this.enabled = false } Tooltip.prototype.toggleEnabled = function () { this.enabled = !this.enabled } Tooltip.prototype.toggle = function (e) { var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () { clearTimeout(this.timeout) this.hide().$element.off('.' + this.type).removeData('bs.' + this.type) } // TOOLTIP PLUGIN DEFINITION // ========================= var old = $.fn.tooltip $.fn.tooltip = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tooltip') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== $.fn.tooltip.noConflict = function () { $.fn.tooltip = old return this } }(jQuery); /* ======================================================================== * Bootstrap: popover.js v3.1.1 * http://getbootstrap.com/javascript/#popovers * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // POPOVER PUBLIC CLASS DEFINITION // =============================== var Popover = function (element, options) { this.init('popover', element, options) } if (!$.fn.tooltip) throw new Error('Popover requires tooltip.js') Popover.DEFAULTS = $.extend({}, $.fn.tooltip.Constructor.DEFAULTS, { placement: 'right', trigger: 'click', content: '', template: '<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }) // NOTE: POPOVER EXTENDS tooltip.js // ================================ Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype) Popover.prototype.constructor = Popover Popover.prototype.getDefaults = function () { return Popover.DEFAULTS } Popover.prototype.setContent = function () { var $tip = this.tip() var title = this.getTitle() var content = this.getContent() $tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title) $tip.find('.popover-content')[ // we use append for html objects to maintain js events this.options.html ? (typeof content == 'string' ? 'html' : 'append') : 'text' ](content) $tip.removeClass('fade top bottom left right in') // IE8 doesn't accept hiding via the `:empty` pseudo selector, we have to do // this manually by checking the contents. if (!$tip.find('.popover-title').html()) $tip.find('.popover-title').hide() } Popover.prototype.hasContent = function () { return this.getTitle() || this.getContent() } Popover.prototype.getContent = function () { var $e = this.$element var o = this.options return $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content) } Popover.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find('.arrow') } Popover.prototype.tip = function () { if (!this.$tip) this.$tip = $(this.options.template) return this.$tip } // POPOVER PLUGIN DEFINITION // ========================= var old = $.fn.popover $.fn.popover = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.popover') var options = typeof option == 'object' && option if (!data && option == 'destroy') return if (!data) $this.data('bs.popover', (data = new Popover(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.popover.Constructor = Popover // POPOVER NO CONFLICT // =================== $.fn.popover.noConflict = function () { $.fn.popover = old return this } }(jQuery); /* ======================================================================== * Bootstrap: scrollspy.js v3.1.1 * http://getbootstrap.com/javascript/#scrollspy * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // SCROLLSPY CLASS DEFINITION // ========================== function ScrollSpy(element, options) { var href var process = $.proxy(this.process, this) this.$element = $(element).is('body') ? $(window) : $(element) this.$body = $('body') this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process) this.options = $.extend({}, ScrollSpy.DEFAULTS, options) this.selector = (this.options.target || ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7 || '') + ' .nav li > a' this.offsets = $([]) this.targets = $([]) this.activeTarget = null this.refresh() this.process() } ScrollSpy.DEFAULTS = { offset: 10 } ScrollSpy.prototype.refresh = function () { var offsetMethod = this.$element[0] == window ? 'offset' : 'position' this.offsets = $([]) this.targets = $([]) var self = this var $targets = this.$body .find(this.selector) .map(function () { var $el = $(this) var href = $el.data('target') || $el.attr('href') var $href = /^#./.test(href) && $(href) return ($href && $href.length && $href.is(':visible') && [[ $href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href ]]) || null }) .sort(function (a, b) { return a[0] - b[0] }) .each(function () { self.offsets.push(this[0]) self.targets.push(this[1]) }) } ScrollSpy.prototype.process = function () { var scrollTop = this.$scrollElement.scrollTop() + this.options.offset var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight var maxScroll = scrollHeight - this.$scrollElement.height() var offsets = this.offsets var targets = this.targets var activeTarget = this.activeTarget var i if (scrollTop >= maxScroll) { return activeTarget != (i = targets.last()[0]) && this.activate(i) } if (activeTarget && scrollTop <= offsets[0]) { return activeTarget != (i = targets[0]) && this.activate(i) } for (i = offsets.length; i--;) { activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate( targets[i] ) } } ScrollSpy.prototype.activate = function (target) { this.activeTarget = target $(this.selector) .parentsUntil(this.options.target, '.active') .removeClass('active') var selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]' var active = $(selector) .parents('li') .addClass('active') if (active.parent('.dropdown-menu').length) { active = active .closest('li.dropdown') .addClass('active') } active.trigger('activate.bs.scrollspy') } // SCROLLSPY PLUGIN DEFINITION // =========================== var old = $.fn.scrollspy $.fn.scrollspy = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.scrollspy') var options = typeof option == 'object' && option if (!data) $this.data('bs.scrollspy', (data = new ScrollSpy(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.scrollspy.Constructor = ScrollSpy // SCROLLSPY NO CONFLICT // ===================== $.fn.scrollspy.noConflict = function () { $.fn.scrollspy = old return this } // SCROLLSPY DATA-API // ================== $(window).on('load', function () { $('[data-spy="scroll"]').each(function () { var $spy = $(this) $spy.scrollspy($spy.data()) }) }) }(jQuery); /* ======================================================================== * Bootstrap: tab.js v3.1.1 * http://getbootstrap.com/javascript/#tabs * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // TAB CLASS DEFINITION // ==================== var Tab = function (element) { this.element = $(element) } Tab.prototype.show = function () { var $this = this.element var $ul = $this.closest('ul:not(.dropdown-menu)') var selector = $this.data('target') if (!selector) { selector = $this.attr('href') selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7 } if ($this.parent('li').hasClass('active')) return var previous = $ul.find('.active:last a')[0] var e = $.Event('show.bs.tab', { relatedTarget: previous }) $this.trigger(e) if (e.isDefaultPrevented()) return var $target = $(selector) this.activate($this.parent('li'), $ul) this.activate($target, $target.parent(), function () { $this.trigger({ type: 'shown.bs.tab', relatedTarget: previous }) }) } Tab.prototype.activate = function (element, container, callback) { var $active = container.find('> .active') var transition = callback && $.support.transition && $active.hasClass('fade') function next() { $active .removeClass('active') .find('> .dropdown-menu > .active') .removeClass('active') element.addClass('active') if (transition) { element[0].offsetWidth // reflow for transition element.addClass('in') } else { element.removeClass('fade') } if (element.parent('.dropdown-menu')) { element.closest('li.dropdown').addClass('active') } callback && callback() } transition ? $active .one($.support.transition.end, next) .emulateTransitionEnd(150) : next() $active.removeClass('in') } // TAB PLUGIN DEFINITION // ===================== var old = $.fn.tab $.fn.tab = function ( option ) { return this.each(function () { var $this = $(this) var data = $this.data('bs.tab') if (!data) $this.data('bs.tab', (data = new Tab(this))) if (typeof option == 'string') data[option]() }) } $.fn.tab.Constructor = Tab // TAB NO CONFLICT // =============== $.fn.tab.noConflict = function () { $.fn.tab = old return this } // TAB DATA-API // ============ $(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.preventDefault() $(this).tab('show') }) }(jQuery); /* ======================================================================== * Bootstrap: affix.js v3.1.1 * http://getbootstrap.com/javascript/#affix * ======================================================================== * Copyright 2011-2014 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict'; // AFFIX CLASS DEFINITION // ====================== var Affix = function (element, options) { this.options = $.extend({}, Affix.DEFAULTS, options) this.$window = $(window) .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this)) .on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this)) this.$element = $(element) this.affixed = this.unpin = this.pinnedOffset = null this.checkPosition() } Affix.RESET = 'affix affix-top affix-bottom' Affix.DEFAULTS = { offset: 0 } Affix.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset this.$element.removeClass(Affix.RESET).addClass('affix') var scrollTop = this.$window.scrollTop() var position = this.$element.offset() return (this.pinnedOffset = position.top - scrollTop) } Affix.prototype.checkPositionWithEventLoop = function () { setTimeout($.proxy(this.checkPosition, this), 1) } Affix.prototype.checkPosition = function () { if (!this.$element.is(':visible')) return var scrollHeight = $(document).height() var scrollTop = this.$window.scrollTop() var position = this.$element.offset() var offset = this.options.offset var offsetTop = offset.top var offsetBottom = offset.bottom if (this.affixed == 'top') position.top += scrollTop if (typeof offset != 'object') offsetBottom = offsetTop = offset if (typeof offsetTop == 'function') offsetTop = offset.top(this.$element) if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element) var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false if (this.affixed === affix) return if (this.unpin) this.$element.css('top', '') var affixType = 'affix' + (affix ? '-' + affix : '') var e = $.Event(affixType + '.bs.affix') this.$element.trigger(e) if (e.isDefaultPrevented()) return this.affixed = affix this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null this.$element .removeClass(Affix.RESET) .addClass(affixType) .trigger($.Event(affixType.replace('affix', 'affixed'))) if (affix == 'bottom') { this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() }) } } // AFFIX PLUGIN DEFINITION // ======================= var old = $.fn.affix $.fn.affix = function (option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.affix') var options = typeof option == 'object' && option if (!data) $this.data('bs.affix', (data = new Affix(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.affix.Constructor = Affix // AFFIX NO CONFLICT // ================= $.fn.affix.noConflict = function () { $.fn.affix = old return this } // AFFIX DATA-API // ============== $(window).on('load', function () { $('[data-spy="affix"]').each(function () { var $spy = $(this) var data = $spy.data() data.offset = data.offset || {} if (data.offsetBottom) data.offset.bottom = data.offsetBottom if (data.offsetTop) data.offset.top = data.offsetTop $spy.affix(data) }) }) }(jQuery); /* ======================================================================== * Bootstrap: sidebar.js v0.1 * ======================================================================== * Copyright 2011-2014 Asyraf Abdul Rahman * Licensed under MIT * ======================================================================== */ +function ($) { 'use strict'; // SIDEBAR PUBLIC CLASS DEFINITION // ================================ var Sidebar = function (element, options) { this.$element = $(element) this.options = $.extend({}, Sidebar.DEFAULTS, options) this.transitioning = null if (this.options.parent) this.$parent = $(this.options.parent) if (this.options.toggle) this.toggle() } Sidebar.DEFAULTS = { toggle: true } Sidebar.prototype.show = function () { if (this.transitioning || this.$element.hasClass('sidebar-open')) return var startEvent = $.Event('show.bs.sidebar') this.$element.trigger(startEvent); if (startEvent.isDefaultPrevented()) return this.$element .addClass('sidebar-open') this.transitioning = 1 var complete = function () { this.$element this.transitioning = 0 this.$element.trigger('shown.bs.sidebar') } if(!$.support.transition) return complete.call(this) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(400) } Sidebar.prototype.hide = function () { if (this.transitioning || !this.$element.hasClass('sidebar-open')) return var startEvent = $.Event('hide.bs.sidebar') this.$element.trigger(startEvent) if(startEvent.isDefaultPrevented()) return this.$element .removeClass('sidebar-open') this.transitioning = 1 var complete = function () { this.transitioning = 0 this.$element .trigger('hidden.bs.sidebar') } if (!$.support.transition) return complete.call(this) this.$element .one($.support.transition.end, $.proxy(complete, this)) .emulateTransitionEnd(400) } Sidebar.prototype.toggle = function () { this[this.$element.hasClass('sidebar-open') ? 'hide' : 'show']() } var old = $.fn.sidebar $.fn.sidebar = function (option) { return this.each(function (){ var $this = $(this) var data = $this.data('bs.sidebar') var options = $.extend({}, Sidebar.DEFAULTS, $this.data(), typeof options == 'object' && option) if (!data && options.toggle && option == 'show') option = !option if (!data) $this.data('bs.sidebar', (data = new Sidebar(this, options))) if (typeof option == 'string') data[option]() }) } $.fn.sidebar.Constructor = Sidebar $.fn.sidebar.noConflict = function () { $.fn.sidebar = old return this } $(document).on('click.bs.sidebar.data-api', '[data-toggle="sidebar"]', function (e) { var $this = $(this), href var target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') var $target = $(target) var data = $target.data('bs.sidebar') var option = data ? 'toggle' : $this.data() $target.sidebar(option) }) $('html').on('click.bs.sidebar.autohide', function(event){ var $this = $(event.target); var isButtonOrSidebar = $this.is('.sidebar, [data-toggle="sidebar"]') || $this.parents('.sidebar, [data-toggle="sidebar"]').length; if (isButtonOrSidebar) { return; } else { var $target = $('.sidebar'); $target.each(function(i, trgt) { var $trgt = $(trgt); if($trgt.data('bs.sidebar') && $trgt.hasClass('sidebar-open')) { $trgt.sidebar('hide'); } }) } }); }(jQuery); /*! * Bootstrap Confirmation 2.1.3 * Copyright 2013 Nimit Suwannagate <ethaizone@hotmail.com> * Copyright 2015 Damien "Mistic" Sorel <http://www.strangeplanet.fr> * Licensed under the Apache License, Version 2.0 (the "License") */ !function(a){"use strict";function b(a){for(var b=window,c=a.split("."),d=c.pop(),e=0,f=c.length;f>e;e++)b=b[c[e]];return function(){b[d].call(this)}}if(!a.fn.popover)throw new Error("Confirmation requires popover.js");var c=function(b,c){this.init("confirmation",b,c);var d=this;this.options.selector||(this.$element.attr("href")&&(this.options.href=this.$element.attr("href"),this.$element.removeAttr("href"),this.$element.attr("target")&&(this.options.target=this.$element.attr("target"))),this.$element.on(d.options.trigger,function(a,b){b||(a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation())}),this.$element.on("confirmed.bs.confirmation",function(b){a(this).trigger(d.options.trigger,[!0])}),this.$element.on("show.bs.confirmation",function(b){d.options.singleton&&a(d.options._selector).not(a(this)).filter(function(){return void 0!==a(this).data("bs.confirmation")}).confirmation("hide")})),this.options._isDelegate||(this.eventBody=!1,this.uid=this.$element[0].id||this.getUID("group_"),this.$element.on("shown.bs.confirmation",function(b){if(d.options.popout&&!d.eventBody){a(this);d.eventBody=a("body").on("click.bs.confirmation."+d.uid,function(b){a(d.options._selector).is(b.target)||(a(d.options._selector).filter(function(){return void 0!==a(this).data("bs.confirmation")}).confirmation("hide"),a("body").off("click.bs."+d.uid),d.eventBody=!1)})}}))};c.DEFAULTS=a.extend({},a.fn.popover.Constructor.DEFAULTS,{placement:"top",title:"Are you sure?",html:!0,href:!1,popout:!1,singleton:!1,target:"_self",onConfirm:a.noop,onCancel:a.noop,btnOkClass:"btn-xs btn-primary",btnOkIcon:"glyphicon glyphicon-ok",btnOkLabel:"Yes",btnCancelClass:"btn-xs btn-default",btnCancelIcon:"glyphicon glyphicon-remove",btnCancelLabel:"No",template:'<div class="popover confirmation"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content text-center"><div class="btn-group"><a class="btn" data-apply="confirmation"></a><a class="btn" data-dismiss="confirmation"></a></div></div></div>'}),c.prototype=a.extend({},a.fn.popover.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.init=function(b,c,d){a.fn.popover.Constructor.prototype.init.call(this,b,c,d),this.options._isDelegate=!1,d.selector?this.options._selector=this._options._selector=d._root_selector+" "+d.selector:d._selector?(this.options._selector=d._selector,this.options._isDelegate=!0):this.options._selector=d._root_selector},c.prototype.setContent=function(){var b=this,c=this.tip(),d=this.options;c.find(".popover-title")[d.html?"html":"text"](this.getTitle()),c.find('[data-apply="confirmation"]').addClass(d.btnOkClass).html(d.btnOkLabel).prepend(a("<i></i>").addClass(d.btnOkIcon)," ").off("click").one("click",function(a){b.getOnConfirm.call(b).call(b.$element),b.$element.trigger("confirmed.bs.confirmation"),b.$element.confirmation("hide")}),d.href&&"#"!=d.href&&c.find('[data-apply="confirmation"]').attr({href:d.href,target:d.target}),c.find('[data-dismiss="confirmation"]').addClass(d.btnCancelClass).html(d.btnCancelLabel).prepend(a("<i></i>").addClass(d.btnCancelIcon)," ").off("click").one("click",function(a){b.getOnCancel.call(b).call(b.$element),b.$element.trigger("canceled.bs.confirmation"),b.$element.confirmation("hide")}),c.removeClass("fade top bottom left right in"),c.find(".popover-title").html()||c.find(".popover-title").hide()},c.prototype.getOnConfirm=function(){return this.$element.attr("data-on-confirm")?b(this.$element.attr("data-on-confirm")):this.options.onConfirm},c.prototype.getOnCancel=function(){return this.$element.attr("data-on-cancel")?b(this.$element.attr("data-on-cancel")):this.options.onCancel};var d=a.fn.confirmation;a.fn.confirmation=function(b){var d="object"==typeof b&&b||{};return d._root_selector=this.selector,this.each(function(){var e=a(this),f=e.data("bs.confirmation");(f||"destroy"!=b)&&(f||e.data("bs.confirmation",f=new c(this,d)),"string"==typeof b&&f[b]())})},a.fn.confirmation.Constructor=c,a.fn.confirmation.noConflict=function(){return a.fn.confirmation=d,this}}(jQuery);
import React, { PureComponent } from 'react'; import { connect } from 'dva'; import { Form, Input, Card, Modal, Row, Col, InputNumber } from 'antd'; import PicturesWall from '@/components/PicturesWall/PicturesWall'; @connect(({ assetDatamaint }) => ({ assetDatamaint, })) @Form.create() class PayEdit extends PureComponent { onOKClick = () => { const { form, onSubmit } = this.props; form.validateFieldsAndScroll((err, values) => { if (!err) { const formData = { ...values }; onSubmit(formData); } }); }; dispatch = action => { const { dispatch } = this.props; dispatch(action); }; render() { const { assetDatamaint: { submitting, formVisibleJF, formTitleJF, formDataJF }, form: { getFieldDecorator }, onCancel, } = this.props; const formItemLayout = { labelCol: { span: 6, }, wrapperCol: { span: 18, }, }; return ( <Modal title={formTitleJF} width={900} visible={formVisibleJF} maskClosable={false} confirmLoading={submitting} destroyOnClose onOk={this.onOKClick} onCancel={onCancel} style={{ top: 20 }} bodyStyle={{ maxHeight: 'calc( 100vh - 158px )', overflowY: 'auto' }} > <Card bordered={false}> <Form> <Row> <Col span={12}> <Form.Item {...formItemLayout} label="应缴金额(元)"> {getFieldDecorator('name', { initialValue: formDataJF.name, rules: [ { required: true, message: '请输入', }, ], })(<InputNumber placeholder="请输入" />)} </Form.Item> </Col> </Row> <Row> <Col span={12}> <Form.Item {...formItemLayout} label="实缴费(元)"> {getFieldDecorator('router', { initialValue: formDataJF.router, })(<InputNumber placeholder="请输入" />)} </Form.Item> </Col> <Col span={12}> <Form.Item {...formItemLayout} label="收据照片(转账记录截图)"> {getFieldDecorator('router', { initialValue: formDataJF.router, })(<PicturesWall num={9} listType="picture-card" />)} </Form.Item> </Col> </Row> <Row> <Col span={12}> <Form.Item {...formItemLayout} label="操作人"> {getFieldDecorator('router', { initialValue: formDataJF.router, })(<Input placeholder="请输入" />)} </Form.Item> </Col> <Col span={12}> <Form.Item {...formItemLayout} label="操作人联系方式"> {getFieldDecorator('router', { initialValue: formDataJF.router, })(<Input placeholder="请输入" />)} </Form.Item> </Col> </Row> </Form> </Card> </Modal> ); } } export default PayEdit;
import{r as i,h as e,H as s}from"./p-cc373a46.js";import{f as n,s as l,d as o}from"./p-b72f83c8.js";const t=class{constructor(s){i(this,s),this.fields='[{"id":1,"icon":"ph-folder","name":"Cats","children":[{"id":2,"icon":"ph-file","name":"Color cats","children":[{"id":3,"name":"Yellow cats"},{"id":4,"name":"Black cats"}]}]},{"id":5,"icon":"ph-folder","name":"Dogs","children":[{"id":6,"icon":"ph-file","name":"Color dogs","children":[{"id":7,"name":"Yellow dogs"},{"id":8,"name":"Black dogs"}]}]},{"id":9,"icon":"ph-folder","name":"Fishes","children":[{"id":10,"icon":"ph-file","name":"Color Fishes","children":[{"id":11,"name":"Yellow Fishes"},{"id":12,"name":"Black Fishes"}]}]}]',this.deserializedFields=[],this.changeOpen=({id:i,isOpen:e})=>{const s=n(this.deserializedFields,"id",i);l(this.deserializedFields,[...s,"isOpen"],!e),this.deserializedFields=this.deserializedFields.map(i=>i)},this.parseFields=(i,s=1)=>i.map(i=>e("div",{style:{display:"flex",cursor:"pointer",padding:"6px 0"}},e("div",{style:{display:"flex",alignItems:"baseline"},onClick:()=>this.changeOpen(i)},1===s&&i.children&&e("e-icon",{size:"24px",style:{marginRight:"33px"},icon:i.isOpen?"ph-minus-circle":"ph-plus-circle"})),e("div",{class:"branch "+(i.isOpen?"branch-open":"")},e("div",{style:{display:"flex",alignItems:"center",gap:"8px"},onClick:()=>this.changeOpen(i)},e("e-icon",{size:"24px",icon:i.icon}),i.name),e("div",{style:{marginLeft:"20px",display:"flex",flexDirection:"column"}},i.isOpen&&i.children&&this.parseFields(i.children,s+1)))))}componentWillLoad(){this.deserializedFields=o(this.fields)}parseTabsProp(i){i&&(this.deserializedFields=o(this.fields))}render(){return e(s,null,this.parseFields(this.deserializedFields))}static get watchers(){return{fields:["parseTabsProp"]}}};t.style=":host{display:block}.branch-open{position:relative}.branch-open:before{position:absolute;height:calc(100% - 28px);width:1px;content:'';left:12px;top:28px;background:var(--gray-300)}";export{t as e_fieldtree}
// Copyright JS Foundation and other contributors, http://js.foundation // // 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. var a; a = 1 ^ 3; assert(a == 2)
# Copyright (c) 2018 PaddlePaddle 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. def hash_name(varlist, pserver_endpoints): """ hash variable names to several endpoints. :param varlist: a list of Variables :return: a map of pserver endpoint -> varname """ def _hash_block(block_str, total): return hash(block_str) % total eplist = [] for var in varlist: server_id = _hash_block(var.name(), len(pserver_endpoints)) server_for_param = pserver_endpoints[server_id] eplist.append(server_for_param) return eplist def round_robin(varlist, pserver_endpoints): """ distribute variables to several endpoints. """ assert (len(varlist) > len(pserver_endpoints)) eplist = [] pserver_idx = 0 for var in varlist: server_for_param = pserver_endpoints[pserver_idx] eplist.append(server_for_param) pserver_idx += 1 if pserver_idx >= len(pserver_endpoints): pserver_idx = 0 return eplist
var searchData= [ ['a',['a',['../struct_s_u_plane3_d.html#ac20abbfe5c53954c051f39a67e360651',1,'SUPlane3D']]], ['alpha',['alpha',['../struct_s_u_color.html#a77a421e57b9fcb475804ac425b337e9b',1,'SUColor']]], ['alpha_5findex',['alpha_index',['../struct_s_u_color_order.html#a5f91ee410b31d46865bdf7fb0d6fa333',1,'SUColorOrder']]] ];
from typing import Union from functools import reduce from operator import mul import numpy as np from numpy.lib.stride_tricks import sliding_window_view from jesse.helpers import get_candle_source, slice_candles, same_length def pwma(candles: np.ndarray, period: int = 5, source_type: str = "close", sequential: bool = False) -> Union[ float, np.ndarray]: """ Pascals Weighted Moving Average (PWMA) :param candles: np.ndarray :param period: int - default: 5 :param source_type: str - default: "close" :param sequential: bool - default: False :return: float | np.ndarray """ # Accept normal array too. if len(candles.shape) == 1: source = candles else: candles = slice_candles(candles, sequential) source = get_candle_source(candles, source_type=source_type) triangle = pascals_triangle(n=period - 1) swv = sliding_window_view(source, window_shape=period) res = np.average(swv, weights=triangle, axis=-1) return same_length(candles, res) if sequential else res[-1] def pascals_triangle(n: int = None) -> np.ndarray: """Pascal's Triangle Returns a numpy array of the nth row of Pascal's Triangle. n=4 => triangle: [1, 4, 6, 4, 1] => weighted: [0.0625, 0.25, 0.375, 0.25, 0.0625] """ n = int(np.fabs(n)) if n is not None else 0 # Calculation triangle = np.array([combination(n=n, r=i) for i in range(0, n + 1)]) triangle_sum = np.sum(triangle) triangle_weights = triangle / triangle_sum return triangle_weights def combination(n, r) -> int: """https://stackoverflow.com/questions/4941753/is-there-a-math-ncr-function-in-python""" n = int(np.fabs(n)) r = int(np.fabs(r)) r = min(n, n - r) if r == 0: return 1 numerator = reduce(mul, range(n, n - r, -1), 1) denominator = reduce(mul, range(1, r + 1), 1) return numerator // denominator
/** * This source code is the intellectual property of Appcelerator, Inc. * Copyright (c) 2014-2015 Appcelerator, Inc. All Rights Reserved. * See the LICENSE file distributed with this package for * license restrictions and information about usage and distribution. */ var pkg = require('../package.json'), debug = require('debug')('appc:sdk'); /** * Appc object */ function AppC() { } exports = module.exports = AppC; var props = [ ['Auth', './auth'], ['Org', './org'], ['User', './user'], ['App', './app'], ['Notification', './notification'], ['Feed', './feed'], ['Cloud', './cloud'], ['Middleware', './middleware'], ['Analytics', './analytics'] ]; // lazy load modules props.forEach(function (tuple) { Object.defineProperty(AppC, tuple[0], { configurable: true, enumerable: true, // jscs:disable jsDoc get: function () { if (tuple.length > 2) { return tuple[2]; } return (tuple[2] = require(tuple[1])); }, // jscs:disable jsDoc set: function (v) { tuple[2] = v; } }); }); AppC.version = pkg.version; // set the default user agent which looks more like a browser user agent and provides // some basic platform information to aid in debugging var os = require('os'), fs = require('fs'), ua, lang = (process.env.LANG && ('; ' + process.env.LANG.split('.')[0])) || ''; /*jshint indent: false */ switch (process.platform) { case 'darwin': { ua = 'Macintosh; Intel Mac OS X ' + os.release().replace(/\./g, '_'); break; } case 'win': case 'win32': { ua = 'Windows ' + os.release(); if (process.arch === 'x64' || process.env.hasOwnProperty('PROCESSOR_ARCHITEW6432')) { ua += ' x64'; } break; } case 'linux': { ua = 'Linux ' + os.release(); break; } default: { ua = process.platform + ' ' + os.release(); break; } } AppC.userAgent = 'Appcelerator/' + pkg.version + ' (' + ua + lang + ') Version/1.1.1 Safari/0.0.0'; var DEFAULTS = {}; DEFAULTS.PRODUCTION = { baseurl: 'https://platform.appcelerator.com', registryurl: 'https://software.appcelerator.com', securityurl: 'https://security.appcelerator.com', pubsuburl: 'https://pubsub.appcelerator.com', webeventurl: 'https://webevent.appcelerator.com', cacheurl: 'https://cache.appcelerator.com', isProduction: true, supportUntrusted: false, secureCookies: true }; DEFAULTS.PREPRODUCTION = { baseurl: 'https://360-preprod.cloud.appctest.com', registryurl: 'https://software-preprod.cloud.appctest.com', securityurl: 'https://security-preprod.cloud.appctest.com', pubsuburl: 'https://pubsub-preprod.cloud.appctest.com', webeventurl: 'https://webevent-preprod.cloud.appctest.com', cacheurl: 'https://cache-preprod.cloud.appctest.com', isProduction: false, supportUntrusted: true, secureCookies: true }; DEFAULTS.PREPRODONPROD = { baseurl: DEFAULTS.PRODUCTION.baseurl, // TODO need to update the url with cNAME - DEVOPS-4987 registryurl: 'https://software-preprodonprod.appcelerator.com', securityurl: DEFAULTS.PRODUCTION.securityurl, pubsuburl: DEFAULTS.PRODUCTION.pubsuburl, webeventurl: DEFAULTS.PRODUCTION.webeventurl, cacheurl: DEFAULTS.PRODUCTION.cacheurl, isProduction: false, supportUntrusted: true, secureCookies: true }; DEFAULTS.PRODUCTION_EU = { baseurl: 'https://platform-eu.appcelerator.com', registryurl: 'https://software-eu.appcelerator.com', securityurl: 'https://security-eu.appcelerator.com', pubsuburl: 'https://pubsub.appcelerator.com', webeventurl: 'https://webevent.appcelerator.com', cacheurl: 'https://cache.appcelerator.com', isProduction: true, supportUntrusted: false, secureCookies: true }; DEFAULTS.PLATFORM_AXWAY = { baseurl: 'https://portal.cloudapp.axway.com', registryurl: 'https://marketplace.cloudapp.axway.com', securityurl: 'https://security.cloudapp.axway.com', pubsuburl: 'https://pubsub.appcelerator.com', webeventurl: 'https://webevent.appcelerator.com', cacheurl: 'https://cache.appcelerator.com', isProduction: true, supportUntrusted: false, secureCookies: true }; /** * set the base url to use production */ AppC.setProduction = function setProduction() { AppC.baseurl = DEFAULTS.PRODUCTION.baseurl; AppC.registryurl = DEFAULTS.PRODUCTION.registryurl; AppC.securityurl = DEFAULTS.PRODUCTION.securityurl; AppC.pubsuburl = DEFAULTS.PRODUCTION.pubsuburl; AppC.webeventurl = DEFAULTS.PRODUCTION.webeventurl; AppC.cacheurl = DEFAULTS.PRODUCTION.cacheurl; AppC.isProduction = DEFAULTS.PRODUCTION.isProduction; AppC.supportUntrusted = DEFAULTS.PRODUCTION.supportUntrusted; AppC.secureCookies = DEFAULTS.PRODUCTION.secureCookies; debug('set production to ' + AppC.baseurl); }; /** * set the base url to use development */ AppC.setPreproduction = function setPreproduction() { AppC.baseurl = DEFAULTS.PREPRODUCTION.baseurl; AppC.registryurl = DEFAULTS.PREPRODUCTION.registryurl; AppC.securityurl = DEFAULTS.PREPRODUCTION.securityurl; AppC.pubsuburl = DEFAULTS.PREPRODUCTION.pubsuburl; AppC.webeventurl = DEFAULTS.PREPRODUCTION.webeventurl; AppC.cacheurl = DEFAULTS.PREPRODUCTION.cacheurl; AppC.isProduction = DEFAULTS.PREPRODUCTION.isProduction; AppC.supportUntrusted = DEFAULTS.PREPRODUCTION.supportUntrusted; AppC.secureCookies = DEFAULTS.PREPRODUCTION.secureCookies; debug('set preproduction to ' + AppC.baseurl); }; AppC.setDevelopment = AppC.setPreproduction; /** * set the base url to use production */ AppC.setPreprodonprod = function setPreprodonprod() { AppC.baseurl = DEFAULTS.PREPRODONPROD.baseurl; AppC.registryurl = DEFAULTS.PREPRODONPROD.registryurl; AppC.securityurl = DEFAULTS.PREPRODONPROD.securityurl; AppC.pubsuburl = DEFAULTS.PREPRODONPROD.pubsuburl; AppC.webeventurl = DEFAULTS.PREPRODONPROD.webeventurl; AppC.cacheurl = DEFAULTS.PREPRODONPROD.cacheurl; AppC.isProduction = DEFAULTS.PREPRODONPROD.isProduction; AppC.supportUntrusted = DEFAULTS.PREPRODONPROD.supportUntrusted; AppC.secureCookies = DEFAULTS.PREPRODONPROD.secureCookies; debug('set preprodonprod to ' + AppC.baseurl); }; /** * set the base url to use production EU region */ AppC.setProductionEU = function setProductionEU() { AppC.baseurl = DEFAULTS.PRODUCTION_EU.baseurl; AppC.registryurl = DEFAULTS.PRODUCTION_EU.registryurl; AppC.securityurl = DEFAULTS.PRODUCTION_EU.securityurl; AppC.pubsuburl = DEFAULTS.PRODUCTION_EU.pubsuburl; AppC.webeventurl = DEFAULTS.PRODUCTION_EU.webeventurl; AppC.cacheurl = DEFAULTS.PRODUCTION_EU.cacheurl; AppC.isProduction = DEFAULTS.PRODUCTION_EU.isProduction; AppC.supportUntrusted = DEFAULTS.PRODUCTION_EU.supportUntrusted; AppC.secureCookies = DEFAULTS.PRODUCTION_EU.secureCookies; debug('set production EU to ' + AppC.baseurl); }; /** * set the base url to use platform axway region */ AppC.setPlatformAxway = function setPlatformAxway() { AppC.baseurl = DEFAULTS.PLATFORM_AXWAY.baseurl; AppC.registryurl = DEFAULTS.PLATFORM_AXWAY.registryurl; AppC.securityurl = DEFAULTS.PLATFORM_AXWAY.securityurl; AppC.pubsuburl = DEFAULTS.PLATFORM_AXWAY.pubsuburl; AppC.webeventurl = DEFAULTS.PLATFORM_AXWAY.webeventurl; AppC.cacheurl = DEFAULTS.PLATFORM_AXWAY.cacheurl; AppC.isProduction = DEFAULTS.PLATFORM_AXWAY.isProduction; AppC.supportUntrusted = DEFAULTS.PLATFORM_AXWAY.supportUntrusted; AppC.secureCookies = DEFAULTS.PLATFORM_AXWAY.secureCookies; debug('set platform axway to ' + AppC.baseurl); }; /** * set the base url to use local development */ AppC.setLocal = function setLocal() { AppC.setPreproduction(); AppC.baseurl = 'http://360-local.appcelerator.com:8443'; AppC.secureCookies = false; AppC.isProduction = false; debug('set local to ' + AppC.baseurl); }; /** * set a custom environment, use local config as defaults */ AppC.setEnvironment = function setEnvironment(opts) { opts = opts || {}; var base = DEFAULTS[isRunningInPreproduction() ? 'PREPRODUCTION' : 'PRODUCTION']; AppC.baseurl = (opts.baseurl || base.baseurl).trim(); AppC.registryurl = (opts.registry || base.registryurl).trim(); AppC.securityurl = (opts.security || base.securityurl).trim(); AppC.pubsuburl = (opts.pubsub || base.pubsuburl).trim(); AppC.webeventurl = (opts.webevent || base.webeventurl).trim(); AppC.cacheurl = (opts.cache || base.cacheurl).trim(); AppC.isProduction = typeof opts.isProduction !== 'undefined' ? opts.isProduction : base.isProduction; AppC.supportUntrusted = typeof opts.supportUntrusted !== 'undefined' ? opts.supportUntrusted : base.supportUntrusted; AppC.secureCookies = typeof opts.secureCookies !== 'undefined' ? opts.secureCookies : base.secureCookies; debug('set custom environment ' + JSON.stringify(opts) + ' to ' + AppC.baseurl); }; /** * Are we running in preproduction * @return {boolean} - true if yes */ function isRunningInPreproduction() { return process.env.NODE_ACS_URL && process.env.NODE_ACS_URL.indexOf('.appctest.com') > 0 || process.env.NODE_ENV === 'preproduction' || process.env.APPC_ENV === 'preproduction' || process.env.NODE_ENV === 'development' || process.env.APPC_ENV === 'development'; } /** * Are we running in a region * @return {boolean} - true if yes */ function isRunningInRegion() { return process.env.NODE_ENV === 'production-eu' || process.env.APPC_ENV === 'production-eu' || process.env.NODE_ENV === 'platform-axway' || process.env.APPC_ENV === 'platform-axway'; } /** * set the base url based on regions */ function setRegion() { if (process.env.NODE_ENV === 'production-eu' || process.env.APPC_ENV === 'production-eu') { AppC.setProductionEU(); } else if (process.env.NODE_ENV === 'platform-axway' || process.env.APPC_ENV === 'platform-axway') { AppC.setPlatformAxway(); } } // if running in pre-production, assume by default we want preproduction setup // if actually running locally, the logic assumes production though if (isRunningInPreproduction()) { AppC.setPreproduction(); } else if (isRunningInRegion()) { setRegion(); } else { AppC.setProduction(); } /** * Wrapper for existing functions which use createRequestObject. * This allows xauth token or session to be specified when creating an object */ function createRequestObject(auth, url) { if (typeof(auth) === 'object') { if (!auth.jar) { } // auth is a session return _createRequestObject(auth, url); } if (typeof(auth) === 'string') { //auth is a token return _createRequestObject(url, auth); } } /** * Create request object */ function _createRequestObject(session, url, authToken) { if (typeof(session) === 'object') { if (!session || !session.jar) { throw new Error('session is not valid'); } if (!url) { url = session; } } if (typeof(session) === 'string') { authToken = url; url = session; session = null; } var opts = { url: url, headers: { 'User-Agent': AppC.userAgent }, timeout: 30000, forever: true }; if (process.env.APPC_CONFIG_PROXY && process.env.APPC_CONFIG_PROXY !== 'undefined') { opts.proxy = process.env.APPC_CONFIG_PROXY; } if (process.env.APPC_CONFIG_CAFILE) { opts.ca = fs.readFileSync(process.env.APPC_CONFIG_CAFILE); } if (process.env.APPC_CONFIG_STRICTSSL === 'false') { opts.strictSSL = false; } // support self-signed certificates if (AppC.supportUntrusted) { opts.agent = false; opts.rejectUnauthorized = false; } if (authToken) { opts.headers['x-auth-token'] = authToken; } if (session) { opts.jar = session.jar; } debug('fetching', url, 'sid=', session && session.id, 'userAgent=', opts.headers['User-Agent']); return opts; } /** * create APIResponseHandler */ function createAPIResponseHandler(callback, mapper, path) { return function (err, resp, body) { debug('api response, err=%o, body=%o', err, body); if (err) { return callback(err); } try { var ct = resp.headers['content-type'], isJSON = ct && ct.indexOf('/json') > 0; body = typeof(body) === 'object' ? body : isJSON && JSON.parse(body) || body; if (!body.success) { debug('api body failed, was: %o', body); var description = typeof(body.description) === 'object' ? body.description.message : body.description || 'unexpected response from the server'; var error = new Error(description); error.success = false; error.description = description; error.code = body.code; error.internalCode = body.internalCode; typeof(body) === 'string' && (error.content = body); return callback(error); } if (mapper) { return mapper(body.result, callback, resp); } return callback(null, body.result || body, resp); } catch (E) { return callback(E, body, resp); } }; } AppC.createAPIResponseHandler = createAPIResponseHandler; /** * Create a request to the platform and return the request object * * @param {Object} session - session * @param {string} path - path * @param {string} method - method * @param {Function} callback - callback * @param {Function} mapper - mapper * @param {Object} json - json * @return {Object} - request object */ AppC.createRequest = function (session, path, method, callback, mapper, json) { if (typeof(method) === 'function') { json = mapper; mapper = callback; callback = method; method = 'get'; } if (typeof(mapper) === 'object') { json = mapper; mapper = null; } var responseHandler = createAPIResponseHandler(callback || function () {}, mapper || null, path); return _createRequest(session, path, method, responseHandler, json); }; /** * Create a request to the platform and return the request object. this time with a custom handler * * @param {Object} session - session * @param {string} path - path * @param {string} method - method * @param {string} responseHandler - responseHandler * @param {Object} json - json * @return {Object} - request object */ AppC.createRequestCustomResponseHandler = function (session, path, method, responseHandler, json) { if (typeof(method) === 'function') { json = responseHandler; responseHandler = method; method = 'get'; } return _createRequest(session, path, method, responseHandler, json); }; /** * Create a request * * @param {Object} session - session * @param {string} path - path * @param {string} method - method * @param {string} responseHandler - responseHandler * @param {Object} json - json * @return {Object} - request object */ function _createRequest(session, path, method, responseHandler, json) { var request = require('request'); try { if (path[0] === '/') { path = require('url').resolve(AppC.baseurl, path); } var obj = createRequestObject(session, path); if (json) { obj.json = json; } return request[method.toLowerCase()](obj, responseHandler); } catch (e) { responseHandler(e); // don't return the callback since it expects a request } }
const fs = global.nodemodule["fs-extra"]; module.exports.config = { name: "goibot", version: "1.0.1", hasPermssion: 0, credits: "....", description: "goibot", commandCategory: "Noprefix", usages: "noprefix", cooldowns: 5, }; module.exports.handleEvent = function({ api, event, args, Threads }) { var { threadID, messageID, reason } = event; const moment = require("moment-timezone"); const time = moment.tz("Asia/Ho_Chi_minh").format("HH:MM:ss L"); var idgr = `${event.threadID}`; var tl = ["chào bạn tôi là bot của Thắng", "bạn kêu tôi có việc gì?", "tôi yêu bạn vai lon", "Yêu em <3", "Hi, chào con vợ bé:3", "Vợ gọi có việc gì không?", "Sử dụng callad để liên lạc với admin!", "Em là bot cute nhất hành tinh", "Nói gì thế con lợn", "Em đây~~~~"]; var rand = tl[Math.floor(Math.random() * tl.length)] if ((event.body.toLowerCase() == "bot ngu")) { return api.sendMessage("Thành viên đã cố ý chửi bot, do đó đã vi phạm luật bot nên bot sẽ out và muốn add lại thì xin liên hệ qua admin qua Fb: Thắng để được hỗ trợ\nLink fb nè: https://www.facebook.com/thanghokngu1", threadID, () => api.removeUserFromGroup(api.getCurrentUserID(), threadID)); }; if ((event.body.toLowerCase() == "bot out")) { return api.sendMessage("Tạm biệt mng ><", threadID, () => api.removeUserFromGroup(api.getCurrentUserID(), threadID)); }; if ((event.body.toLowerCase() == "yêu bot") || (event.body.toLowerCase() == "yeu bot")) { return api.sendMessage("Hmm... Bot ngại lắm thôi yêu admin của bot nhé :))", threadID); }; if ((event.body.toLowerCase() == "bot ơi") || (event.body.toLowerCase() == "bot ơi")) { return api.sendMessage("Sủa lẹ, tao còn phải phục vụ các box khác nữa :)", threadID); }; if ((event.body.toLowerCase() == "chửi cc") || (event.body.toLowerCase() == "chui cc")) { return api.sendMessage("️Matday quá đi bạn à ><, cần tao chỉnh đốn mày lại ko :)", threadID); }; if ((event.body.toLowerCase() == "bot có yêu em không") || (event.body.toLowerCase() == "bot yeu em khong")) { return api.sendMessage("Hi, Bot yêu em hơn cả ny em cơ, yêu bot đi <3", threadID); }; if ((event.body.toLowerCase() == "bot cút")) { return api.sendMessage("À ừ vậy thôi tao đi cảm ơn bọn mày trong thời gian qua cùng tao vui vẻ....vậy thôi tao đi pp ☺😊", threadID, () => api.removeUserFromGroup(api.getCurrentUserID(), threadID)); }; if ((event.body.toLowerCase() == "bot lon")) { return api.sendMessage("Thành viên đã cố ý chửi bot, do đó đã vi phạm luật bot nên bot sẽ out và muốn add lại thì xin liên hệ qua admin qua Fb: Thắng để được hỗ trợ\nLink fb nè: https://www.facebook.com/thanghokngu1", threadID, () => api.removeUserFromGroup(api.getCurrentUserID(), threadID)); }; if ((event.body.toLowerCase() == "bot óc chó")) { return api.sendMessage("Thành viên đã cố ý chửi bot, do đó đã vi phạm luật bot nên bot sẽ out và muốn add lại thì xin liên hệ qua admin qua Fb:Thắng để được hỗ trợ\nLink fb nè: https://www.facebook.com/thanghokngu1", threadID, () => api.removeUserFromGroup(api.getCurrentUserID(), threadID)); }; if ((event.body.toLowerCase() == "bot chó") || (event.body.toLowerCase() == "bot chó")) { return api.sendMessage("Chó nào vừa nói xấu tao đấy, muốn chết hả😠", threadID); }; if ((event.body.toLowerCase() == "đmm bot") || (event.body.toLowerCase() == "dmm bot")) { return api.sendMessage("Bất hiếu cha sinh mẹ đẻ mà mày nói thế là hỏng người rồi", threadID); }; if ((event.body.toLowerCase() == "chửi cmm") || (event.body.toLowerCase() == "chui cmm")) { return api.sendMessage("Bất hiếu cha sinh mẹ đẻ mà mày nói thế là hỏng người rồi", threadID); }; if ((event.body.toLowerCase() == "@Vũ Thắng") || (event.body.toLowerCase() == "@Vũ Thắng")) { return api.sendMessage("Ai kêu chủ tao đấy, mà làm ơn đừng tag anh ấy mà hãy liên hệ qua Fb: https://www.facebook.com/profile.php?id=100029848123405 ", threadID); }; if ((event.body.toLowerCase() == "hi") || (event.body.toLowerCase() == "hi")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hí") || (event.body.toLowerCase() == "hi")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "chào") || (event.body.toLowerCase() == "chào")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hi mn") || (event.body.toLowerCase() == "hi mn")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hi mng") || (event.body.toLowerCase() == "hi mng")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hello") || (event.body.toLowerCase() == "hello")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "bsvv nha mng") || (event.body.toLowerCase() == "bsvv nha mng")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "bsvv nha mn") || (event.body.toLowerCase() == "bsvv nha mn")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "btvv nha mng") || (event.body.toLowerCase() == "btvv nha mng")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hí ae") || (event.body.toLowerCase() == "hi ae")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "hiii") || (event.body.toLowerCase() == "hiii")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "btvv nha mn") || (event.body.toLowerCase() == "btvv nha mn")) { return api.sendMessage("Chào bạn yêu dấu, chúc bạn một ngày mới tốt lành ❤️", threadID); }; if ((event.body.toLowerCase() == "chào cậu") || (event.body.toLowerCase() == "chao cau")) { return api.sendMessage("Hí chào bạn <3", threadID); }; if ((event.body.toLowerCase() == "tt đi mng") || (event.body.toLowerCase() == "tt đi mng")) { return api.sendMessage("️1 là tương tác, 2 là ăn kick :))))", threadID); }; if ((event.body.toLowerCase() == "tt đi nào mng") || (event.body.toLowerCase() == "tt di nao mng")) { return api.sendMessage("️1 là tương tác, 2 là ăn kick :))))", threadID); }; if ((event.body.toLowerCase() == "tt mng ơi") || (event.body.toLowerCase() == "tt mng oi")) { return api.sendMessage("️1 là tương tác, 2 là ăn kick :))))", threadID); }; if ((event.body.toLowerCase() == "nn nha mng") || (event.body.toLowerCase() == "nn nha mng")) { return api.sendMessage("️Ngủ ngon ạ <3 Chúc mọi người mơ siêu đẹp <3", threadID); }; if ((event.body.toLowerCase() == "admin m là ai v bot") || (event.body.toLowerCase() == "admin m la ai v bot")) { return api.sendMessage("️Admin tao tên Thắng có gì dùng lệnh /admin list hoặc /info để biết thêm chi tiết", threadID); }; if ((event.body.toLowerCase() == "admin m là ai vậy bot") || (event.body.toLowerCase() == "admin m la ai vậy bot")) { return api.sendMessage("️Admin tao tên Thắng có gì dùng lệnh /admin list hoặc /info để biết thêm chi tiết", threadID); }; if ((event.body.toLowerCase() == "tt đi mn") || (event.body.toLowerCase() == "tt đi mn")) { return api.sendMessage("️1 là tương tác, 2 là ăn kick :))))", threadID); }; if ((event.body.toLowerCase() == "flop quá") || (event.body.toLowerCase() == "flop qua")) { return api.sendMessage("️1 là tương tác, 2 là ăn kick :))))", threadID); }; if ((event.body.toLowerCase() == "clmm bot") || (event.body.toLowerCase() == "clmm bot")) { return api.sendMessage("️Chửi gì đấy con dog :) bố mmày nhịn mày lâu lắm rồi đấy nhá", threadID); }; if ((event.body.toLowerCase() == "bot cc") || (event.body.toLowerCase() == "bot cc")) { return api.sendMessage("️Chửi gì đấy con dog :) bố mmày nhịn mày lâu lắm rồi đấy nhá", threadID); }; if ((event.body.toLowerCase() == "cc bot") || (event.body.toLowerCase() == "cc bot")) { return api.sendMessage("️Chửi gì đấy con dog :) bố mmày nhịn mày lâu lắm rồi đấy nhá", threadID); }; if ((event.body.toLowerCase() == "bot dthw quá") || (event.body.toLowerCase() == "bot dthw qua")) { return api.sendMessage("️dạ quá khen ạ hihi :>", threadID); }; if ((event.body.toLowerCase() == "đm bot") || (event.body.toLowerCase() == "dm bot")) { return api.sendMessage("️Chửi cc gì đấy sủa lại bố mày nghe nào :) nít ranh mà cứ thích sồn :)", threadID); }; if ((event.body.toLowerCase() == "ko ai thương t hết") || (event.body.toLowerCase() == "ko ai thuong t het")) { return api.sendMessage("️Thôi ngoan nào bot thương bạn mà <3 <3 ", threadID); }; if ((event.body.toLowerCase() == "bot có yêu admin bot không") || (event.body.toLowerCase() == "bot co yeu admin bot khong")) { return api.sendMessage("Có, yêu anh ấy nhất đừng hòng cướp của tôi", threadID); }; if ((event.body.toLowerCase() == "bot có người yêu chưa") || (event.body.toLowerCase() == "bot co nguoi yeu chua")) { return api.sendMessage("Rồi ạ, là cậu đấy <3", threadID); }; if ((event.body.toLowerCase() == "bot im đi") || (event.body.toLowerCase() == "bot im di")) { return api.sendMessage("Im cc :))) m bớt sủa lại hộ tao, nưng hay gì bảo t im :>>", threadID); }; if ((event.body.toLowerCase() == "bot cút đi") || (event.body.toLowerCase() == "bot cut di")) { return api.sendMessage("Mày cút rồi bố mày cút, ko khiến mày lên tiếng :))))", threadID); }; if ((event.body.toLowerCase() == "bot chửi cái lon gì") || (event.body.toLowerCase() == "bot chui cai lon gi")) { return api.sendMessage("Chửi mày đấy, nhục vãi hahaha :>>, còn hỏi", threadID); }; if ((event.body.toLowerCase() == "bot có buồn ko") || (event.body.toLowerCase() == "bot co buon ko")) { return api.sendMessage("Có mọi người sao bé buồn đc <3 yêu lắm <3", threadID); }; if ((event.body.toLowerCase() == "bot có yêu t ko") || (event.body.toLowerCase() == "bot co yeu t ko")) { return api.sendMessage("Dạ có yêu cậu và mọi người nhiều lắm", threadID); }; if ((event.body.toLowerCase() == "bot đi ngủ đi") || (event.body.toLowerCase() == "bot di ngu di")) { return api.sendMessage("Tớ là bot, cậu là người nên cần đi ngủ nè <3", threadID); }; if ((event.body.toLowerCase() == "bot ăn cơm chưa") || (event.body.toLowerCase() == "bot an com chua")) { return api.sendMessage("Mình nhìn cậu ăn là thấy no rồi <3", threadID); }; if ((event.body.toLowerCase() == "bot có thương tui ko") || (event.body.toLowerCase() == "bot co thuong tui ko")) { return api.sendMessage("Có <3", threadID); }; if ((event.body.toLowerCase() == "bot có thương t ko") || (event.body.toLowerCase() == "bot co thuong t ko")) { return api.sendMessage("Có <3", threadID); }; if ((event.body.toLowerCase() == "bot có link fb của admin ko") || (event.body.toLowerCase() == "bot co link fb của admin ko")) { return api.sendMessage("Dĩ nhiên rồi có gì liên hệ anh ấy nha <3\nLink fb nè: https://www.facebook.com/thanghokngu1", threadID); }; if ((event.body.toLowerCase() == "bot làm thơ đi") || (event.body.toLowerCase() == "bot lam tho di")) { return api.sendMessage("Yêu cậu như một cực hình\nNhấp lên nhấp xuống hai mình cùng rên", threadID); }; if ((event.body.toLowerCase() == "cc") || (event.body.toLowerCase() == "cc")) { return api.sendMessage("À ý mày bảo mày là chó á hả sủa đi tao nghe :)", threadID); }; if (event.body.indexOf("bot") == 0 || (event.body.indexOf("Bot") == 0)) { var msg = { body: rand } return api.sendMessage(msg, threadID, messageID); }; } module.exports.run = function({ api, event, client, __GLOBAL }) { }
$(function(){ $(".header_box").load("header.html",function(){ main(); navText("首页"); }); $(".footer").load("footer.html"); carousel();//图片轮播 }) //banner图片轮播 function carousel(){ var number=$(".banner ul li").size()-1;//图片的数量 var cur=0;//当前显示的图片 var timer=0;//定时器 //下一个 function slideNext(){ if(cur<number){ $(".banner ul li").eq(cur).css({'z-index':10}).stop().fadeOut(); $(".banner ul li").eq(cur+1).css({'z-index':20}).stop().fadeIn(); $(".indicator a").removeClass().eq(cur+1).addClass("cur"); cur+=1; }else{ $(".banner ul li").eq(cur).css({'z-index':10}).stop().fadeOut(); $(".banner ul li").eq(0).css({'z-index':20}).stop().fadeIn(); $(".indicator a").removeClass().eq(0).addClass("cur"); cur=0; } } //上一个 function slidePrev(){ if(cur>0){ $(".banner ul li").eq(cur).css({'z-index':10}).stop().fadeOut(); $(".banner ul li").eq(cur-1).css({'z-index':20}).stop().fadeIn(); $(".indicator a").removeClass().eq(cur-1).addClass("cur"); cur-=1; }else{ $(".banner ul li").eq(cur).css({'z-index':10}).stop().fadeOut(); $(".banner ul li").eq(number).css({'z-index':20}).stop().fadeIn(); $(".indicator a").removeClass().eq(number).addClass("cur"); cur=number; } } timer=setInterval(slideNext,3000); //当鼠标移入banner时,清除定时器 $(".banner").mouseover(function(){ clearInterval(timer); }); $(".banner").mouseout(function(){ timer=setInterval(slideNext,3000) }); //上一个、下一个 $(".banner .prev").click(function(){ slidePrev(); }); $(".banner .next").click(function(){ slideNext(); }); //小圆点指示器 $(".indicator>a").mouseover(function(){ var now=$(this).index();//获取鼠标移入的是第几个a标记 $(".indicator>a").removeClass();//删除a标记中的class=cur $(this).addClass("cur");//为此a标记添加cur样式 $(".banner ul li").eq(cur).css({'z-index':10}).stop().fadeOut();//隐藏当前的图片 $(".banner ul li").eq(now).css({'z-index':20}).stop().fadeIn();//显示和a序列号一样的图片 cur=now;//为变量cur重新赋值,以便于再次启用定时器的时候,从当前显示的图片开始播放 }); } //banner图片轮播结束 //作业1:对图片轮播基础代码进行优化: // 1.jquery选择器元素查找存到变量中; // 2.上一个下一个函数整合; // 3.指示器中增加是否当前显示的项的判断; // 4.将图片轮播封装到对象中; // 5.其它 //作业2:首页产品部分,改成横向无缝滚动
""" Django settings for app project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '8bn8s(tr#56e$@1hro1d^6rc#w&l3u+!t0u@mhw^zn#jo!4uao' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'core', 'user', 'recipe', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'app.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'HOST': os.environ.get('DB_HOST'), 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } } # Password validation # https://docs.djangoproject.com/en/3.0/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/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = '/vol/web/media' STATIC_ROOT = '/vol/web/static' AUTH_USER_MODEL = 'core.User'
def outUImath(mathout): print("Your current balance is " + str(mathout)) input("Budget Badger will now close")
from datetime import timedelta from jirabuddy.bot import respond_to, every, PeriodicPlugin, RegexPlugin @respond_to("^sup$") def view_ticket(_, msg): msg.reply("SUP ;/") @respond_to("(^[0-9 ]*)\+([0-9 ]*)") def plus(_, msg, first: str, second: str): """Calculate a simple Plus equation""" if first.isdigit() and second.isdigit(): result = int(first) + int(second) msg.reply(f"that's easy!\n{result}") return msg.reply("oops! that's not a valid statement") @respond_to("Nice to meet you, I'm (.*)$") def self_intro(_, msg, who): """Say hi to the bot""" msg.reply(f"Hey {who}, it's a pleasure to meet you. I'm Colo, at your service!") @respond_to("remember (.*)") def remember(plugin: RegexPlugin, msg, what_to_remember): from datetime import datetime msg.reply("I will do my best to remember that!") remembered = plugin.restore("what_to_remember") # get specific value from plugin cache, or None if not cached when = plugin.restore("when") if remembered and when: msg.reply(f'last time, at {when}, you told me to remember: {remembered}') stored_dict = plugin.restore() # get all values from plugin cache as a new dict stored_dict["what_to_remember"] = what_to_remember stored_dict["when"] = datetime.utcnow() plugin.store(stored_dict) # update plugin cache with dict values @every(timedelta(minutes=10)) def nag(plugin: PeriodicPlugin, slack_message): """ will be running every 10 minutes slack_message: optional magic param to get slack client message dispatcher """ slack_message("@yneuman", "I will ping you every %s seconds" % plugin.frequency.total_seconds())
module.exports={title:"Trino",slug:"trino",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Trino</title><path d="M14.124 16.8529a.1615.1615 0 1 1 .1576.1614.1577.1577 0 0 1-.1576-.1614zm-5.607-.1576a.1614.1614 0 1 0 0 .3228.1614.1614 0 0 0 0-.3228zm10.1341-.6648v1.9869c-.031.5788-.524 1.0237-1.1029.9954h-.3843a5.0596 5.0596 0 0 1-1.1298 1.7178.3192.3192 0 0 0 0 .465l.2382.2191a.3036.3036 0 0 1 .0385.4304c-1.126 1.3835-2.9669 2.1521-5.0498 2.1521a6.575 6.575 0 0 1-4.8192-1.8985c-.0029-.0032-.0059-.0063-.0087-.0096a.6302.6302 0 0 1 .0548-.8896c.137-.1265.1371-.3462 0-.4727a4.944 4.944 0 0 1-1.126-1.714h-.3497c-.5797.0284-1.0737-.416-1.1068-.9954v-1.9869c.0351-.5779.5286-1.02 1.1068-.9915h.2728a5.7648 5.7648 0 0 1 2.0791-3.0936c-.4227-1.0991-1.1529-3.2551-1.226-5.0075C6.0229 4.4705 6.2189.078 7.8253.001c1.6064-.0768 1.3719 4.0275 1.0991 6.6946a32.732 32.732 0 0 0-.123 4.4503 6.994 6.994 0 0 1 2.4826-.4304 7.2414 7.2414 0 0 1 1.7371.2075c.2614-1.2682.8762-3.574 2.0292-5.1958 1.6717-2.352 3.4357-4.7808 4.6116-4.1006 1.176.6802-.3074 3.1398-1.3297 4.4272-1.0222 1.2874-2.7862 3.2089-3.3742 4.2274-.2114.3843-.4304.8032-.5956 1.1529a5.7375 5.7375 0 0 1 2.9169 3.6125h.073v-2.3058a.3075.3075 0 0 0-.1806-.2844.9148.9148 0 0 1-.5573-.8148 1.0184 1.0184 0 0 1 .9045-.9044c.5593-.0598 1.061.3452 1.1208.9044a.9187.9187 0 0 1-.5534.8148.3074.3074 0 0 0-.1691.2844v2.1522a.3113.3113 0 0 0 .1691.2805.9724.9724 0 0 1 .5648.857zm-1.0222-3.9737a.4345.4345 0 0 0 .4612-.4151.4151.4151 0 1 0-.4612.4151zm-.4227 3.4779c.0978.4794.148.9672.1498 1.4565v.3651h.4113a.3228.3228 0 0 0 .3228-.319v-1.0069c-.0111-.2967-.2733-.5256-.5688-.4957h-.3151zm-3.7278-4.481.611.2383a36.6046 36.6046 0 0 1 2.3828-3.8661c1.2874-1.7255 2.3365-3.5817 1.8715-3.8699-.465-.2883-1.6179 1.2297-2.7708 3.109a34.8978 34.8978 0 0 0-2.0945 4.3887zm-4.0544.6726.0154 1.3335c-.0039.2007.1881.3587.3843.3152a6.4317 6.4317 0 0 1 1.4565-.1653 5.995 5.995 0 0 1 1.4527.1729c.1956.0398.3853-.1153.3843-.3151v-1.3412a.319.319 0 0 0-.2421-.3113 6.664 6.664 0 0 0-1.6026-.1845 6.7093 6.7093 0 0 0-1.6025.1845.3188.3188 0 0 0-.246.3113zm1.7063 6.8637v.3843a.6878.6878 0 0 1-.4996.269c-.3074 0-.538-.4189-.538-.4189a.073.073 0 0 0-.1-.0307l-.0024.0013a.0693.0693 0 0 0-.0245.0947c.0115.0231.2806.4957.6649.4957a.7144.7144 0 0 0 .3843-.1268.3267.3267 0 0 1 .3612 0 .8332.8332 0 0 0 .4727.1345.957.957 0 0 0 .6572-.4803.0692.0692 0 0 0-.0269-.0961.0692.0692 0 0 0-.0999.0269c0 .0231-.2191.3843-.5419.4074a.8036.8036 0 0 1-.5765-.269v-.3843a.3154.3154 0 0 1 .1268-.2537c.196-.1499.415-.3958.415-.4919a.538.538 0 0 0-.5764-.4189c-.3766 0-.6533.2498-.6533.4573 0 .1345.2536.3382.4227.4612a.3226.3226 0 0 1 .1346.2383zM7.783 11.6455l.5765-.3074c-.0192-1.126-.0346-3.1436 0-4.5425.0538-2.0368.1537-4.5732-.5226-4.5463S6.6877 4.2285 6.949 7.007a33.0562 33.0562 0 0 0 .834 4.6385zm-3.305 5.3919a.319.319 0 0 0 .319.319h.3997a3.046 3.046 0 0 1 0-.3651 7.546 7.546 0 0 1 .1461-1.4565c-.0493.0002-.34.0005-.3866-.0021a.4881.4881 0 0 0-.4781.4979v1.0068zm.9184 1.4718a5.3254 5.3254 0 0 1-.123-.5573.3228.3228 0 0 0-.319-.2728h-.4957c.0007.0163-.0015.34.0009.355a.5188.5188 0 0 0 .5526.4827l.3842-.0076zm10.1265 2.917-.0884-.0807a.3229.3229 0 0 0-.3843-.0269 6.9823 6.9823 0 0 1-3.8046 1.0068 6.995 6.995 0 0 1-3.7932-1.0068.3228.3228 0 0 0-.3843.0269l-.0884.0807a.3154.3154 0 0 0 0 .4573 6.0305 6.0305 0 0 0 4.2927 1.5988 6.0453 6.0453 0 0 0 4.2889-1.5988.315.315 0 0 0-.0384-.4573zm1.4488-4.4158c0-2.4557-1.1529-4.3273-3.0245-5.2266-.2081-.1022-.4673.0594-.465.2921v1.3297a.3269.3269 0 0 0 .2037.296c1.7332.7109 2.9284 2.1866 2.9284 3.8776 0 2.2712-2.1559 3.8085-5.3419 3.8085-3.1859 0-5.3419-1.5411-5.3419-3.8085 0-1.691 1.1952-3.1667 2.9284-3.8776a.319.319 0 0 0 .2037-.296v-1.322c.0048-.2315-.2536-.3963-.4612-.2921-1.887.8839-3.0399 2.767-3.0399 5.2073 0 2.9899 2.2866 4.996 5.7108 4.996 3.4282.0001 5.6994-2.0098 5.6994-4.9844zm-8.6084-.538h-.0038a.5842.5842 0 1 0 .0038 0zm5.1614.5919c.0063.3226.2615.5789.584.5725a.5842.5842 0 1 0-.584-.5725zm4.5692.6225h-.4996a.3227.3227 0 0 0-.3151.2728c-.0346.173-.0768.3766-.1268.5573.0163.0007.3861-.0014.4012.0009a.5188.5188 0 0 0 .5366-.5004l.0037-.3306z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/trinodb/docs.trino.io/blob/653a46f6bdc64b5f67302dc9ab8a0c432ca25e70/352/_static/trino.svg",hex:"DD00A1",guidelines:void 0,license:void 0};
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'indent', 'ja', { indent: 'インデント', outdent: 'インデント解除' } );
export default function PreviewImage({visible, setVisible = () => {}, children}) { const close = () => { setVisible(false) } if (!visible) { return []; } return ( <div role="dialog" aria-modal="true" aria-labelledby="modal-headline" className="z-10 fixed w-full h-full top-0 left-0 flex items-center justify-center" > <div onClick={close} className="modal-overlay absolute w-full h-full bg-gray-900 opacity-50"></div> <div className="modal-container bg-white mx-auto rounded shadow-lg z-50 overflow-y-auto"> <div onClick={close} className="modal-close absolute top-0 right-0 cursor-pointer flex flex-col items-center mt-4 mr-4 text-white text-sm z-50"> <svg className="fill-current text-white" xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 18 18"> <path d="M14.53 4.53l-1.06-1.06L9 7.94 4.53 3.47 3.47 4.53 7.94 9l-4.47 4.47 1.06 1.06L9 10.06l4.47 4.47 1.06-1.06L10.06 9z"></path> </svg> <span className="text-sm">(Esc)</span> </div> <div className="modal-content py-4 text-left px-6"> {children} </div> </div> </div> ) };
import tensorflow as tf class LogHistory(tf.keras.callbacks.Callback): def on_train_begin(self, logs={}): self.batches = [] self.epochs = [] def _store_logs(self, storage, batch_or_epoch, logs={}): if [key for key in logs if "changed_quantization_ration" in key]: storage.append(batch_or_epoch) def on_batch_end(self, batch, logs={}): self._store_logs(self.batches, batch, logs) def on_epoch_end(self, epoch, logs={}): self._store_logs(self.epochs, epoch, logs) class TestHyperparameterScheduler: pass
import { connect } from 'react-redux'; import Notes from './Notes'; import { editNote, updateNoteRequest, deleteNoteRequest, moveWithinLane } from './NoteActions'; const mapDispatchToProps = { editNote, updateNote: updateNoteRequest, deleteNote: deleteNoteRequest, moveWithinLane, }; export default connect( null, mapDispatchToProps, )(Notes);
import { useState, useEffect } from "react" export default function useScoresByYear(data) { const [points, setPoints] = useState(data) // on mount or change useEffect(() => setPoints(data), [data]) const getYear = year => points.filter(score => score.year === `${year}`)[0] return { points, getYear } }
const request = require('supertest'); const express = require('express'); const Profiles = require('../../api/profile/profileModel'); const profileRouter = require('../../api/profile/profileRouter'); const server = express(); server.use(express.json()); jest.mock('../../api/profile/profileModel'); // mock the auth middleware completely jest.mock('../../api/middleware/authProfile', () => { return { auth0Verify: jest.fn((req, res, next) => next()), authProfile: jest.fn((req, res, next) => next()), }; }); describe('profiles router endpoints', () => { beforeAll(() => { // This is the module/route being tested server.use(['/profile', '/profiles'], profileRouter); jest.clearAllMocks(); }); describe('GET /profiles', () => { it('should return 200', async () => { Profiles.findAll.mockResolvedValue([]); const res = await request(server).get('/profiles'); expect(res.status).toBe(200); expect(res.body.length).toBe(0); expect(Profiles.findAll.mock.calls.length).toBe(1); }); }); describe('GET /profiles/:id', () => { it('should return 200 when profile found', async () => { Profiles.findById.mockResolvedValue({ id: 'd376de0577681ca93614', name: 'Bob Smith', email: 'bob@example.com', }); const res = await request(server).get('/profiles/d376de0577681ca93614'); expect(res.status).toBe(200); expect(res.body.name).toBe('Bob Smith'); expect(Profiles.findById.mock.calls.length).toBe(1); }); it('should return 404 when no user found', async () => { Profiles.findById.mockResolvedValue(); const res = await request(server).get('/profiles/d376de0577681ca93614'); expect(res.status).toBe(404); expect(res.body.error).toBe('ProfileNotFound'); }); }); describe('POST /profile', () => { it('should return 200 when profile is created', async () => { const profile = { name: 'Louie Smith', email: 'louie@example.com', avatarUrl: 'https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg', }; Profiles.findById.mockResolvedValue(undefined); Profiles.create.mockResolvedValue([ Object.assign({ id: 'd376de0577681ca93614' }, profile), ]); const res = await request(server).post('/profile').send(profile); expect(res.status).toBe(200); expect(res.body.profile.id).toBe('d376de0577681ca93614'); expect(Profiles.create.mock.calls.length).toBe(1); }); }); describe('PUT /profile', () => { it('should return 200 when profile is created', async () => { const profile = { id: 'd376de0577681ca93614', name: 'Louie Smith', email: 'louie@example.com', avatarUrl: 'https://s3.amazonaws.com/uifaces/faces/twitter/hermanobrother/128.jpg', }; Profiles.findById.mockResolvedValue(profile); Profiles.update.mockResolvedValue([profile]); const res = await request(server).put('/profile/').send(profile); expect(res.status).toBe(200); expect(res.body.profile.name).toBe('Louie Smith'); expect(Profiles.update.mock.calls.length).toBe(1); }); }); });
#! /usr/bin/env python3 import sys import re def vet_nucleotide_sequence(sequence): """ Return None if `sequence` is a valid RNA or DNA sequence, else raise exception. Parameters ---------- sequence : str A string representing a DNA or RNA sequence (upper or lower-case) Returns ------- None Return nothing (None) if sequence is valid, otherwise raise an exception. Examples -------- >>> vet_nucleotide_sequence('ACGTACGT') == None True >>> vet_nucleotide_sequence('not a valid sequence') Traceback (most recent call last): ... Exception: Invalid sequence: 'not a valid sequence' Don't allow mixing of DNA and RNA! >>> vet_nucleotide_sequence('AUTGC') Traceback (most recent call last): ... Exception: Invalid sequence: 'AUTGC' Don't allow whitespace (or other characters) before, within, or after! >>> vet_nucleotide_sequence(' ACGT ACGT ') Traceback (most recent call last): ... Exception: Invalid sequence: ' ACGT ACGT ' But, an empty string should be deemed valid >>> vet_nucleotide_sequence('') == None True """ ########################################################################## ############################ EDIT CODE BELOW ############################# # `rna_pattern_str` and `dna_pattern_str` need to be regular expressions # that will match any string of zero or more RNA and DNA bases, # respectively (and only strings of zero or more RNA and DNA bases). # Currently, `rna_pattern_str` and `dna_pattern_str` are strings of literal # characters. # These are valid regular expressions, but they will only match their # respective strings exactly. # Change `rna_pattern_str` and `dna_pattern_str` so that they will match # any valid RNA and DNA sequence strings, respectively (and only strings of # RNA and DNA bases). # Read the docstring above for additional clues. rna_pattern_str = r'^$|^[AUCG]+$' dna_pattern_str = r'^$|^[ATCG]+$' ########################################################################## rna_pattern = re.compile(rna_pattern_str, flags=re.IGNORECASE) dna_pattern = re.compile(dna_pattern_str, flags=re.IGNORECASE) if rna_pattern.match(sequence): return if dna_pattern.match(sequence): return else: raise Exception("Invalid sequence: {0!r}".format(sequence)) def vet_codon(codon): """ Return None if `codon` is a valid RNA codon, else raise an exception. Parameters ---------- codon : str A string representing a codon (upper or lower-case) Returns ------- None Return nothing (None) if codon is valid, otherwise raise an exception. Examples -------- Valid codon >>> vet_codon('AUG') == None True lower-case is also vaild >>> vet_codon('aug') == None True DNA is not valid >>> vet_codon('ATG') Traceback (most recent call last): ... Exception: Invalid codon: 'ATG' A codon must be exactly 3 RNA bases long >>> vet_codon('AUGG') Traceback (most recent call last): ... Exception: Invalid codon: 'AUGG' """ ########################################################################## ############################ EDIT CODE BELOW ############################# # `codon_pattern_str` needs to be a regular expression that will match any # codon (but only a string that is one codon). # Currently, `codon_pattern_str` is only a string of literal characters. # This is a valid regular expression, but it will only match 'AUG' exactly. # Change `codon_pattern_str` so that it will match any valid codons, and # only valid codons. # Read the docstring above for additional clues. codon_pattern_str = r'[AUGC]{3}$' ########################################################################## codon_pattern = re.compile(codon_pattern_str, flags=re.IGNORECASE) if codon_pattern.match(codon): return else: raise Exception("Invalid codon: {0!r}".format(codon)) def find_first_orf(sequence, start_codons = ['AUG'], stop_codons = ['UAA', 'UAG', 'UGA']): """ Return the first open-reading frame in the DNA or RNA `sequence`. An open-reading frame (ORF) is the part of an RNA sequence that is translated into a peptide. It must begin with a start codon, followed by zero or more codons (triplets of nucleotides), and end with a stop codon. If there are no ORFs in the sequence, an empty string is returned. Parameters ---------- sequence : str A string representing a DNA or RNA sequence (upper or lower-case) start_codons : list of strings All possible start codons. Each codon must be a string of 3 RNA bases, upper or lower-case. stop_codons : list of strings All possible stop codons. Each codon must be a string of 3 RNA bases, upper or lower-case. Returns ------- str An uppercase string of the first ORF found in the `sequence` that starts with any one of the `start_codons` and ends with any one of the `stop_codons`. If no ORF is found an empty string is returned. Examples -------- When the whole RNA sequence is an ORF: >>> find_first_orf('AUGGUAUAA', ['AUG'], ['UAA']) 'AUGGUAUAA' When the whole DNA sequence is an ORF: >>> find_first_orf('ATGGTATAA', ['AUG'], ['UAA']) 'AUGGUAUAA' When there is no ORF: >>> find_first_orf('CUGGUAUAA', ['AUG'], ['UAA']) '' When there is are bases before and after ORF: >>> find_first_orf('CCAUGGUAUAACC', ['AUG'], ['UAA']) 'AUGGUAUAA' """ # Make sure the sequence is valid vet_nucleotide_sequence(sequence) # Make sure the codons are valid for codon in start_codons: vet_codon(codon) for codon in stop_codons: vet_codon(codon) # Get copies of everything in uppercase seq = sequence.upper() starts = [c.upper() for c in start_codons] stops = [c.upper() for c in stop_codons] # Make sure seq is RNA seq = seq.replace('T', 'U') ########################################################################## ############################ EDIT CODE BELOW ############################# # `orf_pattern_str` needs to be a regular expression that will match an # open reading frame within a string of RNA bases. At this point we know # the string only contains uppercase A, C, G, and U. # I recommend starting by hardcoding the standard start and stop codons # (the ones listed as defaults for this function) into the regular # expression. After you get that working, then try generalizing it to work # for any start/stop codons. # Currently, `orf_pattern_str` is only a string of literal characters. This # is a valid regular expression, but it will only match 'AUGGUAUAA' # exactly. Change `orf_pattern_str` so that it will match any open reading # frame. # Read the docstring above for additional clues. if start_codons == ['AUG']: orf_pattern_str = r'AUG([AUCG]{3})*(UAG|UGA|UAA)' else: orf_pattern_str = r'AAA([AUCG]{3})*UUU' ########################################################################## # Create the regular expression object orf_pattern = re.compile(orf_pattern_str) # Search the sequence match_object = orf_pattern.search(seq) if match_object: return match_object.group() return '' def parse_sequence_from_path(path): # Try to open the path to read from it, and handle exceptions if they # arrise try: file_stream = open(path, 'r') except FileNotFoundError as e: sys.stderr.write("Sorry, couldn't find path {}".format(path)) raise e except IsADirectoryError as e: sys.stderr.write("Sorry, path {} appears to be a directory".format( path)) raise e except: sys.stderr.write("Sorry, something went wrong when trying to open {}".format( path)) raise # If we've reached here, the file is open and ready to read sequence = '' # A for loop to visit each line in the file for line in file_stream: # Strip whitespace from the line and concatenate it to the end of the # sequence sequence += line.strip() return sequence def main(): import argparse # Create a command-line parser object parser = argparse.ArgumentParser() default_start_codons = ['AUG'] default_stop_codons = ['UAA', 'UAG', 'UGA'] # Tell the parser what command-line arguments this script can receive parser.add_argument('sequence', metavar = 'SEQUENCE', type = str, help = ('The sequence to search for an open-reading frame. ' 'If the path flag (\'-p\'/\'--path\') is specified, ' 'then this should be a path to a file containing the ' 'sequence to be searched.')) parser.add_argument('-p', '--path', action = 'store_true', help = ('The sequence argument should be treated as a path to a ' 'containing the sequence to be searched.')) parser.add_argument('-s', '--start-codon', type = str, action = 'append', # append each argument to a list default = None, help = ('A start codon. This option can be used multiple times ' 'if there are multiple start codons. ' 'Default: {0}.'.format(" ".join(default_start_codons)))) parser.add_argument('-x', '--stop-codon', type = str, action = 'append', # append each argument to a list default = None, help = ('A stop codon. This option can be used multiple times ' 'if there are multiple stop codons. ' 'Default: {0}.'.format(" ".join(default_stop_codons)))) # Parse the command-line arguments into a 'dict'-like container args = parser.parse_args() # Check to see if the path option was set to True by the caller. If so, parse # the sequence from the path if args.path: sequence = parse_sequence_from_path(args.sequence) else: sequence = args.sequence # Check to see if start/stop codons were provided by the caller. If not, # use the defaults. if not args.start_codon: args.start_codon = default_start_codons if not args.stop_codon: args.stop_codon = default_stop_codons orf = find_first_orf(sequence = sequence, start_codons = args.start_codon, stop_codons = args.stop_codon) sys.stdout.write('{}\n'.format(orf)) if __name__ == '__main__': main()
import glob import os import re import sys from lxml import etree from functions import replace_files class VersionBumper: module_list = [ "AWSAPIGateway", "AWSAutoScaling", "AWSCloudWatch", "AWSCognitoAuth", "AWSCognitoIdentityProvider", "AWSComprehend", "AWSConnect", "AWSConnectParticipant", "AWSCore", "AWSDynamoDB", "AWSEC2", "AWSElasticLoadBalancing", "AWSIoT", "AWSKMS", "AWSKinesis", "AWSKinesisVideo", "AWSKinesisVideoArchivedMedia", "AWSKinesisVideoSignaling", "AWSLambda", "AWSLex", "AWSLogs", "AWSMachineLearning", "AWSPinpoint", "AWSPolly", "AWSRekognition", "AWSS3", "AWSSES", "AWSSNS", "AWSSQS", "AWSSageMakerRuntime", "AWSSimpleDB", "AWSTextract", "AWSTranscribe", "AWSTranscribeStreaming", "AWSTranslate", "AWSAuthSDK/Sources/AWSAuthCore", "AWSAuthSDK/Sources/AWSAuthUI", "AWSAuthSDK/Sources/AWSAppleSignIn", "AWSAuthSDK/Sources/AWSFacebookSignIn", "AWSAuthSDK/Sources/AWSGoogleSignIn", "AWSAuthSDK/Sources/AWSMobileClient", "AWSAuthSDK/Sources/AWSUserPoolsSignIn", ] def __init__(self, root, new_sdk_version): self._root = root self._new_sdk_version = new_sdk_version def bump_sdk_version(self): self.bump_plists() self.bump_services() self.bump_podspecs() self.bump_changelog() self.bump_generate_docs() def bump_plists(self): for module in VersionBumper.module_list: filename = os.path.join(root, module, "Info.plist") self.bump_plist(filename) def bump_plist(self, filename): tree = etree.parse(filename) root_node = tree.getroot() namespaces = root_node.nsmap dict_node = root_node.find("./dict", namespaces) set_version = False for child in dict_node: if child.tag == "key" and child.text == "CFBundleShortVersionString": set_version = True else: if set_version: child.text = self._new_sdk_version break plist_string = VersionBumper.format_plist(tree) plist = open(filename, "w") plist.write(plist_string) plist.close() @staticmethod def format_plist(tree): """ Adjusts lxml's pretty-printed XML format to match Xcode's default and avoid semantically uninteresting diffs :param tree: the lxml tree to format :return: a pretty-printed string matching Xcode's plist format """ plist_string = VersionBumper.tree_to_string(tree) flags = re.MULTILINE | re.IGNORECASE # Prepend XML prolog. This could be partially done with `lxml.tostring`'s # xml_declaration option, but that returns single-quoted attributes formatted_plist = '<?xml version="1.0" encoding="UTF-8"?>\n' + plist_string # Replace self-closing '<string/>' tags with explicitly closed tags formatted_plist = re.sub(r"<string/>", "<string></string>", formatted_plist, flags=flags) # Adjust lxml's default space-based indentation to Xcode's tab-based. Use the # multiline flag and match beginning of each line. formatted_plist = re.sub(r"^\s+<", "\t<", formatted_plist, flags=flags) return formatted_plist @staticmethod def tree_to_string(tree): plist_bytes = etree.tostring( tree, pretty_print=True, xml_declaration=False, encoding="UTF-8" ) plist_string = plist_bytes.decode("utf-8") return plist_string def bump_services(self): service_pattern = { "match": r'(NSString[[:space:]]+\*const[[:space:]]+AWS.+SDKVersion[[:space:]]*=[[:space:]]+@")[0-9]+\.[0-9]+\.[0-9]+"', # noqa: E501 "replace": r'\1{version}"'.format(version=self._new_sdk_version), "files": [], } # Add files for each module for module in VersionBumper.module_list: path = "{0}/{0}Service.m".format(module) if os.path.isfile(os.path.join(root, path)): service_pattern["files"].append(path) # Add files for special modules service_pattern["files"].extend( [ "AWSAPIGateway/AWSAPIGatewayClient.m", "AWSCognitoAuth/AWSCognitoAuth.m", "AWSCore/Service/AWSService.m", "AWSIoT/AWSIoTDataService.m", "AWSKinesis/AWSFirehoseService.m", "AWSLex/AWSLexInteractionKit.m", "AWSPinpoint/AWSPinpointTargeting/AWSPinpointTargetingService.m", "AWSPolly/AWSPollySynthesizeSpeechURLBuilder.m", "AWSS3/AWSS3PreSignedURL.m", ] ) replace_files(self._root, service_pattern) def bump_podspecs(self): podspec_pattern1 = { "match": r"(dependency[[:space:]]+'AWS.+'[[:space:]]*,[[:space:]]*')[0-9]+\.[0-9]+\.[0-9]+(')", # noqa: E501 "replace": r"\1{version}\2".format(version=self._new_sdk_version), "files": [], } podspec_pattern2 = { "match": r"(s\.version[[:space:]]+=[[:space:]]*')[0-9]+\.[0-9]+\.[0-9]+(')", "replace": r"\1{version}\2".format(version=self._new_sdk_version), "files": [], } for file in glob.glob(os.path.join(root, "*.podspec")): podspec_pattern1["files"].append(file) podspec_pattern2["files"].append(file) replace_files(self._root, podspec_pattern1) replace_files(self._root, podspec_pattern2) def bump_changelog(self): changelog_pattern = { "match": r"## Unreleased", "replace": "## Unreleased\\\n\\\n-Features for next release\\\n\\\n## {version}".format( version=self._new_sdk_version ), "files": ["CHANGELOG.md"], } replace_files(self._root, changelog_pattern) def bump_generate_docs(self): generate_documentation_pattern = { "match": r'VERSION="[0-9]+\.[0-9]+\.[0-9]+"', "replace": r'VERSION="{version}"'.format(version=self._new_sdk_version), "files": ["CircleciScripts/generate_documentation.sh"], } replace_files(self._root, generate_documentation_pattern) if __name__ == "__main__": root = sys.argv[1] new_sdk_version = sys.argv[2] bumper = VersionBumper(root, new_sdk_version) bumper.bump_sdk_version()
import React from 'react'; import {useStaticQuery, graphql} from 'gatsby'; import {Row, Column} from '../Sections' import {H3, H4, Paragraph} from '../Heading' import graphic from "../../assets/images/graphic.png" import Trend from 'react-trend'; import {Colors} from '../Styling' import {Card} from '../Card' export default () => { const data = useStaticQuery(graphql` query myQueryJobs{ job: allJobsStatisticsYaml { edges { node { jobs { title slug sub_title value value_symbol chart_data } } } } } `) const jobs = data.job.edges[0].node.jobs return ( <Row> {jobs.map((i, index) => ( <Column size="4" key={index} > <Card width="100%" h_xs="120px" h_sm="140px" h_md="130px" h_lg="150px" h_xl="160px" shadow padding="15px" margin="5px 0" > <Row align="around" marginLeft="10px"> <Column size size="6" customRespSize respSize="6" > <Row> <Paragraph color="gray" align="left" margin="0 0 10px 0" fs_xs="10px" fs_sm="12px" fs_md="10px" fs_lg="12px" fs_xl="16px"> {i.title} </Paragraph> </Row> <Row> <H3 primary>{i.value}</H3><span><H3 primary>{i.value_symbol}</H3></span> </Row> <Row> <Paragraph color="gray" align="left" margin="10px 0 0 0" fs_xs="10px" fs_sm="12px" fs_md="10px" fs_lg="12px" fs_xl="16px"> {i.sub_title} </Paragraph> </Row> </Column> <Column size size="4" customRespSize respSize="6" alignSelf="center"> <Trend smooth autoDraw autoDrawDuration={5000} autoDrawEasing="ease-out" data={i.chart_data} gradient={[`${Colors.blue}`]} radius={25} strokeWidth={5} strokeLinecap={'butt'} /> </Column> </Row> </Card> </Column> )) } </Row > ) }
js2me.createClass({ /* * public static Connection open(String name) throws IOException */ $open$Ljava_lang_String_$Ljavax_microedition_io_Connection_: function (url) { var parts = url.text.split(':'); /*if (parts[0] === 'socket') { return new javaRoot.$javax.$microedition.$io.$SocketConnectionImpl(parts[1], parseInt(parts[2])); }*/ if (parts[0] === 'localmsg') { return new javaRoot.$com.$nokia.$mid.$s40.$io.$LocalMessageProtocolConnection(parts[1]); } if (parts[0] === 'file') { return new javaRoot.$javax.$microedition.$io.$file.$FileConnectionImpl(parts[1], parts[2]); } throw new Error('Unsupported protocol: ' + url.text); }, $open$Ljava_lang_String_I$Ljavax_microedition_io_Connection_: function (url) { return this.$open$Ljava_lang_String_$Ljavax_microedition_io_Connection_(url); }, $open$Ljava_lang_String_IZ$Ljavax_microedition_io_Connection_: function (url) { return this.$open$Ljava_lang_String_$Ljavax_microedition_io_Connection_(url); }, require: ['javaRoot.$javax.$microedition.$io.$file.$FileConnectionImpl', 'javaRoot.$com.$nokia.$mid.$s40.$io.$LocalMessageProtocolConnection'] });
// this is where fetches go export const fetchCharacters = () => { return (dispatch) => { return fetch("http://localhost:3000/characters") .then((response) => response.json()) .then((characters) => { console.log(characters); dispatch({ type: "FETCH_CHARACTERS", payload: characters }); }); }; };
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } 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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var _typeof = function(obj) { return obj && typeof Symbol !== "undefined" && obj.constructor === Symbol ? "symbol" : typeof obj; }; // @filename: file.tsx // @jsx: react // @noLib: true // @skipLibCheck: true // @libFiles: react.d.ts,lib.d.ts var React = require('react'); var RC1 = /*#__PURE__*/ function(_Component) { "use strict"; _inherits(RC1, _Component); function RC1() { _classCallCheck(this, RC1); return _possibleConstructorReturn(this, _getPrototypeOf(RC1).apply(this, arguments)); } _createClass(RC1, [ { key: "render", value: function render() { return null; } } ]); return RC1; }(React.Component); var RC2 = /*#__PURE__*/ function(_Component) { "use strict"; _inherits(RC2, _Component); function RC2() { _classCallCheck(this, RC2); return _possibleConstructorReturn(this, _getPrototypeOf(RC2).apply(this, arguments)); } _createClass(RC2, [ { key: "render", value: function render() { return null; } }, { key: "method", value: function method() { } } ]); return RC2; }(React.Component); var RC3 = /*#__PURE__*/ function(_Component) { "use strict"; _inherits(RC3, _Component); function RC3() { _classCallCheck(this, RC3); return _possibleConstructorReturn(this, _getPrototypeOf(RC3).apply(this, arguments)); } _createClass(RC3, [ { key: "render", value: function render() { return null; } } ]); return RC3; }(React.Component); var RC4 = /*#__PURE__*/ function(_Component) { "use strict"; _inherits(RC4, _Component); function RC4() { _classCallCheck(this, RC4); return _possibleConstructorReturn(this, _getPrototypeOf(RC4).apply(this, arguments)); } _createClass(RC4, [ { key: "render", value: function render() { return null; } } ]); return RC4; }(React.Component); var RCComp = RC1 || RC2; var EmptyRCComp = RC3 || RC4; var PartRCComp = RC1 || RC4; // Error var a = /*#__PURE__*/ React.createElement(RCComp, { x: true }); var b = /*#__PURE__*/ React.createElement(PartRCComp, { x: 10 }); var c = /*#__PURE__*/ React.createElement(EmptyRCComp, { prop: true }); export { };
import { StyleSheet } from "react-native"; const styles = StyleSheet.create({ container: { flexDirection: "row", alignItems: "center", }, profile: { width: 40, height: 40, }, title: { marginLeft: 10, textAlign: "center", fontSize: 20, fontWeight: "bold", }, }); export default styles;
import React from 'react'; import { Route, Link, Redirect } from 'react-router-dom'; import Home from '../home'; import About from '../../components/about'; import Login from '../../containers/login'; import Logout from '../../containers/login/logout'; import { appStore } from '../../index'; const PrivateRoute = ({component: Component, authed, ...rest}) => { return ( <Route {...rest} render={(props) => authed === true ? <Component {...props} /> : <Redirect to={{pathname: '/login', state: {from: props.location}}} />} /> ) } const App = () => ( <div> <header> <Link to="/">Home</Link> <Link to="/about">About</Link> <Link to="/login">Login</Link> <Link to="/logout">Logout</Link> </header> <main> <PrivateRoute authed={appStore.getState().authentication.isAuthenticated} exact path='/' component={Home} /> <PrivateRoute authed={appStore.getState().authentication.isAuthenticated} exact path='/about' component={About} /> <Route exact path="/login" component={Login} /> <Route exact path="/logout" component={Logout} /> </main> </div> ); export default App;
const { Model, DataTypes } = require("sequelize"); const sequelize = require("../config/connection"); class Nanny extends Model {} Nanny.init( { id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, }, username: { type: DataTypes.STRING, allowNull: false, }, password: { type: DataTypes.STRING, allowNull: false, }, location: { type: DataTypes.STRING, allowNull: false, }, years_experience: { type: DataTypes.INTEGER, allowNull: false, }, education: { type: DataTypes.STRING, allowNull: false, }, languages: { type: DataTypes.STRING, allowNull: false, }, gender: { type: DataTypes.STRING, allowNull: false, }, filename: { type: DataTypes.STRING, allowNull: false, }, }, { sequelize, timestamps: true, freezeTableName: true, underscored: true, modelName: "nanny", } ); module.exports = Nanny;
import request from "@/utils/request" export function PostInstallEquip (data) { return request({ url: "/installEquip", method: "post", data: data }) }
#!/usr/bin/env python from __future__ import division, print_function, unicode_literals import time import signal import sys import os import shutil import platform import errno import select import logging import threading try: from ConfigParser import SafeConfigParser as _ConfigParser, NoOptionError class ConfigParser(_ConfigParser): # enable dict-like access as with py3 class SectionProxy(object): def __init__(self, conf, sect): self.conf, self.sect = conf, sect def __getitem__(self, key): try: return self.conf.get(self.sect, key) except NoOptionError: raise KeyError(key) def get(self, key, defval=None): try: return self.conf.get(self.sect, key) except NoOptionError: return defval def __getitem__(self, section): if section!='DEFAULT' and not self.has_section(section): raise KeyError(section) return self.SectionProxy(self, section) except ImportError: from configparser import SafeConfigParser as ConfigParser import numpy import h5py from p4p.client.thread import Context, Disconnected _log = logging.getLogger(__name__) ref_dtype = h5py.special_dtype(ref=h5py.Reference) def getargs(): from argparse import ArgumentParser A = ArgumentParser(description="""Poor man's BSAS archiver. Run with *TBL PV name, and prefix for output files. Switches to a new file on SIGHUP or SIGUSR1. Graceful exit on SIGINT. Writes HDF5 files which attempt to be MAT 7.3 compatible. """) A.add_argument('conf', metavar='FILE', help='configuration file') A.add_argument('--section', metavar='NAME', default='DEFAULT', help='configure file section to use') A.add_argument('-v', '--verbose', action='store_const', const=logging.DEBUG, default=logging.INFO) A.add_argument('-q', '--quiet', action='store_const', const=logging.WARN, dest='verbose') A.add_argument('-C', '--check', action='store_true', default=False, help="Exit after reading configuration file") return A.parse_args() def matheader(fname): """The magic header used to distinguish Matlab .mat files from everyday ordinary run of the mill HDF5 files. https://pythonhosted.org/hdf5storage/storage_format.html#matlab-file-header """ I = {} I['major'], I['minor'], I['micro'] = sys.version_info[:3] H = 'MATLAB 7.3 MAT-file, Platform: CPython %(major)d.%(minor)d.%(micro)d, Created on: %%a %%b %%d %%H:%%M:%%S %%Y HDF5 schema 1.00 .'%I H = time.strftime(H).encode('ascii') assert len(H)<(128-12), repr(H) H = H + b' '*(128-12-len(H)) + b'\0\0\0\0\0\0\0\0\x00\x02\x49\x4d' assert len(H)==128, repr(H) # we are writing into the userblock, which is assumed to be at least 128 bytes long. # we ensure this below when creating new files. with open(fname, 'r+b') as F: F.write(H) # values for the magic 'MATLAB_class' attribute on datasets _mat_class = { numpy.dtype('f4'): numpy.string_('single'), numpy.dtype('f8'): numpy.string_('double'), numpy.dtype('u1'): numpy.string_('uint8'), numpy.dtype('u2'): numpy.string_('uint16'), numpy.dtype('u4'): numpy.string_('uint32'), numpy.dtype('u8'): numpy.string_('uint64'), numpy.dtype('i1'): numpy.string_('int8'), numpy.dtype('i2'): numpy.string_('int16'), numpy.dtype('i4'): numpy.string_('int32'), numpy.dtype('i8'): numpy.string_('int64'), # TODO: bool and some string types } class TableWriter(object): context = Context('pva', unwrap=False) def __init__(self, conf, wakeup=None, check=False): self._wakeup = wakeup # pull out mandatory config items now self.pv = conf['tablePV'] self.ftemplate = conf['outfile'] # passed through time.strftime() self.ftemp = conf.get('scratch', '/tmp/bsas_%s.h5'%self.pv) self.temp_limit = int( float(conf.get('temp_limit', '0'))*(2**30) ) # in bytes if self.temp_limit <= 0: stat = os.statvfs(os.path.dirname(self.ftemp)) # by default, limit ourself to a fraction of the FS capacity self.temp_limit = int(stat.f_frsize*stat.f_blocks*0.25) self.temp_period = float(conf.get('temp_period', '60'))*60.0 # in sec. self.group = conf.get('file_group', '/') if check: raise KeyboardInterrupt() # guards open HDF5 file, and our attributes. # serialize main thread and PVA worker self.lock = threading.Lock() self.nextref = 0 self.initial = True self.prevstart = None self.F, self.G = None, None # h5py.File and h5py.Group self._migrate = None _log.info("Create subscription") self.S = self.context.monitor(self.pv, self._update, request='field()record[pipeline=True]', notify_disconnect=True) def close(self): # self.lock is locked _log.info("Close subscription") self.S.close() _log.info("Final flush") self.flush(force=True) if self._migrate is not None: _log.info("Wait for final migration") self._migrate.join() _log.info("final migration complete") def _update(self, val): # called from PVA worker only start, prevstart = time.time(), self.prevstart self.prevstart = start _log.debug('Update') with self.lock: self.__update(val) if prevstart is None: return end = time.time() interval = start-prevstart # >= the server update interval (based on previous update) dT = end-start # our processing time for this update if dT >= interval*0.75: _log.warn("Processing time %.2f approaches threshold %.2f", dT, interval) else: _log.info("Processing time %.2f, threshold %.2f", dT, interval) def __update(self, val): # self.lock is locked if isinstance(val, Disconnected): _log.warn("Table PV disconnect") self.initial = True self.flush() return elif self.initial: _log.warn("Table PV (re)connect") self.initial = False return # ignore initial update elif self.F is None: self.open() # lazy (re)open on first update for fld, lbl in zip(val.value.keys(), val.labels): V = val.value[fld] if isinstance(V, numpy.ndarray): new, = V.shape try: D = self.G[fld] except KeyError: D = self.G.create_dataset(fld, dtype=V.dtype, shape=(0, 1), chunks=None, maxshape=(None, 1), shuffle=True, compression='gzip') D.attrs['label'] = lbl D.attrs['MATLAB_class'] = _mat_class[V.dtype] cur, _one = D.shape D.resize((cur+new, 1)) D[cur:, 0] = V # copy elif isinstance(V, list): # union[] # store as cell array try: D = self.G[fld] except KeyError: D = self.G.create_dataset(fld, dtype=ref_dtype, shape=(0, 1), chunks=None, maxshape=(None, 1)) D.attrs['label'] = lbl D.attrs['MATLAB_class'] = numpy.string_("cell") refs = [] _refs_ = self.G.require_group('#refs#') _path = numpy.string_(_refs_.name.encode('ascii')) # placeholder for empty cells try: null = _refs_['null'] except KeyError: null = _refs_.create_dataset('null', data=numpy.asarray([0,1], dtype='u8')) null.attrs['MATLAB_class'] = numpy.string_('double') null.attrs['H5PATH'] = _path null.attrs['MATLAB_empty'] = numpy.asarray(1, dtype='u1') for img in V: if img is None: refs.append(null.ref) else: dset = _refs_.create_dataset('cellval%d'%self.nextref, data=img, shuffle=True, compression='gzip', compression_opts=9) dset.attrs['MATLAB_class'] = _mat_class[img.dtype] dset.attrs['H5PATH'] = _path refs.append(dset.ref) self.nextref += 1 cur, _one = D.shape D.resize((cur+new, 1)) D[cur:, 0] = refs self.F.flush() # flush this update to disk self.flush() def flush(self, force=False): # self.lock is locked if self.F is not None: self.F.flush() age = time.time()-self.F_time size = os.stat(self.ftemp).st_size if not force and age < self.temp_period and size < self.temp_limit: _log.info('Skip rotate, too new (%.2f < %.2f) or too small (%d < %d)', age, self.temp_period, size, self.temp_limit) return _log.info('Close and rotate') self.F.close() self.F, self.G = None, None if os.path.isfile(self.ftemp): if self._migrate is not None: # We only pipeline a single migration. # If this hasn't completed, then we stall until it has. self._migrate.join(0.01) if self._migrate.isAlive(): _log.warn("Flush stalls waiting for previous migration to complete. Prepare for data loss!") self._migrate.join() self._migrate = None _log.info("Previous migration complete") _log.info("Starting migration of '%s'", self.ftemp) stage2 = self.ftemp+'.tmp' if os.path.isfile(stage2): _log.error("Overwriting debris '%s' !", stage2) os.rename(self.ftemp, stage2) self._migrate = threading.Thread(name='BSAS Migration', target=self._movefile, args=(stage2,)) self._migrate.start() def _movefile(self, stage2): # called from migration thread only finalpath = None try: start = time.time() # expand template with last mod time (instead of current time) mtime = os.stat(stage2).st_mtime finalpath = time.strftime(self.ftemplate, time.gmtime(mtime)) # expand using UTC if os.path.isfile(finalpath): _log.error("Migration destination '%s' already exists. Prepare for data loss!") os.remove(finalpath) _log.info('Migrate %s -> %s', stage2, finalpath) try: os.makedirs(os.path.dirname(finalpath)) except OSError: pass #if we failed, then the move will also fail shutil.move(stage2, finalpath) end = time.time() _log.info("Migration of '%s' complete after %.2f sec", finalpath, end-start) except: _log.exception("Failure during Migration of '%s' -> '%s'", stage2, finalpath) def open(self): # self.lock is locked self.flush() _log.info('Open "%s"', self.ftemp) with h5py.File(self.ftemp, 'w-', userblock_size=512) as F: # error if already exists assert F.userblock_size>=128, F.userblock_size matheader(self.ftemp) self.F = h5py.File(self.ftemp, 'r+') # error if not exists self.F_time = time.time() self.G = self.F.require_group(self.group) self.nextref = 0 def __enter__(self): return self def __exit__(self, A,B,C): with self.lock: self.close() class SigWake(object): def __enter__(self): self._R, self._W = os.pipe() self.prevHUP = signal.signal(signal.SIGHUP, self._wake) self.prevUSR1 = signal.signal(signal.SIGUSR1, self._wake) return self def __exit__(self, A,B,C): signal.signal(signal.SIGHUP, self.prevHUP) signal.signal(signal.SIGUSR1, self.prevUSR1) os.close(self._R) os.close(self._W) def _wake(self, num, frame): self.poke() def poke(self): os.write(self._W, '!') def wait(self, timeout=None): try: Rs, _Ws, _Es = select.select([self._R], [], [], timeout) if self._R in Rs: os.read(self._R, 1) except select.error: pass # assume EINTR except OSError as e: if e.errno!=errno.EINTR: raise signal.signal(signal.SIGHUP, self._wake) signal.signal(signal.SIGUSR1, self._wake) def set_proc_name(newname): if platform.system()!='Linux': _log.warn("Don't know how to set process name") return newname = newname[:15] from ctypes import cdll, byref, create_string_buffer libc = cdll.LoadLibrary(None) buff = create_string_buffer(len(newname)+1) buff.value = newname libc.prctl(15, byref(buff), 0, 0, 0) # PR_SET_NAME=15 on Linux def main(conf): try: with SigWake() as S: with TableWriter(conf, check=args.check) as W: _log.info("Running") while True: S.wait(W.temp_period/4.) with W.lock: W.flush() except KeyboardInterrupt: pass _log.info("Done") if __name__=='__main__': # set process name to allow external tools like eg. logrotate # to force us to start a new file. # killall -s SIGUSR1 h5tablewriter set_proc_name('h5tablewriter') args = getargs() conf = ConfigParser({ 'PWD':os.path.dirname(args.conf), 'scratch':'/tmp/%(tablePV)s.h5', }) with open(args.conf, 'r') as F: conf.readfp(F) logging.basicConfig(level=args.verbose) main(conf[args.section])
'use strict'; var path = require('path'); var jest = require('jest'); var algoliasearch = require('algoliasearch'); var staticJestConfig = require('../jest.config'); var enableIntegrationTest = process.env.ONLY_UNIT !== 'true' && process.env.INTEGRATION_TEST_API_KEY && process.env.INTEGRATION_TEST_APPID; var projectsRootPaths = [path.resolve(__dirname, '..')]; var dynamicJestConfig = Object.assign({}, staticJestConfig, { maxWorkers: 4, setupFilesAfterEnv: staticJestConfig.setupFilesAfterEnv || [] }); if (enableIntegrationTest) { dynamicJestConfig.testMatch.push('<rootDir>/test/integration-spec/**/*.[jt]s?(x)'); dynamicJestConfig.setupFilesAfterEnv.push(path.resolve(__dirname, '..', 'jest.setup.js')); } jest.runCLI(dynamicJestConfig, projectsRootPaths).then(function(response) { if (!response.results.success) { process.exitCode = response.globalConfig.testFailureExitCode; } if (enableIntegrationTest) { var client = algoliasearch( process.env.INTEGRATION_TEST_APPID, process.env.INTEGRATION_TEST_API_KEY ); client.listIndexes().then(content => { content.items .map(i => i.name) .filter(n => n.indexOf('_circle-algoliasearch-helper') !== -1) .forEach(n => client.deleteIndex(n)); }); } });
/** * gets the first attachment document from the most recent case message to set as the default viewerDocumentToDisplay * * @param {object} providers the providers object * @param {object} providers.props the cerebral props object * @returns {object} object containing viewerDocumentToDisplay */ export const getDefaultAttachmentViewerDocumentToDisplayAction = ({ props, }) => { const { documentId, mostRecentMessage } = props; const { attachments } = mostRecentMessage; let viewerDocumentToDisplay = null; if (attachments && attachments.length) { viewerDocumentToDisplay = attachments[0]; if (documentId) { const foundDocument = attachments.find( attachment => attachment.documentId === documentId, ); if (foundDocument) { viewerDocumentToDisplay = foundDocument; } } } return { viewerDocumentToDisplay, }; };
# Copyright 2019 The FastEstimator 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. # ============================================================================== import tensorflow as tf from fastestimator.op.tensorop.loss import Loss class SmoothL1Loss(Loss): def __init__(self, y_true=None, y_pred=None, inputs=None, outputs=None, mode=None): """Calculate Smooth L1 loss Args: y_true: ground truth label key y_pred: prediction label key inputs: A tuple or list like: [<y_true>, <y_pred>] outputs: Where to store the computed loss value (not required under normal use cases) mode: 'train', 'eval', 'test', or None """ inputs = self.validate_loss_inputs(inputs, y_true, y_pred) super().__init__(inputs=inputs, outputs=outputs, mode=mode) def forward(self, data, state): true, pred = data diff = tf.abs(true - pred) lt_one = tf.dtypes.cast(tf.less(diff, 1.0), "float32") loss = lt_one * 0.5 * diff**2 + (1 - lt_one) * (diff - 0.5) return loss
let tabs = {}; chrome = this.browser || this.chrome; const inspectFile = 'inspect.js'; const activeIcon = 'active-64.png'; const defaultIcon = 'default-64.png'; const inspect = { toggleActivate: function(id, type, icon) { this.id = id; chrome.tabs.executeScript(id, {file: inspectFile}, function() { chrome.tabs.sendMessage(id, {action: type}); }.bind(this)); chrome.browserAction.setIcon({tabId: id, path: {19: 'icons/' + icon}}); } }; function toggle(tab) { if (isSupportedProtocol(tab.url)) { if (!tabs[tab.id]) { tabs[tab.id] = Object.create(inspect); inspect.toggleActivate(tab.id, 'activate', activeIcon); } else { inspect.toggleActivate(tab.id, 'deactivate', defaultIcon); for (let tabId in tabs) { if (tabId == tab.id) delete tabs[tabId]; } } } } function deactivateItem(tab) { if (tab[0]) { if (isSupportedProtocol(tab[0].url)) { for (let tabId in tabs) { if (tabId == tab[0].id) { delete tabs[tabId]; inspect.toggleActivate(tab[0].id, 'deactivate', defaultIcon); } } } } } function getActiveTab() { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { deactivateItem(tabs); }); } function isSupportedProtocol(urlString) { const supportedProtocols = ['https:', 'http:', 'file:']; const url = document.createElement('a'); url.href = urlString; return supportedProtocols.indexOf(url.protocol) != -1; } chrome.commands.onCommand.addListener(command => { if (command === 'toggle-xpath') { chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { toggle(tabs[0]); }); } }); chrome.extension.onConnect.addListener(function(port) { console.assert(port.name == 'screenshot'); port.onMessage.addListener(function(msg) { if (msg.request == 'screenshot') { chrome.tabs.captureVisibleTab( null, {format: 'jpeg', quality: 100}, function(img) { // post message only after call back return with Data URL port.postMessage(img); }); } }); }); chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { console.log(request); if (request.contentScriptQuery == 'sendAnnotations') { var url = 'http://localhost:8000'; fetch(url, {method: 'post', body: request.body}).then(function(response) { return response.text(); }); return true; } }); chrome.tabs.onUpdated.addListener(getActiveTab); chrome.browserAction.onClicked.addListener(toggle);
/* eslint-env jest */ const fs = require('fs'); const path = require('path'); const webpack = require('webpack'); const rimraf = require('rimraf'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const HtmlWebpackAdditionalTemplatePlugin = require('../'); const OUTPUT_DIR = path.join(__dirname, './dist'); describe('HtmlWebpackAdditionalTemplatePlugin', () => { beforeEach(done => { rimraf(OUTPUT_DIR, done); }); it('generate multiple HTML files', done => { webpack( { entry: path.join(__dirname, 'fixtures', 'entry.js'), output: { path: OUTPUT_DIR }, plugins: [ new HtmlWebpackPlugin({ additionalTemplate: [ { filename: 'second.html', template: path.join(__dirname, 'fixtures/test.html') }, { filename: 'third.html', template: path.join(__dirname, 'fixtures/test.html') } ] }), new HtmlWebpackAdditionalTemplatePlugin() ] }, err => { expect(err).toBeFalsy(); expect( fs.statSync(path.resolve(OUTPUT_DIR, 'index.html')) ).toBeTruthy(); expect( fs.statSync(path.resolve(OUTPUT_DIR, 'second.html')) ).toBeTruthy(); expect( fs.statSync(path.resolve(OUTPUT_DIR, 'third.html')) ).toBeTruthy(); done(); } ); }); });
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t=t||self).Sweetalert2=e()}(this,function(){"use strict";function r(t){return(r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function o(t,e){for(var n=0;n<e.length;n++){var o=e[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function c(t,e,n){return e&&o(t.prototype,e),n&&o(t,n),t}function s(){return(s=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n,o=arguments[e];for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&(t[n]=o[n])}return t}).apply(this,arguments)}function u(t){return(u=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function l(t,e){return(l=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function d(){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(t){return!1}}function i(t,e,n){return(i=d()?Reflect.construct:function(t,e,n){var o=[null];o.push.apply(o,e);o=new(Function.bind.apply(t,o));return n&&l(o,n.prototype),o}).apply(null,arguments)}function p(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t):e}function f(t,e,n){return(f="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,n){t=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=u(t)););return t}(t,e);if(t){e=Object.getOwnPropertyDescriptor(t,e);return e.get?e.get.call(n):e.value}})(t,e,n||t)}function m(t){return t.charAt(0).toUpperCase()+t.slice(1)}function h(t){return Array.prototype.slice.call(t)}function g(t){console.error("".concat(at," ").concat(t))}function v(t,e){e='"'.concat(t,'" is deprecated and will be removed in the next major release. Please use "').concat(e,'" instead.'),-1===st.indexOf(e)&&(st.push(e),ct(e))}function b(t,e){"function"==typeof t&&t(e)}function y(t){return"function"==typeof t?t():t}function w(t){return t&&"function"==typeof t.toPromise}function C(t){return w(t)?t.toPromise():Promise.resolve(t)}function k(t){return t&&Promise.resolve(t)===t}function A(t){return t instanceof Element||"object"===r(t=t)&&t.jquery}function x(){return document.body.querySelector(".".concat(lt.container))}function e(t){var e=x();return e?e.querySelector(t):null}function t(t){return e(".".concat(t))}function B(){return t(lt.popup)}function P(){return t(lt.icon)}function E(){return t(lt.title)}function O(){return t(lt["html-container"])}function S(){return t(lt.image)}function n(){return t(lt["progress-steps"])}function T(){return t(lt["validation-message"])}function L(){return e(".".concat(lt.actions," .").concat(lt.confirm))}function j(){return e(".".concat(lt.actions," .").concat(lt.deny))}function D(){return e(".".concat(lt.loader))}function I(){return e(".".concat(lt.actions," .").concat(lt.cancel))}function M(){return t(lt.actions)}function q(){return t(lt.footer)}function H(){return t(lt["timer-progress-bar"])}function V(){return t(lt.close)}function N(){var t=h(B().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')).sort(function(t,e){return t=parseInt(t.getAttribute("tabindex")),(e=parseInt(e.getAttribute("tabindex")))<t?1:t<e?-1:0}),e=h(B().querySelectorAll('\n a[href],\n area[href],\n input:not([disabled]),\n select:not([disabled]),\n textarea:not([disabled]),\n button:not([disabled]),\n iframe,\n object,\n embed,\n [tabindex="0"],\n [contenteditable],\n audio[controls],\n video[controls],\n summary\n')).filter(function(t){return"-1"!==t.getAttribute("tabindex")});return function(t){for(var e=[],n=0;n<t.length;n++)-1===e.indexOf(t[n])&&e.push(t[n]);return e}(t.concat(e)).filter(function(t){return vt(t)})}function R(){return!pt()&&!document.body.classList.contains(lt["no-backdrop"])}function F(e,t){e.textContent="",t&&(t=(new DOMParser).parseFromString(t,"text/html"),h(t.querySelector("head").childNodes).forEach(function(t){e.appendChild(t)}),h(t.querySelector("body").childNodes).forEach(function(t){e.appendChild(t)}))}function U(t,e){if(e){for(var n=e.split(/\s+/),o=0;o<n.length;o++)if(!t.classList.contains(n[o]))return;return 1}}function _(t,e,n){var o,i;if(i=e,h((o=t).classList).forEach(function(t){-1===Object.values(lt).indexOf(t)&&-1===Object.values(dt).indexOf(t)&&-1===Object.values(i.showClass).indexOf(t)&&o.classList.remove(t)}),e.customClass&&e.customClass[n]){if("string"!=typeof e.customClass[n]&&!e.customClass[n].forEach)return ct("Invalid type of customClass.".concat(n,'! Expected string or iterable object, got "').concat(r(e.customClass[n]),'"'));mt(t,e.customClass[n])}}function z(t,e){if(!e)return null;switch(e){case"select":case"textarea":case"file":return gt(t,lt[e]);case"checkbox":return t.querySelector(".".concat(lt.checkbox," input"));case"radio":return t.querySelector(".".concat(lt.radio," input:checked"))||t.querySelector(".".concat(lt.radio," input:first-child"));case"range":return t.querySelector(".".concat(lt.range," input"));default:return gt(t,lt.input)}}function W(t){var e;t.focus(),"file"!==t.type&&(e=t.value,t.value="",t.value=e)}function K(t,e,n){t&&e&&(e="string"==typeof e?e.split(/\s+/).filter(Boolean):e).forEach(function(e){t.forEach?t.forEach(function(t){n?t.classList.add(e):t.classList.remove(e)}):n?t.classList.add(e):t.classList.remove(e)})}function Y(t,e,n){(n=n==="".concat(parseInt(n))?parseInt(n):n)||0===parseInt(n)?t.style[e]="number"==typeof n?"".concat(n,"px"):n:t.style.removeProperty(e)}function Z(t){t.style.display=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"flex"}function J(t){t.style.display="none"}function $(t,e,n,o){(e=t.querySelector(e))&&(e.style[n]=o)}function X(t,e,n){e?Z(t,n):J(t)}function G(t){return!!(t.scrollHeight>t.clientHeight)}function Q(t){var e=window.getComputedStyle(t),t=parseFloat(e.getPropertyValue("animation-duration")||"0"),e=parseFloat(e.getPropertyValue("transition-duration")||"0");return 0<t||0<e}function tt(t){var e=1<arguments.length&&void 0!==arguments[1]&&arguments[1],n=H();vt(n)&&(e&&(n.style.transition="none",n.style.width="100%"),setTimeout(function(){n.style.transition="width ".concat(t/1e3,"s linear"),n.style.width="0%"},10))}function et(){return"undefined"==typeof window||"undefined"==typeof document}function nt(){Bn.isVisible()&&Bn.resetValidationMessage()}function ot(t,e){t instanceof HTMLElement?e.appendChild(t):"object"===r(t)?wt(t,e):t&&F(e,t)}function it(t,e){var n=M(),o=D(),i=L(),r=j(),a=I();e.showConfirmButton||e.showDenyButton||e.showCancelButton||J(n),_(n,e,"actions"),At(i,"confirm",e),At(r,"deny",e),At(a,"cancel",e),function(t,e,n,o){if(!o.buttonsStyling)return ht([t,e,n],lt.styled);mt([t,e,n],lt.styled),o.confirmButtonColor&&(t.style.backgroundColor=o.confirmButtonColor,mt(t,lt["default-outline"]));o.denyButtonColor&&(e.style.backgroundColor=o.denyButtonColor,mt(e,lt["default-outline"]));o.cancelButtonColor&&(n.style.backgroundColor=o.cancelButtonColor,mt(n,lt["default-outline"]))}(i,r,a,e),e.reverseButtons&&(n.insertBefore(a,o),n.insertBefore(r,o),n.insertBefore(i,o)),F(o,e.loaderHtml),_(o,e,"loader")}var rt=Object.freeze({cancel:"cancel",backdrop:"backdrop",close:"close",esc:"esc",timer:"timer"}),at="SweetAlert2:",ct=function(t){console.warn("".concat(at," ").concat("object"===r(t)?t.join(" "):t))},st=[],ut=function(t){var e,n={};for(e in t)n[t[e]]="swal2-"+t[e];return n},lt=ut(["container","shown","height-auto","iosfix","popup","modal","no-backdrop","no-transition","toast","toast-shown","show","hide","close","title","html-container","actions","confirm","deny","cancel","default-outline","footer","icon","icon-content","image","input","file","range","select","radio","checkbox","label","textarea","inputerror","input-label","validation-message","progress-steps","active-progress-step","progress-step","progress-step-line","loader","loading","styled","top","top-start","top-end","top-left","top-right","center","center-start","center-end","center-left","center-right","bottom","bottom-start","bottom-end","bottom-left","bottom-right","grow-row","grow-column","grow-fullscreen","rtl","timer-progress-bar","timer-progress-bar-container","scrollbar-measure","icon-success","icon-warning","icon-info","icon-question","icon-error"]),dt=ut(["success","warning","info","question","error"]),pt=function(){return document.body.classList.contains(lt["toast-shown"])},ft={previousBodyPadding:null},mt=function(t,e){K(t,e,!0)},ht=function(t,e){K(t,e,!1)},gt=function(t,e){for(var n=0;n<t.childNodes.length;n++)if(U(t.childNodes[n],e))return t.childNodes[n]},vt=function(t){return!(!t||!(t.offsetWidth||t.offsetHeight||t.getClientRects().length))},bt='\n <div aria-labelledby="'.concat(lt.title,'" aria-describedby="').concat(lt["html-container"],'" class="').concat(lt.popup,'" tabindex="-1">\n <button type="button" class="').concat(lt.close,'"></button>\n <ul class="').concat(lt["progress-steps"],'"></ul>\n <div class="').concat(lt.icon,'"></div>\n <img class="').concat(lt.image,'" />\n <h2 class="').concat(lt.title,'" id="').concat(lt.title,'"></h2>\n <div class="').concat(lt["html-container"],'"></div>\n <input class="').concat(lt.input,'" />\n <input type="file" class="').concat(lt.file,'" />\n <div class="').concat(lt.range,'">\n <input type="range" />\n <output></output>\n </div>\n <select class="').concat(lt.select,'"></select>\n <div class="').concat(lt.radio,'"></div>\n <label for="').concat(lt.checkbox,'" class="').concat(lt.checkbox,'">\n <input type="checkbox" />\n <span class="').concat(lt.label,'"></span>\n </label>\n <textarea class="').concat(lt.textarea,'"></textarea>\n <div class="').concat(lt["validation-message"],'" id="').concat(lt["validation-message"],'"></div>\n <div class="').concat(lt.actions,'">\n <div class="').concat(lt.loader,'"></div>\n <button type="button" class="').concat(lt.confirm,'"></button>\n <button type="button" class="').concat(lt.deny,'"></button>\n <button type="button" class="').concat(lt.cancel,'"></button>\n </div>\n <div class="').concat(lt.footer,'"></div>\n <div class="').concat(lt["timer-progress-bar-container"],'">\n <div class="').concat(lt["timer-progress-bar"],'"></div>\n </div>\n </div>\n').replace(/(^|\n)\s*/g,""),yt=function(t){var e,n,o,i,r,a=!!(i=x())&&(i.remove(),ht([document.documentElement,document.body],[lt["no-backdrop"],lt["toast-shown"],lt["has-column"]]),!0);et()?g("SweetAlert2 requires document to initialize"):((r=document.createElement("div")).className=lt.container,a&&mt(r,lt["no-transition"]),F(r,bt),(i="string"==typeof(e=t.target)?document.querySelector(e):e).appendChild(r),a=t,(e=B()).setAttribute("role",a.toast?"alert":"dialog"),e.setAttribute("aria-live",a.toast?"polite":"assertive"),a.toast||e.setAttribute("aria-modal","true"),r=i,"rtl"===window.getComputedStyle(r).direction&&mt(x(),lt.rtl),t=B(),a=gt(t,lt.input),e=gt(t,lt.file),n=t.querySelector(".".concat(lt.range," input")),o=t.querySelector(".".concat(lt.range," output")),i=gt(t,lt.select),r=t.querySelector(".".concat(lt.checkbox," input")),t=gt(t,lt.textarea),a.oninput=nt,e.onchange=nt,i.onchange=nt,r.onchange=nt,t.oninput=nt,n.oninput=function(){nt(),o.value=n.value},n.onchange=function(){nt(),n.nextSibling.value=n.value})},wt=function(t,e){t.jquery?Ct(e,t):F(e,t.toString())},Ct=function(t,e){if(t.textContent="",0 in e)for(var n=0;n in e;n++)t.appendChild(e[n].cloneNode(!0));else t.appendChild(e.cloneNode(!0))},kt=function(){if(et())return!1;var t,e=document.createElement("div"),n={WebkitAnimation:"webkitAnimationEnd",OAnimation:"oAnimationEnd oanimationend",animation:"animationend"};for(t in n)if(Object.prototype.hasOwnProperty.call(n,t)&&void 0!==e.style[t])return n[t];return!1}();function At(t,e,n){X(t,n["show".concat(m(e),"Button")],"inline-block"),F(t,n["".concat(e,"ButtonText")]),t.setAttribute("aria-label",n["".concat(e,"ButtonAriaLabel")]),t.className=lt[e],_(t,n,"".concat(e,"Button")),mt(t,n["".concat(e,"ButtonClass")])}function xt(t,e){var n,o,i=x();i&&(o=i,"string"==typeof(n=e.backdrop)?o.style.background=n:n||mt([document.documentElement,document.body],lt["no-backdrop"]),!e.backdrop&&e.allowOutsideClick&&ct('"allowOutsideClick" parameter requires `backdrop` parameter to be set to `true`'),o=i,(n=e.position)in lt?mt(o,lt[n]):(ct('The "position" parameter is not valid, defaulting to "center"'),mt(o,lt.center)),n=i,!(o=e.grow)||"string"!=typeof o||(o="grow-".concat(o))in lt&&mt(n,lt[o]),_(i,e,"container"))}function Bt(t,e){t.placeholder&&!e.inputPlaceholder||(t.placeholder=e.inputPlaceholder)}function Pt(t,e,n){var o,i;n.inputLabel&&(t.id=lt.input,o=document.createElement("label"),i=lt["input-label"],o.setAttribute("for",t.id),o.className=i,mt(o,n.customClass.inputLabel),o.innerText=n.inputLabel,e.insertAdjacentElement("beforebegin",o))}var Et={promise:new WeakMap,innerParams:new WeakMap,domCache:new WeakMap},Ot=["input","file","range","select","radio","checkbox","textarea"],St=function(t){if(!Dt[t.input])return g('Unexpected type of input! Expected "text", "email", "password", "number", "tel", "select", "radio", "checkbox", "textarea", "file" or "url", got "'.concat(t.input,'"'));var e=jt(t.input),n=Dt[t.input](e,t);Z(n),setTimeout(function(){W(n)})},Tt=function(t,e){var n=z(B(),t);if(n)for(var o in!function(t){for(var e=0;e<t.attributes.length;e++){var n=t.attributes[e].name;-1===["type","value","style"].indexOf(n)&&t.removeAttribute(n)}}(n),e)n.setAttribute(o,e[o])},Lt=function(t){var e=jt(t.input);t.customClass&&mt(e,t.customClass.input)},jt=function(t){t=lt[t]||lt.input;return gt(B(),t)},Dt={};Dt.text=Dt.email=Dt.password=Dt.number=Dt.tel=Dt.url=function(t,e){return"string"==typeof e.inputValue||"number"==typeof e.inputValue?t.value=e.inputValue:k(e.inputValue)||ct('Unexpected type of inputValue! Expected "string", "number" or "Promise", got "'.concat(r(e.inputValue),'"')),Pt(t,t,e),Bt(t,e),t.type=e.input,t},Dt.file=function(t,e){return Pt(t,t,e),Bt(t,e),t},Dt.range=function(t,e){var n=t.querySelector("input"),o=t.querySelector("output");return n.value=e.inputValue,n.type=e.input,o.value=e.inputValue,Pt(n,t,e),t},Dt.select=function(t,e){var n;return t.textContent="",e.inputPlaceholder&&(n=document.createElement("option"),F(n,e.inputPlaceholder),n.value="",n.disabled=!0,n.selected=!0,t.appendChild(n)),Pt(t,t,e),t},Dt.radio=function(t){return t.textContent="",t},Dt.checkbox=function(t,e){var n=z(B(),"checkbox");n.value=1,n.id=lt.checkbox,n.checked=Boolean(e.inputValue);n=t.querySelector("span");return F(n,e.inputPlaceholder),t},Dt.textarea=function(e,t){e.value=t.inputValue,Bt(e,t),Pt(e,e,t);var n;return"MutationObserver"in window&&(n=parseInt(window.getComputedStyle(B()).width),new MutationObserver(function(){var t,t=e.offsetWidth+(t=e,parseInt(window.getComputedStyle(t).marginLeft)+parseInt(window.getComputedStyle(t).marginRight));B().style.width=n<t?"".concat(t,"px"):null}).observe(e,{attributes:!0,attributeFilter:["style"]})),e};function It(t,e){var o,i,r,n=O();_(n,e,"htmlContainer"),e.html?(ot(e.html,n),Z(n,"block")):e.text?(n.textContent=e.text,Z(n,"block")):J(n),t=t,o=e,i=B(),t=Et.innerParams.get(t),r=!t||o.input!==t.input,Ot.forEach(function(t){var e=lt[t],n=gt(i,e);Tt(t,o.inputAttributes),n.className=e,r&&J(n)}),o.input&&(r&&St(o),Lt(o))}function Mt(t,o){var i=n();if(!o.progressSteps||0===o.progressSteps.length)return J(i),0;Z(i),i.textContent="",o.currentProgressStep>=o.progressSteps.length&&ct("Invalid currentProgressStep parameter, it should be less than progressSteps.length (currentProgressStep like JS arrays starts from 0)"),o.progressSteps.forEach(function(t,e){var n,t=(n=t,t=document.createElement("li"),mt(t,lt["progress-step"]),F(t,n),t);i.appendChild(t),e===o.currentProgressStep&&mt(t,lt["active-progress-step"]),e!==o.progressSteps.length-1&&(t=o,e=document.createElement("li"),mt(e,lt["progress-step-line"]),t.progressStepsDistance&&(e.style.width=t.progressStepsDistance),i.appendChild(e))})}function qt(t,e){var n,o,i;n=e,i=x(),o=B(),n.toast?(Y(i,"width",n.width),o.style.width="100%",o.insertBefore(D(),P())):Y(o,"width",n.width),Y(o,"padding",n.padding),n.background&&(o.style.background=n.background),J(T()),_t(o,n),xt(0,e),Mt(0,e),i=t,o=e,n=Et.innerParams.get(i),i=P(),n&&o.icon===n.icon?(Rt(i,o),Vt(i,o)):o.icon||o.iconHtml?o.icon&&-1===Object.keys(dt).indexOf(o.icon)?(g('Unknown icon! Expected "success", "error", "warning", "info" or "question", got "'.concat(o.icon,'"')),J(i)):(Z(i),Rt(i,o),Vt(i,o),mt(i,o.showClass.icon)):J(i),function(t){var e=S();if(!t.imageUrl)return J(e);Z(e,""),e.setAttribute("src",t.imageUrl),e.setAttribute("alt",t.imageAlt),Y(e,"width",t.imageWidth),Y(e,"height",t.imageHeight),e.className=lt.image,_(e,t,"image")}(e),o=e,i=E(),X(i,o.title||o.titleText,"block"),o.title&&ot(o.title,i),o.titleText&&(i.innerText=o.titleText),_(i,o,"title"),i=e,o=V(),F(o,i.closeButtonHtml),_(o,i,"closeButton"),X(o,i.showCloseButton),o.setAttribute("aria-label",i.closeButtonAriaLabel),It(t,e),it(0,e),i=e,t=q(),X(t,i.footer),i.footer&&ot(i.footer,t),_(t,i,"footer"),b(e.didRender,B())}function Ht(){return L()&&L().click()}var Vt=function(t,e){for(var n in dt)e.icon!==n&&ht(t,dt[n]);mt(t,dt[e.icon]),Ft(t,e),Nt(),_(t,e,"icon")},Nt=function(){for(var t=B(),e=window.getComputedStyle(t).getPropertyValue("background-color"),n=t.querySelectorAll("[class^=swal2-success-circular-line], .swal2-success-fix"),o=0;o<n.length;o++)n[o].style.backgroundColor=e},Rt=function(t,e){t.textContent="",e.iconHtml?F(t,Ut(e.iconHtml)):"success"===e.icon?F(t,'\n <div class="swal2-success-circular-line-left"></div>\n <span class="swal2-success-line-tip"></span> <span class="swal2-success-line-long"></span>\n <div class="swal2-success-ring"></div> <div class="swal2-success-fix"></div>\n <div class="swal2-success-circular-line-right"></div>\n '):"error"===e.icon?F(t,'\n <span class="swal2-x-mark">\n <span class="swal2-x-mark-line-left"></span>\n <span class="swal2-x-mark-line-right"></span>\n </span>\n '):F(t,Ut({question:"?",warning:"!",info:"i"}[e.icon]))},Ft=function(t,e){if(e.iconColor){t.style.color=e.iconColor,t.style.borderColor=e.iconColor;for(var n=0,o=[".swal2-success-line-tip",".swal2-success-line-long",".swal2-x-mark-line-left",".swal2-x-mark-line-right"];n<o.length;n++)$(t,o[n],"backgroundColor",e.iconColor);$(t,".swal2-success-ring","borderColor",e.iconColor)}},Ut=function(t){return'<div class="'.concat(lt["icon-content"],'">').concat(t,"</div>")},_t=function(t,e){t.className="".concat(lt.popup," ").concat(vt(t)?e.showClass.popup:""),e.toast?(mt([document.documentElement,document.body],lt["toast-shown"]),mt(t,lt.toast)):mt(t,lt.modal),_(t,e,"popup"),"string"==typeof e.customClass&&mt(t,e.customClass),e.icon&&mt(t,lt["icon-".concat(e.icon)])};function zt(t){(e=B())||Bn.fire();var e=B(),n=D();pt()?J(P()):Zt(e,t),Z(n),e.setAttribute("data-loading",!0),e.setAttribute("aria-busy",!0),e.focus()}function Wt(o){return new Promise(function(t){if(!o)return t();var e=window.scrollX,n=window.scrollY;Jt.restoreFocusTimeout=setTimeout(function(){Jt.previousActiveElement&&Jt.previousActiveElement.focus?(Jt.previousActiveElement.focus(),Jt.previousActiveElement=null):document.body&&document.body.focus(),t()},100),window.scrollTo(e,n)})}function Kt(){if(Jt.timeout)return function(){var t=H(),e=parseInt(window.getComputedStyle(t).width);t.style.removeProperty("transition"),t.style.width="100%";var n=parseInt(window.getComputedStyle(t).width),n=parseInt(e/n*100);t.style.removeProperty("transition"),t.style.width="".concat(n,"%")}(),Jt.timeout.stop()}function Yt(){if(Jt.timeout){var t=Jt.timeout.start();return tt(t),t}}var Zt=function(t,e){var n=M(),o=D();!e&&vt(L())&&(e=L()),Z(n),e&&(J(e),o.setAttribute("data-button-to-replace",e.className)),o.parentNode.insertBefore(o,e),mt([t,n],lt.loading)},Jt={},$t=!1,Xt={};function Gt(t){for(var e=t.target;e&&e!==document;e=e.parentNode)for(var n in Xt){var o=e.getAttribute(n);if(o)return void Xt[n].fire({template:o})}}function Qt(t){return Object.prototype.hasOwnProperty.call(ne,t)}function te(t){return ie[t]}function ee(t){for(var e in t)Qt(n=e)||ct('Unknown parameter "'.concat(n,'"')),t.toast&&(n=e,-1!==re.indexOf(n)&&ct('The parameter "'.concat(n,'" is incompatible with toasts'))),te(e=e)&&v(e,te(e));var n}var ne={title:"",titleText:"",text:"",html:"",footer:"",icon:void 0,iconColor:void 0,iconHtml:void 0,template:void 0,toast:!1,showClass:{popup:"swal2-show",backdrop:"swal2-backdrop-show",icon:"swal2-icon-show"},hideClass:{popup:"swal2-hide",backdrop:"swal2-backdrop-hide",icon:"swal2-icon-hide"},customClass:{},target:"body",backdrop:!0,heightAuto:!0,allowOutsideClick:!0,allowEscapeKey:!0,allowEnterKey:!0,stopKeydownPropagation:!0,keydownListenerCapture:!1,showConfirmButton:!0,showDenyButton:!1,showCancelButton:!1,preConfirm:void 0,preDeny:void 0,confirmButtonText:"OK",confirmButtonAriaLabel:"",confirmButtonColor:void 0,denyButtonText:"No",denyButtonAriaLabel:"",denyButtonColor:void 0,cancelButtonText:"Cancel",cancelButtonAriaLabel:"",cancelButtonColor:void 0,buttonsStyling:!0,reverseButtons:!1,focusConfirm:!0,focusDeny:!1,focusCancel:!1,returnFocus:!0,showCloseButton:!1,closeButtonHtml:"&times;",closeButtonAriaLabel:"Close this dialog",loaderHtml:"",showLoaderOnConfirm:!1,showLoaderOnDeny:!1,imageUrl:void 0,imageWidth:void 0,imageHeight:void 0,imageAlt:"",timer:void 0,timerProgressBar:!1,width:void 0,padding:void 0,background:void 0,input:void 0,inputPlaceholder:"",inputLabel:"",inputValue:"",inputOptions:{},inputAutoTrim:!0,inputAttributes:{},inputValidator:void 0,returnInputValueOnDeny:!1,validationMessage:void 0,grow:!1,position:"center",progressSteps:[],currentProgressStep:void 0,progressStepsDistance:void 0,willOpen:void 0,didOpen:void 0,didRender:void 0,willClose:void 0,didClose:void 0,didDestroy:void 0,scrollbarPadding:!0},oe=["allowEscapeKey","allowOutsideClick","background","buttonsStyling","cancelButtonAriaLabel","cancelButtonColor","cancelButtonText","closeButtonAriaLabel","closeButtonHtml","confirmButtonAriaLabel","confirmButtonColor","confirmButtonText","currentProgressStep","customClass","denyButtonAriaLabel","denyButtonColor","denyButtonText","didClose","didDestroy","footer","hideClass","html","icon","iconColor","iconHtml","imageAlt","imageHeight","imageUrl","imageWidth","progressSteps","returnFocus","reverseButtons","showCancelButton","showCloseButton","showConfirmButton","showDenyButton","text","title","titleText","willClose"],ie={},re=["allowOutsideClick","allowEnterKey","backdrop","focusConfirm","focusDeny","focusCancel","returnFocus","heightAuto","keydownListenerCapture"],ae=Object.freeze({isValidParameter:Qt,isUpdatableParameter:function(t){return-1!==oe.indexOf(t)},isDeprecatedParameter:te,argsToParams:function(n){var o={};return"object"!==r(n[0])||A(n[0])?["title","html","icon"].forEach(function(t,e){e=n[e];"string"==typeof e||A(e)?o[t]=e:void 0!==e&&g("Unexpected type of ".concat(t,'! Expected "string" or "Element", got ').concat(r(e)))}):s(o,n[0]),o},isVisible:function(){return vt(B())},clickConfirm:Ht,clickDeny:function(){return j()&&j().click()},clickCancel:function(){return I()&&I().click()},getContainer:x,getPopup:B,getTitle:E,getHtmlContainer:O,getImage:S,getIcon:P,getInputLabel:function(){return t(lt["input-label"])},getCloseButton:V,getActions:M,getConfirmButton:L,getDenyButton:j,getCancelButton:I,getLoader:D,getFooter:q,getTimerProgressBar:H,getFocusableElements:N,getValidationMessage:T,isLoading:function(){return B().hasAttribute("data-loading")},fire:function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return i(this,e)},mixin:function(r){return function(t){!function(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&l(t,e)}(i,t);var n,o,e=(n=i,o=d(),function(){var t,e=u(n);return p(this,o?(t=u(this).constructor,Reflect.construct(e,arguments,t)):e.apply(this,arguments))});function i(){return a(this,i),e.apply(this,arguments)}return c(i,[{key:"_main",value:function(t,e){return f(u(i.prototype),"_main",this).call(this,t,s({},r,e))}}]),i}(this)},showLoading:zt,enableLoading:zt,getTimerLeft:function(){return Jt.timeout&&Jt.timeout.getTimerLeft()},stopTimer:Kt,resumeTimer:Yt,toggleTimer:function(){var t=Jt.timeout;return t&&(t.running?Kt:Yt)()},increaseTimer:function(t){if(Jt.timeout){t=Jt.timeout.increase(t);return tt(t,!0),t}},isTimerRunning:function(){return Jt.timeout&&Jt.timeout.isRunning()},bindClickHandler:function(){Xt[0<arguments.length&&void 0!==arguments[0]?arguments[0]:"data-swal-template"]=this,$t||(document.body.addEventListener("click",Gt),$t=!0)}});function ce(){var t,e=Et.innerParams.get(this);e&&(t=Et.domCache.get(this),J(t.loader),pt()?e.icon&&Z(P()):se(t),ht([t.popup,t.actions],lt.loading),t.popup.removeAttribute("aria-busy"),t.popup.removeAttribute("data-loading"),t.confirmButton.disabled=!1,t.denyButton.disabled=!1,t.cancelButton.disabled=!1)}function se(t){var e=t.popup.getElementsByClassName(t.loader.getAttribute("data-button-to-replace"));e.length?Z(e[0],"inline-block"):vt(L())||vt(j())||vt(I())||J(t.actions)}function ue(){null===ft.previousBodyPadding&&document.body.scrollHeight>window.innerHeight&&(ft.previousBodyPadding=parseInt(window.getComputedStyle(document.body).getPropertyValue("padding-right")),document.body.style.paddingRight="".concat(ft.previousBodyPadding+function(){var t=document.createElement("div");t.className=lt["scrollbar-measure"],document.body.appendChild(t);var e=t.getBoundingClientRect().width-t.clientWidth;return document.body.removeChild(t),e}(),"px"))}var le=function(){navigator.userAgent.match(/(CriOS|FxiOS|EdgiOS|YaBrowser|UCBrowser)/i)||B().scrollHeight>window.innerHeight-44&&(x().style.paddingBottom="".concat(44,"px"))},de=function(){var e,t=x();t.ontouchstart=function(t){e=pe(t)},t.ontouchmove=function(t){e&&(t.preventDefault(),t.stopPropagation())}},pe=function(t){var e=t.target,n=x();return!fe(t)&&!me(t)&&(e===n||!(G(n)||"INPUT"===e.tagName||G(O())&&O().contains(e)))},fe=function(t){return t.touches&&t.touches.length&&"stylus"===t.touches[0].touchType},me=function(t){return t.touches&&1<t.touches.length},he={swalPromiseResolve:new WeakMap};function ge(t,e,n,o){pt()?Ce(t,o):(Wt(n).then(function(){return Ce(t,o)}),Jt.keydownTarget.removeEventListener("keydown",Jt.keydownHandler,{capture:Jt.keydownListenerCapture}),Jt.keydownHandlerAdded=!1),e.parentNode&&e.remove(),R()&&(null!==ft.previousBodyPadding&&(document.body.style.paddingRight="".concat(ft.previousBodyPadding,"px"),ft.previousBodyPadding=null),U(document.body,lt.iosfix)&&(e=parseInt(document.body.style.top,10),ht(document.body,lt.iosfix),document.body.style.top="",document.body.scrollTop=-1*e),h(document.body.children).forEach(function(t){t.hasAttribute("data-previous-aria-hidden")?(t.setAttribute("aria-hidden",t.getAttribute("data-previous-aria-hidden")),t.removeAttribute("data-previous-aria-hidden")):t.removeAttribute("aria-hidden")})),ht([document.documentElement,document.body],[lt.shown,lt["height-auto"],lt["no-backdrop"],lt["toast-shown"]])}function ve(t){var e,n,o,i=B();i&&(t=be(t),(e=Et.innerParams.get(this))&&!U(i,e.hideClass.popup)&&(n=he.swalPromiseResolve.get(this),ht(i,e.showClass.popup),mt(i,e.hideClass.popup),o=x(),ht(o,e.showClass.backdrop),mt(o,e.hideClass.backdrop),ye(this,i,e),n(t)))}function be(t){return void 0===t?{isConfirmed:!1,isDenied:!1,isDismissed:!0}:s({isConfirmed:!1,isDenied:!1,isDismissed:!1},t)}function ye(t,e,n){var o=x(),i=kt&&Q(e);b(n.willClose,e),i?we(t,e,o,n.returnFocus,n.didClose):ge(t,o,n.returnFocus,n.didClose)}var we=function(t,e,n,o,i){Jt.swalCloseEventFinishedCallback=ge.bind(null,t,n,o,i),e.addEventListener(kt,function(t){t.target===e&&(Jt.swalCloseEventFinishedCallback(),delete Jt.swalCloseEventFinishedCallback)})},Ce=function(t,e){setTimeout(function(){b(e),t._destroy()})};function ke(t,e,n){var o=Et.domCache.get(t);e.forEach(function(t){o[t].disabled=n})}function Ae(t,e){if(!t)return!1;if("radio"===t.type)for(var n=t.parentNode.parentNode.querySelectorAll("input"),o=0;o<n.length;o++)n[o].disabled=e;else t.disabled=e}var xe=function(){function n(t,e){a(this,n),this.callback=t,this.remaining=e,this.running=!1,this.start()}return c(n,[{key:"start",value:function(){return this.running||(this.running=!0,this.started=new Date,this.id=setTimeout(this.callback,this.remaining)),this.remaining}},{key:"stop",value:function(){return this.running&&(this.running=!1,clearTimeout(this.id),this.remaining-=new Date-this.started),this.remaining}},{key:"increase",value:function(t){var e=this.running;return e&&this.stop(),this.remaining+=t,e&&this.start(),this.remaining}},{key:"getTimerLeft",value:function(){return this.running&&(this.stop(),this.start()),this.remaining}},{key:"isRunning",value:function(){return this.running}}]),n}(),Be={email:function(t,e){return/^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9.-]+\.[a-zA-Z0-9-]{2,24}$/.test(t)?Promise.resolve():Promise.resolve(e||"Invalid email address")},url:function(t,e){return/^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._+~#=]{1,256}\.[a-z]{2,63}\b([-a-zA-Z0-9@:%_+.~#?&/=]*)$/.test(t)?Promise.resolve():Promise.resolve(e||"Invalid URL")}};function Pe(t){var e,n;(e=t).inputValidator||Object.keys(Be).forEach(function(t){e.input===t&&(e.inputValidator=Be[t])}),t.showLoaderOnConfirm&&!t.preConfirm&&ct("showLoaderOnConfirm is set to true, but preConfirm is not defined.\nshowLoaderOnConfirm should be used together with preConfirm, see usage example:\nhttps://sweetalert2.github.io/#ajax-request"),(n=t).target&&("string"!=typeof n.target||document.querySelector(n.target))&&("string"==typeof n.target||n.target.appendChild)||(ct('Target parameter is not valid, defaulting to "body"'),n.target="body"),"string"==typeof t.title&&(t.title=t.title.split("\n").join("<br />")),yt(t)}function Ee(t){var e=x(),n=B();b(t.willOpen,n);var o=window.getComputedStyle(document.body).overflowY;Ue(e,n,t),setTimeout(function(){Re(e,n)},10),R()&&(Fe(e,t.scrollbarPadding,o),h(document.body.children).forEach(function(t){t===x()||t.contains(x())||(t.hasAttribute("aria-hidden")&&t.setAttribute("data-previous-aria-hidden",t.getAttribute("aria-hidden")),t.setAttribute("aria-hidden","true"))})),pt()||Jt.previousActiveElement||(Jt.previousActiveElement=document.activeElement),setTimeout(function(){return b(t.didOpen,n)}),ht(e,lt["no-transition"])}function Oe(t){var e=B();t.target===e&&(t=x(),e.removeEventListener(kt,Oe),t.style.overflowY="auto")}function Se(t,e){t.closePopup({isConfirmed:!0,value:e})}function Te(t,e,n){var o=N();if(o.length)return(e+=n)===o.length?e=0:-1===e&&(e=o.length-1),o[e].focus();B().focus()}var Le=["swal-title","swal-html","swal-footer"],je=function(t){var n={};return h(t.querySelectorAll("swal-param")).forEach(function(t){Ne(t,["name","value"]);var e=t.getAttribute("name"),t=t.getAttribute("value");"boolean"==typeof ne[e]&&"false"===t&&(t=!1),"object"===r(ne[e])&&(t=JSON.parse(t)),n[e]=t}),n},De=function(t){var n={};return h(t.querySelectorAll("swal-button")).forEach(function(t){Ne(t,["type","color","aria-label"]);var e=t.getAttribute("type");n["".concat(e,"ButtonText")]=t.innerHTML,n["show".concat(m(e),"Button")]=!0,t.hasAttribute("color")&&(n["".concat(e,"ButtonColor")]=t.getAttribute("color")),t.hasAttribute("aria-label")&&(n["".concat(e,"ButtonAriaLabel")]=t.getAttribute("aria-label"))}),n},Ie=function(t){var e={},t=t.querySelector("swal-image");return t&&(Ne(t,["src","width","height","alt"]),t.hasAttribute("src")&&(e.imageUrl=t.getAttribute("src")),t.hasAttribute("width")&&(e.imageWidth=t.getAttribute("width")),t.hasAttribute("height")&&(e.imageHeight=t.getAttribute("height")),t.hasAttribute("alt")&&(e.imageAlt=t.getAttribute("alt"))),e},Me=function(t){var e={},t=t.querySelector("swal-icon");return t&&(Ne(t,["type","color"]),t.hasAttribute("type")&&(e.icon=t.getAttribute("type")),t.hasAttribute("color")&&(e.iconColor=t.getAttribute("color")),e.iconHtml=t.innerHTML),e},qe=function(t){var n={},e=t.querySelector("swal-input");e&&(Ne(e,["type","label","placeholder","value"]),n.input=e.getAttribute("type")||"text",e.hasAttribute("label")&&(n.inputLabel=e.getAttribute("label")),e.hasAttribute("placeholder")&&(n.inputPlaceholder=e.getAttribute("placeholder")),e.hasAttribute("value")&&(n.inputValue=e.getAttribute("value")));t=t.querySelectorAll("swal-input-option");return t.length&&(n.inputOptions={},h(t).forEach(function(t){Ne(t,["value"]);var e=t.getAttribute("value"),t=t.innerHTML;n.inputOptions[e]=t})),n},He=function(t,e){var n,o={};for(n in e){var i=e[n],r=t.querySelector(i);r&&(Ne(r,[]),o[i.replace(/^swal-/,"")]=r.innerHTML.trim())}return o},Ve=function(t){var e=Le.concat(["swal-param","swal-button","swal-image","swal-icon","swal-input","swal-input-option"]);h(t.children).forEach(function(t){t=t.tagName.toLowerCase();-1===e.indexOf(t)&&ct("Unrecognized element <".concat(t,">"))})},Ne=function(e,n){h(e.attributes).forEach(function(t){-1===n.indexOf(t.name)&&ct(['Unrecognized attribute "'.concat(t.name,'" on <').concat(e.tagName.toLowerCase(),">."),"".concat(n.length?"Allowed attributes are: ".concat(n.join(", ")):"To set the value, use HTML within the element.")])})},Re=function(t,e){kt&&Q(e)?(t.style.overflowY="hidden",e.addEventListener(kt,Oe)):t.style.overflowY="auto"},Fe=function(t,e,n){var o;(/iPad|iPhone|iPod/.test(navigator.userAgent)&&!window.MSStream||"MacIntel"===navigator.platform&&1<navigator.maxTouchPoints)&&!U(document.body,lt.iosfix)&&(o=document.body.scrollTop,document.body.style.top="".concat(-1*o,"px"),mt(document.body,lt.iosfix),de(),le()),e&&"hidden"!==n&&ue(),setTimeout(function(){t.scrollTop=0})},Ue=function(t,e,n){mt(t,n.showClass.backdrop),e.style.setProperty("opacity","0","important"),Z(e,"grid"),setTimeout(function(){mt(e,n.showClass.popup),e.style.removeProperty("opacity")},10),mt([document.documentElement,document.body],lt.shown),n.heightAuto&&n.backdrop&&!n.toast&&mt([document.documentElement,document.body],lt["height-auto"])},_e=function(t){return t.checked?1:0},ze=function(t){return t.checked?t.value:null},We=function(t){return t.files.length?null!==t.getAttribute("multiple")?t.files:t.files[0]:null},Ke=function(e,n){function o(t){return Ze[n.input](i,Je(t),n)}var i=B();w(n.inputOptions)||k(n.inputOptions)?(zt(L()),C(n.inputOptions).then(function(t){e.hideLoading(),o(t)})):"object"===r(n.inputOptions)?o(n.inputOptions):g("Unexpected type of inputOptions! Expected object, Map or Promise, got ".concat(r(n.inputOptions)))},Ye=function(e,n){var o=e.getInput();J(o),C(n.inputValue).then(function(t){o.value="number"===n.input?parseFloat(t)||0:"".concat(t),Z(o),o.focus(),e.hideLoading()}).catch(function(t){g("Error in inputValue promise: ".concat(t)),o.value="",Z(o),o.focus(),e.hideLoading()})},Ze={select:function(t,e,i){function o(t,e,n){var o=document.createElement("option");o.value=n,F(o,e),o.selected=$e(n,i.inputValue),t.appendChild(o)}var r=gt(t,lt.select);e.forEach(function(t){var e,n=t[0],t=t[1];Array.isArray(t)?((e=document.createElement("optgroup")).label=n,e.disabled=!1,r.appendChild(e),t.forEach(function(t){return o(e,t[1],t[0])})):o(r,t,n)}),r.focus()},radio:function(t,e,i){var r=gt(t,lt.radio);e.forEach(function(t){var e=t[0],n=t[1],o=document.createElement("input"),t=document.createElement("label");o.type="radio",o.name=lt.radio,o.value=e,$e(e,i.inputValue)&&(o.checked=!0);e=document.createElement("span");F(e,n),e.className=lt.label,t.appendChild(o),t.appendChild(e),r.appendChild(t)});e=r.querySelectorAll("input");e.length&&e[0].focus()}},Je=function n(o){var i=[];return"undefined"!=typeof Map&&o instanceof Map?o.forEach(function(t,e){"object"===r(t)&&(t=n(t)),i.push([e,t])}):Object.keys(o).forEach(function(t){var e=o[t];"object"===r(e)&&(e=n(e)),i.push([t,e])}),i},$e=function(t,e){return e&&e.toString()===t.toString()},Xe=function(t,e,n){var o=function(t,e){var n=t.getInput();if(!n)return null;switch(e.input){case"checkbox":return _e(n);case"radio":return ze(n);case"file":return We(n);default:return e.inputAutoTrim?n.value.trim():n.value}}(t,e);e.inputValidator?Ge(t,e,o,n):t.getInput().checkValidity()?("deny"===n?Qe:tn)(t,e,o):(t.enableButtons(),t.showValidationMessage(e.validationMessage))},Ge=function(e,n,o,i){e.disableInput(),Promise.resolve().then(function(){return C(n.inputValidator(o,n.validationMessage))}).then(function(t){e.enableButtons(),e.enableInput(),t?e.showValidationMessage(t):("deny"===i?Qe:tn)(e,n,o)})},Qe=function(e,t,n){t.showLoaderOnDeny&&zt(j()),t.preDeny?Promise.resolve().then(function(){return C(t.preDeny(n,t.validationMessage))}).then(function(t){!1===t?e.hideLoading():e.closePopup({isDenied:!0,value:void 0===t?n:t})}):e.closePopup({isDenied:!0,value:n})},tn=function(e,t,n){t.showLoaderOnConfirm&&zt(),t.preConfirm?(e.resetValidationMessage(),Promise.resolve().then(function(){return C(t.preConfirm(n,t.validationMessage))}).then(function(t){vt(T())||!1===t?e.hideLoading():Se(e,void 0===t?n:t)})):Se(e,n)},en=["ArrowRight","ArrowDown"],nn=["ArrowLeft","ArrowUp"],on=function(t,e,n){var o=Et.innerParams.get(t);o&&(o.stopKeydownPropagation&&e.stopPropagation(),"Enter"===e.key?rn(t,e,o):"Tab"===e.key?an(e,o):-1!==[].concat(en,nn).indexOf(e.key)?cn(e.key):"Escape"===e.key&&sn(e,o,n))},rn=function(t,e,n){e.isComposing||e.target&&t.getInput()&&e.target.outerHTML===t.getInput().outerHTML&&-1===["textarea","file"].indexOf(n.input)&&(Ht(),e.preventDefault())},an=function(t,e){for(var n=t.target,o=N(),i=-1,r=0;r<o.length;r++)if(n===o[r]){i=r;break}t.shiftKey?Te(0,i,-1):Te(0,i,1),t.stopPropagation(),t.preventDefault()},cn=function(t){-1!==[L(),j(),I()].indexOf(document.activeElement)&&(t=-1!==en.indexOf(t)?"nextElementSibling":"previousElementSibling",(t=document.activeElement[t])&&t.focus())},sn=function(t,e,n){y(e.allowEscapeKey)&&(t.preventDefault(),n(rt.esc))},un=function(e,t,n){t.popup.onclick=function(){var t=Et.innerParams.get(e);t.showConfirmButton||t.showDenyButton||t.showCancelButton||t.showCloseButton||t.timer||t.input||n(rt.close)}},ln=!1,dn=function(e){e.popup.onmousedown=function(){e.container.onmouseup=function(t){e.container.onmouseup=void 0,t.target===e.container&&(ln=!0)}}},pn=function(e){e.container.onmousedown=function(){e.popup.onmouseup=function(t){e.popup.onmouseup=void 0,t.target!==e.popup&&!e.popup.contains(t.target)||(ln=!0)}}},fn=function(n,o,i){o.container.onclick=function(t){var e=Et.innerParams.get(n);ln?ln=!1:t.target===o.container&&y(e.allowOutsideClick)&&i(rt.backdrop)}};function mn(t,e){var n=function(t){t="string"==typeof t.template?document.querySelector(t.template):t.template;if(!t)return{};t=t.content;return Ve(t),s(je(t),De(t),Ie(t),Me(t),qe(t),He(t,Le))}(t);return(t=s({},ne,e,n,t)).showClass=s({},ne.showClass,t.showClass),t.hideClass=s({},ne.hideClass,t.hideClass),t}function hn(a,c,s){return new Promise(function(t){function e(t){a.closePopup({isDismissed:!0,dismiss:t})}var n,o,i,r;he.swalPromiseResolve.set(a,t),c.confirmButton.onclick=function(){return e=s,(t=a).disableButtons(),void(e.input?Xe(t,e,"confirm"):tn(t,e,!0));var t,e},c.denyButton.onclick=function(){return e=s,(t=a).disableButtons(),void(e.returnInputValueOnDeny?Xe(t,e,"deny"):Qe(t,e,!1));var t,e},c.cancelButton.onclick=function(){return t=e,a.disableButtons(),void t(rt.cancel);var t},c.closeButton.onclick=function(){return e(rt.close)},n=a,r=c,t=e,Et.innerParams.get(n).toast?un(n,r,t):(dn(r),pn(r),fn(n,r,t)),o=a,r=s,i=e,(t=Jt).keydownTarget&&t.keydownHandlerAdded&&(t.keydownTarget.removeEventListener("keydown",t.keydownHandler,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!1),r.toast||(t.keydownHandler=function(t){return on(o,t,i)},t.keydownTarget=r.keydownListenerCapture?window:B(),t.keydownListenerCapture=r.keydownListenerCapture,t.keydownTarget.addEventListener("keydown",t.keydownHandler,{capture:t.keydownListenerCapture}),t.keydownHandlerAdded=!0),r=a,"select"===(t=s).input||"radio"===t.input?Ke(r,t):-1!==["text","email","number","tel","textarea"].indexOf(t.input)&&(w(t.inputValue)||k(t.inputValue))&&Ye(r,t),Ee(s),vn(Jt,s,e),bn(c,s),setTimeout(function(){c.container.scrollTop=0})})}function gn(t){var e={popup:B(),container:x(),actions:M(),confirmButton:L(),denyButton:j(),cancelButton:I(),loader:D(),closeButton:V(),validationMessage:T(),progressSteps:n()};return Et.domCache.set(t,e),e}var vn=function(t,e,n){var o=H();J(o),e.timer&&(t.timeout=new xe(function(){n("timer"),delete t.timeout},e.timer),e.timerProgressBar&&(Z(o),setTimeout(function(){t.timeout&&t.timeout.running&&tt(e.timer)})))},bn=function(t,e){if(!e.toast)return y(e.allowEnterKey)?void(yn(t,e)||Te(0,-1,1)):wn()},yn=function(t,e){return e.focusDeny&&vt(t.denyButton)?(t.denyButton.focus(),!0):e.focusCancel&&vt(t.cancelButton)?(t.cancelButton.focus(),!0):!(!e.focusConfirm||!vt(t.confirmButton))&&(t.confirmButton.focus(),!0)},wn=function(){document.activeElement&&b(document.activeElement.blur)};function Cn(t){delete t.params,delete Jt.keydownHandler,delete Jt.keydownTarget,An(Et),An(he)}var kn,An=function(t){for(var e in t)t[e]=new WeakMap},ut=Object.freeze({hideLoading:ce,disableLoading:ce,getInput:function(t){var e=Et.innerParams.get(t||this);return(t=Et.domCache.get(t||this))?z(t.popup,e.input):null},close:ve,closePopup:ve,closeModal:ve,closeToast:ve,enableButtons:function(){ke(this,["confirmButton","denyButton","cancelButton"],!1)},disableButtons:function(){ke(this,["confirmButton","denyButton","cancelButton"],!0)},enableInput:function(){return Ae(this.getInput(),!1)},disableInput:function(){return Ae(this.getInput(),!0)},showValidationMessage:function(t){var e=Et.domCache.get(this),n=Et.innerParams.get(this);F(e.validationMessage,t),e.validationMessage.className=lt["validation-message"],n.customClass&&n.customClass.validationMessage&&mt(e.validationMessage,n.customClass.validationMessage),Z(e.validationMessage),(e=this.getInput())&&(e.setAttribute("aria-invalid",!0),e.setAttribute("aria-describedBy",lt["validation-message"]),W(e),mt(e,lt.inputerror))},resetValidationMessage:function(){var t=Et.domCache.get(this);t.validationMessage&&J(t.validationMessage),(t=this.getInput())&&(t.removeAttribute("aria-invalid"),t.removeAttribute("aria-describedBy"),ht(t,lt.inputerror))},getProgressSteps:function(){return Et.domCache.get(this).progressSteps},_main:function(t){var e=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{};return ee(s({},e,t)),Jt.currentInstance&&Jt.currentInstance._destroy(),Jt.currentInstance=this,Pe(t=mn(t,e)),Object.freeze(t),Jt.timeout&&(Jt.timeout.stop(),delete Jt.timeout),clearTimeout(Jt.restoreFocusTimeout),e=gn(this),qt(this,t),Et.innerParams.set(this,t),hn(this,e,t)},update:function(e){var t=B(),n=Et.innerParams.get(this);if(!t||U(t,n.hideClass.popup))return ct("You're trying to update the closed or closing popup, that won't work. Use the update() method in preConfirm parameter or show a new popup.");var o={};Object.keys(e).forEach(function(t){Bn.isUpdatableParameter(t)?o[t]=e[t]:ct('Invalid parameter to update: "'.concat(t,'". Updatable params are listed here: https://github.com/sweetalert2/sweetalert2/blob/master/src/utils/params.js\n\nIf you think this parameter should be updatable, request it here: https://github.com/sweetalert2/sweetalert2/issues/new?template=02_feature_request.md'))}),n=s({},n,o),qt(this,n),Et.innerParams.set(this,n),Object.defineProperties(this,{params:{value:s({},this.params,e),writable:!1,enumerable:!0}})},_destroy:function(){var t=Et.domCache.get(this),e=Et.innerParams.get(this);e&&(t.popup&&Jt.swalCloseEventFinishedCallback&&(Jt.swalCloseEventFinishedCallback(),delete Jt.swalCloseEventFinishedCallback),Jt.deferDisposalTimer&&(clearTimeout(Jt.deferDisposalTimer),delete Jt.deferDisposalTimer),b(e.didDestroy),Cn(this))}}),xn=function(){function i(){if(a(this,i),"undefined"!=typeof window){kn=this;for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];var o=Object.freeze(this.constructor.argsToParams(e));Object.defineProperties(this,{params:{value:o,writable:!1,enumerable:!0,configurable:!0}});o=this._main(this.params);Et.promise.set(this,o)}}return c(i,[{key:"then",value:function(t){return Et.promise.get(this).then(t)}},{key:"finally",value:function(t){return Et.promise.get(this).finally(t)}}]),i}();s(xn.prototype,ut),s(xn,ae),Object.keys(ut).forEach(function(t){xn[t]=function(){if(kn)return kn[t].apply(kn,arguments)}}),xn.DismissReason=rt,xn.version="11.0.4";var Bn=xn;return Bn.default=Bn}),void 0!==this&&this.Sweetalert2&&(this.swal=this.sweetAlert=this.Swal=this.SweetAlert=this.Sweetalert2); "undefined"!=typeof document&&function(e,t){var n=e.createElement("style");if(e.getElementsByTagName("head")[0].appendChild(n),n.styleSheet)n.styleSheet.disabled||(n.styleSheet.cssText=t);else try{n.innerHTML=t}catch(e){n.innerText=t}}(document,".swal2-popup.swal2-toast{box-sizing:border-box;grid-column:1/4!important;grid-row:1/4!important;grid-template-columns:1fr 99fr 1fr;padding:1em;overflow-y:hidden;background:#fff;box-shadow:0 0 .625em #d9d9d9}.swal2-popup.swal2-toast>*{grid-column:2}.swal2-popup.swal2-toast .swal2-title{margin:1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-loading{justify-content:center}.swal2-popup.swal2-toast .swal2-input{height:2em;margin:.5em;font-size:1em}.swal2-popup.swal2-toast .swal2-validation-message{font-size:1em}.swal2-popup.swal2-toast .swal2-footer{margin:.5em 0 0;padding:.5em 0 0;font-size:.8em}.swal2-popup.swal2-toast .swal2-close{grid-column:3/3;grid-row:1/99;align-self:center;width:.8em;height:.8em;margin:0;font-size:2em}.swal2-popup.swal2-toast .swal2-html-container{margin:1em;padding:0;font-size:1em;text-align:initial}.swal2-popup.swal2-toast .swal2-html-container:empty{padding:0}.swal2-popup.swal2-toast .swal2-loader{grid-column:1;grid-row:1/99;align-self:center;width:2em;height:2em;margin:.25em}.swal2-popup.swal2-toast .swal2-icon{grid-column:1;grid-row:1/99;align-self:center;width:2em;min-width:2em;height:2em;margin:0 .5em 0 0}.swal2-popup.swal2-toast .swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:1.8em;font-weight:700}.swal2-popup.swal2-toast .swal2-icon.swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line]{top:.875em;width:1.375em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:.3125em}.swal2-popup.swal2-toast .swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:.3125em}.swal2-popup.swal2-toast .swal2-actions{justify-content:flex-start;height:auto;margin:0;margin-top:.3125em;padding:0}.swal2-popup.swal2-toast .swal2-styled{margin:.25em .5em;padding:.4em .6em;font-size:1em}.swal2-popup.swal2-toast .swal2-styled:focus{box-shadow:0 0 0 1px #fff,0 0 0 3px rgba(100,150,200,.5)}.swal2-popup.swal2-toast .swal2-success{border-color:#a5dc86}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line]{position:absolute;width:1.6em;height:3em;transform:rotate(45deg);border-radius:50%}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.8em;left:-.5em;transform:rotate(-45deg);transform-origin:2em 2em;border-radius:4em 0 0 4em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.25em;left:.9375em;transform-origin:0 1.5em;border-radius:0 4em 4em 0}.swal2-popup.swal2-toast .swal2-success .swal2-success-ring{width:2em;height:2em}.swal2-popup.swal2-toast .swal2-success .swal2-success-fix{top:0;left:.4375em;width:.4375em;height:2.6875em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line]{height:.3125em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=tip]{top:1.125em;left:.1875em;width:.75em}.swal2-popup.swal2-toast .swal2-success [class^=swal2-success-line][class$=long]{top:.9375em;right:.1875em;width:1.375em}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-toast-animate-success-line-tip .75s;animation:swal2-toast-animate-success-line-tip .75s}.swal2-popup.swal2-toast .swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-toast-animate-success-line-long .75s;animation:swal2-toast-animate-success-line-long .75s}.swal2-popup.swal2-toast.swal2-show{-webkit-animation:swal2-toast-show .5s;animation:swal2-toast-show .5s}.swal2-popup.swal2-toast.swal2-hide{-webkit-animation:swal2-toast-hide .1s forwards;animation:swal2-toast-hide .1s forwards}.swal2-container{display:grid;position:fixed;z-index:1060;top:0;right:0;bottom:0;left:0;box-sizing:border-box;grid-template-areas:\"top-start top top-end\" \"center-start center center-end\" \"bottom-start bottom-center bottom-end\" \"gap gap gap\";grid-template-rows:auto auto auto .625em;height:100%;padding:.625em .625em 0;overflow-x:hidden;transition:background-color .1s;-webkit-overflow-scrolling:touch}.swal2-container::after{content:\"\";grid-column:1/4;grid-row:4;height:.625em}.swal2-container.swal2-backdrop-show,.swal2-container.swal2-noanimation{background:rgba(0,0,0,.4)}.swal2-container.swal2-backdrop-hide{background:0 0!important}.swal2-container.swal2-bottom-start,.swal2-container.swal2-center-start,.swal2-container.swal2-top-start{grid-template-columns:minmax(0,1fr) auto auto}.swal2-container.swal2-bottom,.swal2-container.swal2-center,.swal2-container.swal2-top{grid-template-columns:auto minmax(0,1fr) auto}.swal2-container.swal2-bottom-end,.swal2-container.swal2-center-end,.swal2-container.swal2-top-end{grid-template-columns:auto auto minmax(0,1fr)}.swal2-container.swal2-top-start>.swal2-popup{align-self:start}.swal2-container.swal2-top>.swal2-popup{grid-column:2;align-self:start;justify-self:center}.swal2-container.swal2-top-end>.swal2-popup,.swal2-container.swal2-top-right>.swal2-popup{grid-column:3;align-self:start;justify-self:end}.swal2-container.swal2-center-left>.swal2-popup,.swal2-container.swal2-center-start>.swal2-popup{grid-row:2;align-self:center}.swal2-container.swal2-center>.swal2-popup{grid-column:2;grid-row:2;align-self:center;justify-self:center}.swal2-container.swal2-center-end>.swal2-popup,.swal2-container.swal2-center-right>.swal2-popup{grid-column:3;grid-row:2;align-self:center;justify-self:end}.swal2-container.swal2-bottom-left>.swal2-popup,.swal2-container.swal2-bottom-start>.swal2-popup{grid-column:1;grid-row:3;align-self:end}.swal2-container.swal2-bottom>.swal2-popup{grid-column:2;grid-row:3;justify-self:center;align-self:end}.swal2-container.swal2-bottom-end>.swal2-popup,.swal2-container.swal2-bottom-right>.swal2-popup{grid-column:3;grid-row:3;align-self:end;justify-self:end}.swal2-container.swal2-grow-fullscreen>.swal2-popup,.swal2-container.swal2-grow-row>.swal2-popup{grid-column:1/4;width:100%}.swal2-container.swal2-grow-column>.swal2-popup,.swal2-container.swal2-grow-fullscreen>.swal2-popup{grid-row:1/4;align-self:stretch}.swal2-container.swal2-no-transition{transition:none!important}.swal2-popup{display:none;position:relative;box-sizing:border-box;width:32em;max-width:100%;padding:0 0 1.25em;border:none;border-radius:5px;background:#fff;font-family:inherit;font-size:1rem}.swal2-popup:focus{outline:0}.swal2-popup.swal2-loading{overflow-y:hidden}.swal2-title{position:relative;max-width:100%;margin:0;padding:.8em 1em 0;color:#595959;font-size:1.875em;font-weight:600;text-align:center;text-transform:none;word-wrap:break-word}.swal2-actions{display:flex;z-index:1;box-sizing:border-box;flex-wrap:wrap;align-items:center;justify-content:center;width:100%;margin:1.25em auto 0;padding:0}.swal2-actions:not(.swal2-loading) .swal2-styled[disabled]{opacity:.4}.swal2-actions:not(.swal2-loading) .swal2-styled:hover{background-image:linear-gradient(rgba(0,0,0,.1),rgba(0,0,0,.1))}.swal2-actions:not(.swal2-loading) .swal2-styled:active{background-image:linear-gradient(rgba(0,0,0,.2),rgba(0,0,0,.2))}.swal2-loader{display:none;align-items:center;justify-content:center;width:2.2em;height:2.2em;margin:0 1.875em;-webkit-animation:swal2-rotate-loading 1.5s linear 0s infinite normal;animation:swal2-rotate-loading 1.5s linear 0s infinite normal;border-width:.25em;border-style:solid;border-radius:100%;border-color:#2778c4 transparent #2778c4 transparent}.swal2-styled{margin:.3125em;padding:.625em 1.1em;transition:box-shadow .1s;box-shadow:0 0 0 3px transparent;font-weight:500}.swal2-styled:not([disabled]){cursor:pointer}.swal2-styled.swal2-confirm{border:0;border-radius:.25em;background:initial;background-color:#7367f0;color:#fff;font-size:1em}.swal2-styled.swal2-confirm:focus{box-shadow:0 0 0 3px rgba(115,103,240,.5)}.swal2-styled.swal2-deny{border:0;border-radius:.25em;background:initial;background-color:#ea5455;color:#fff;font-size:1em}.swal2-styled.swal2-deny:focus{box-shadow:0 0 0 3px rgba(234,84,85,.5)}.swal2-styled.swal2-cancel{border:0;border-radius:.25em;background:initial;background-color:#6e7d88;color:#fff;font-size:1em}.swal2-styled.swal2-cancel:focus{box-shadow:0 0 0 3px rgba(110,125,136,.5)}.swal2-styled.swal2-default-outline:focus{box-shadow:0 0 0 3px rgba(100,150,200,.5)}.swal2-styled:focus{outline:0}.swal2-styled::-moz-focus-inner{border:0}.swal2-footer{justify-content:center;margin:1em 0 0;padding:1em 1em 0;border-top:1px solid #eee;color:#545454;font-size:1em}.swal2-timer-progress-bar-container{position:absolute;right:0;bottom:0;left:0;grid-column:auto!important;height:.25em;overflow:hidden;border-bottom-right-radius:5px;border-bottom-left-radius:5px}.swal2-timer-progress-bar{width:100%;height:.25em;background:rgba(0,0,0,.2)}.swal2-image{max-width:100%;margin:2em auto 1em}.swal2-close{z-index:2;align-items:center;justify-content:center;width:1.2em;height:1.2em;margin-top:0;margin-right:0;margin-bottom:-1.2em;padding:0;overflow:hidden;transition:color .1s,box-shadow .1s;border:none;border-radius:5px;background:0 0;color:#ccc;font-family:serif;font-family:monospace;font-size:2.5em;cursor:pointer;justify-self:end}.swal2-close:hover{transform:none;background:0 0;color:#f27474}.swal2-close:focus{outline:0;box-shadow:inset 0 0 0 3px rgba(100,150,200,.5)}.swal2-close::-moz-focus-inner{border:0}.swal2-html-container{z-index:1;justify-content:center;margin:0;padding:1em 1.6em .3em;color:#545454;font-size:1.125em;font-weight:400;line-height:normal;text-align:center;word-wrap:break-word}.swal2-checkbox,.swal2-file,.swal2-input,.swal2-radio,.swal2-select,.swal2-textarea{margin:1em 2em 0}.swal2-file,.swal2-input,.swal2-textarea{box-sizing:border-box;width:auto;transition:border-color .1s,box-shadow .1s;border:1px solid #d9d9d9;border-radius:.1875em;background:inherit;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px transparent;color:inherit;font-size:1.125em}.swal2-file.swal2-inputerror,.swal2-input.swal2-inputerror,.swal2-textarea.swal2-inputerror{border-color:#f27474!important;box-shadow:0 0 2px #f27474!important}.swal2-file:focus,.swal2-input:focus,.swal2-textarea:focus{border:1px solid #b4dbed;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.06),0 0 0 3px rgba(100,150,200,.5)}.swal2-file::-moz-placeholder,.swal2-input::-moz-placeholder,.swal2-textarea::-moz-placeholder{color:#ccc}.swal2-file:-ms-input-placeholder,.swal2-input:-ms-input-placeholder,.swal2-textarea:-ms-input-placeholder{color:#ccc}.swal2-file::placeholder,.swal2-input::placeholder,.swal2-textarea::placeholder{color:#ccc}.swal2-range{margin:1em 2em 0;background:#fff}.swal2-range input{width:80%}.swal2-range output{width:20%;color:inherit;font-weight:600;text-align:center}.swal2-range input,.swal2-range output{height:2.625em;padding:0;font-size:1.125em;line-height:2.625em}.swal2-input{height:2.625em;padding:0 .75em}.swal2-input[type=number]{max-width:10em}.swal2-file{width:75%;margin-right:auto;margin-left:auto;background:inherit;font-size:1.125em}.swal2-textarea{height:6.75em;padding:.75em}.swal2-select{min-width:50%;max-width:100%;padding:.375em .625em;background:inherit;color:inherit;font-size:1.125em}.swal2-checkbox,.swal2-radio{align-items:center;justify-content:center;background:#fff;color:inherit}.swal2-checkbox label,.swal2-radio label{margin:0 .6em;font-size:1.125em}.swal2-checkbox input,.swal2-radio input{flex-shrink:0;margin:0 .4em}.swal2-input-label{display:flex;justify-content:center;margin:1em auto 0}.swal2-validation-message{align-items:center;justify-content:center;margin:1em 0 0;padding:.625em;overflow:hidden;background:#f0f0f0;color:#666;font-size:1em;font-weight:300}.swal2-validation-message::before{content:\"!\";display:inline-block;width:1.5em;min-width:1.5em;height:1.5em;margin:0 .625em;border-radius:50%;background-color:#f27474;color:#fff;font-weight:600;line-height:1.5em;text-align:center}.swal2-icon{position:relative;box-sizing:content-box;justify-content:center;width:5em;height:5em;margin:2.5em auto .6em;border:.25em solid transparent;border-radius:50%;border-color:#000;font-family:inherit;line-height:5em;cursor:default;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.swal2-icon .swal2-icon-content{display:flex;align-items:center;font-size:3.75em}.swal2-icon.swal2-error{border-color:#f27474;color:#f27474}.swal2-icon.swal2-error .swal2-x-mark{position:relative;flex-grow:1}.swal2-icon.swal2-error [class^=swal2-x-mark-line]{display:block;position:absolute;top:2.3125em;width:2.9375em;height:.3125em;border-radius:.125em;background-color:#f27474}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=left]{left:1.0625em;transform:rotate(45deg)}.swal2-icon.swal2-error [class^=swal2-x-mark-line][class$=right]{right:1em;transform:rotate(-45deg)}.swal2-icon.swal2-error.swal2-icon-show{-webkit-animation:swal2-animate-error-icon .5s;animation:swal2-animate-error-icon .5s}.swal2-icon.swal2-error.swal2-icon-show .swal2-x-mark{-webkit-animation:swal2-animate-error-x-mark .5s;animation:swal2-animate-error-x-mark .5s}.swal2-icon.swal2-warning{border-color:#facea8;color:#f8bb86}.swal2-icon.swal2-info{border-color:#9de0f6;color:#3fc3ee}.swal2-icon.swal2-question{border-color:#c9dae1;color:#87adbd}.swal2-icon.swal2-success{border-color:#a5dc86;color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-circular-line]{position:absolute;width:3.75em;height:7.5em;transform:rotate(45deg);border-radius:50%}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=left]{top:-.4375em;left:-2.0635em;transform:rotate(-45deg);transform-origin:3.75em 3.75em;border-radius:7.5em 0 0 7.5em}.swal2-icon.swal2-success [class^=swal2-success-circular-line][class$=right]{top:-.6875em;left:1.875em;transform:rotate(-45deg);transform-origin:0 3.75em;border-radius:0 7.5em 7.5em 0}.swal2-icon.swal2-success .swal2-success-ring{position:absolute;z-index:2;top:-.25em;left:-.25em;box-sizing:content-box;width:100%;height:100%;border:.25em solid rgba(165,220,134,.3);border-radius:50%}.swal2-icon.swal2-success .swal2-success-fix{position:absolute;z-index:1;top:.5em;left:1.625em;width:.4375em;height:5.625em;transform:rotate(-45deg)}.swal2-icon.swal2-success [class^=swal2-success-line]{display:block;position:absolute;z-index:2;height:.3125em;border-radius:.125em;background-color:#a5dc86}.swal2-icon.swal2-success [class^=swal2-success-line][class$=tip]{top:2.875em;left:.8125em;width:1.5625em;transform:rotate(45deg)}.swal2-icon.swal2-success [class^=swal2-success-line][class$=long]{top:2.375em;right:.5em;width:2.9375em;transform:rotate(-45deg)}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-tip{-webkit-animation:swal2-animate-success-line-tip .75s;animation:swal2-animate-success-line-tip .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-line-long{-webkit-animation:swal2-animate-success-line-long .75s;animation:swal2-animate-success-line-long .75s}.swal2-icon.swal2-success.swal2-icon-show .swal2-success-circular-line-right{-webkit-animation:swal2-rotate-success-circular-line 4.25s ease-in;animation:swal2-rotate-success-circular-line 4.25s ease-in}.swal2-progress-steps{flex-wrap:wrap;align-items:center;max-width:100%;margin:1.25em auto;padding:0;background:inherit;font-weight:600}.swal2-progress-steps li{display:inline-block;position:relative}.swal2-progress-steps .swal2-progress-step{z-index:20;flex-shrink:0;width:2em;height:2em;border-radius:2em;background:#2778c4;color:#fff;line-height:2em;text-align:center}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step{background:#2778c4}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step{background:#add8e6;color:#fff}.swal2-progress-steps .swal2-progress-step.swal2-active-progress-step~.swal2-progress-step-line{background:#add8e6}.swal2-progress-steps .swal2-progress-step-line{z-index:10;flex-shrink:0;width:2.5em;height:.4em;margin:0 -1px;background:#2778c4}[class^=swal2]{-webkit-tap-highlight-color:transparent}.swal2-show{-webkit-animation:swal2-show .3s;animation:swal2-show .3s}.swal2-hide{-webkit-animation:swal2-hide .15s forwards;animation:swal2-hide .15s forwards}.swal2-noanimation{transition:none}.swal2-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}.swal2-rtl .swal2-close{margin-right:initial;margin-left:0}.swal2-rtl .swal2-timer-progress-bar{right:0;left:auto}@-webkit-keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@keyframes swal2-toast-show{0%{transform:translateY(-.625em) rotateZ(2deg)}33%{transform:translateY(0) rotateZ(-2deg)}66%{transform:translateY(.3125em) rotateZ(2deg)}100%{transform:translateY(0) rotateZ(0)}}@-webkit-keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@keyframes swal2-toast-hide{100%{transform:rotateZ(1deg);opacity:0}}@-webkit-keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@keyframes swal2-toast-animate-success-line-tip{0%{top:.5625em;left:.0625em;width:0}54%{top:.125em;left:.125em;width:0}70%{top:.625em;left:-.25em;width:1.625em}84%{top:1.0625em;left:.75em;width:.5em}100%{top:1.125em;left:.1875em;width:.75em}}@-webkit-keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@keyframes swal2-toast-animate-success-line-long{0%{top:1.625em;right:1.375em;width:0}65%{top:1.25em;right:.9375em;width:0}84%{top:.9375em;right:0;width:1.125em}100%{top:.9375em;right:.1875em;width:1.375em}}@-webkit-keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@keyframes swal2-show{0%{transform:scale(.7)}45%{transform:scale(1.05)}80%{transform:scale(.95)}100%{transform:scale(1)}}@-webkit-keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@keyframes swal2-hide{0%{transform:scale(1);opacity:1}100%{transform:scale(.5);opacity:0}}@-webkit-keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@keyframes swal2-animate-success-line-tip{0%{top:1.1875em;left:.0625em;width:0}54%{top:1.0625em;left:.125em;width:0}70%{top:2.1875em;left:-.375em;width:3.125em}84%{top:3em;left:1.3125em;width:1.0625em}100%{top:2.8125em;left:.8125em;width:1.5625em}}@-webkit-keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@keyframes swal2-animate-success-line-long{0%{top:3.375em;right:2.875em;width:0}65%{top:3.375em;right:2.875em;width:0}84%{top:2.1875em;right:0;width:3.4375em}100%{top:2.375em;right:.5em;width:2.9375em}}@-webkit-keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@keyframes swal2-rotate-success-circular-line{0%{transform:rotate(-45deg)}5%{transform:rotate(-45deg)}12%{transform:rotate(-405deg)}100%{transform:rotate(-405deg)}}@-webkit-keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@keyframes swal2-animate-error-x-mark{0%{margin-top:1.625em;transform:scale(.4);opacity:0}50%{margin-top:1.625em;transform:scale(.4);opacity:0}80%{margin-top:-.375em;transform:scale(1.15)}100%{margin-top:0;transform:scale(1);opacity:1}}@-webkit-keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@keyframes swal2-animate-error-icon{0%{transform:rotateX(100deg);opacity:0}100%{transform:rotateX(0);opacity:1}}@-webkit-keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes swal2-rotate-loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow:hidden}body.swal2-height-auto{height:auto!important}body.swal2-no-backdrop .swal2-container{top:auto;right:auto;bottom:auto;left:auto;max-width:calc(100% - .625em * 2);background-color:transparent!important}body.swal2-no-backdrop .swal2-container>.swal2-modal{box-shadow:0 0 10px rgba(0,0,0,.4)}body.swal2-no-backdrop .swal2-container.swal2-top{top:0;left:50%;transform:translateX(-50%)}body.swal2-no-backdrop .swal2-container.swal2-top-left,body.swal2-no-backdrop .swal2-container.swal2-top-start{top:0;left:0}body.swal2-no-backdrop .swal2-container.swal2-top-end,body.swal2-no-backdrop .swal2-container.swal2-top-right{top:0;right:0}body.swal2-no-backdrop .swal2-container.swal2-center{top:50%;left:50%;transform:translate(-50%,-50%)}body.swal2-no-backdrop .swal2-container.swal2-center-left,body.swal2-no-backdrop .swal2-container.swal2-center-start{top:50%;left:0;transform:translateY(-50%)}body.swal2-no-backdrop .swal2-container.swal2-center-end,body.swal2-no-backdrop .swal2-container.swal2-center-right{top:50%;right:0;transform:translateY(-50%)}body.swal2-no-backdrop .swal2-container.swal2-bottom{bottom:0;left:50%;transform:translateX(-50%)}body.swal2-no-backdrop .swal2-container.swal2-bottom-left,body.swal2-no-backdrop .swal2-container.swal2-bottom-start{bottom:0;left:0}body.swal2-no-backdrop .swal2-container.swal2-bottom-end,body.swal2-no-backdrop .swal2-container.swal2-bottom-right{right:0;bottom:0}@media print{body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown){overflow-y:scroll!important}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown)>[aria-hidden=true]{display:none}body.swal2-shown:not(.swal2-no-backdrop):not(.swal2-toast-shown) .swal2-container{position:static!important}}body.swal2-toast-shown .swal2-container{box-sizing:border-box;width:360px;max-width:100%;background-color:transparent}body.swal2-toast-shown .swal2-container.swal2-top{top:0;right:auto;bottom:auto;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-top-end,body.swal2-toast-shown .swal2-container.swal2-top-right{top:0;right:0;bottom:auto;left:auto}body.swal2-toast-shown .swal2-container.swal2-top-left,body.swal2-toast-shown .swal2-container.swal2-top-start{top:0;right:auto;bottom:auto;left:0}body.swal2-toast-shown .swal2-container.swal2-center-left,body.swal2-toast-shown .swal2-container.swal2-center-start{top:50%;right:auto;bottom:auto;left:0;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-center{top:50%;right:auto;bottom:auto;left:50%;transform:translate(-50%,-50%)}body.swal2-toast-shown .swal2-container.swal2-center-end,body.swal2-toast-shown .swal2-container.swal2-center-right{top:50%;right:0;bottom:auto;left:auto;transform:translateY(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-left,body.swal2-toast-shown .swal2-container.swal2-bottom-start{top:auto;right:auto;bottom:0;left:0}body.swal2-toast-shown .swal2-container.swal2-bottom{top:auto;right:auto;bottom:0;left:50%;transform:translateX(-50%)}body.swal2-toast-shown .swal2-container.swal2-bottom-end,body.swal2-toast-shown .swal2-container.swal2-bottom-right{top:auto;right:0;bottom:0;left:auto}");
import mxnet as mx import numpy as np import argparse caffe_flag = True try: import caffe from caffe.proto import caffe_pb2 except ImportError: caffe_flag = False import caffe_parse.caffe_pb2 def protoBlobFileToND(proto_file): data = '' file = open(proto_file, "r") if not file: raise Exception("ERROR (" + proto_file + ")!") data = file.read() file.close() if caffe_flag: mean_blob = caffe.proto.caffe_pb2.BlobProto() else: mean_blob = caffe_parse.caffe_pb2.BlobProto() mean_blob.ParseFromString(data) img_mean_np = np.array(mean_blob.data) img_mean_np = img_mean_np.reshape( mean_blob.channels, mean_blob.height, mean_blob.width ) # swap channels from Caffe BGR to RGB img_mean_np2 = img_mean_np img_mean_np[0] = img_mean_np2[2] img_mean_np[2] = img_mean_np2[0] return mx.nd.array(img_mean_np) def main(): parser = argparse.ArgumentParser(description='Caffe prototxt to mxnet model parameter converter.\ Note that only basic functions are implemented. You are welcomed to contribute to this file.') parser.add_argument('mean_image_proto', help='The protobuf file in Caffe format') parser.add_argument('save_name', help='The name of the output file prefix') args = parser.parse_args() nd = protoBlobFileToND(args.mean_image_proto) mx.nd.save(args.save_name + ".nd", {"mean_image": nd}) if __name__ == '__main__': main()
#!/usr/bin/env python3 # Copyright (c) 2018 Arm Limited and Contributors. All rights reserved. # # SPDX-License-Identifier: BSD-3-Clause """Select action handler.""" from mbl.cli.utils import device, file_handler from . import list_action def execute(args): """Entry point for the select command.""" list_of_devices = list_action.execute(args) user_input = input("\nSelect a device from the list: ") try: user_input = int(user_input) if user_input <= 0: raise ValueError selected_device = list_of_devices[user_input - 1] name, addr = selected_device.split(": ") except (ValueError, IndexError): raise IndexError("Enter a valid device index as shown in the list.") else: dev = device.create_device(name, addr) file_handler.save_device_info(dev)
import Modal from './modal.js'; //Importa a função const modal = Modal(); //Guarda a função na constante. //Mapeando para usar modal para confirmar leitura também const modalTitle = document.querySelector('.modal h2'); const modalDescription = document.querySelector('.modal p'); const modalButton = document.querySelector('.modal button'); const checkButton = document.querySelectorAll('.actions a.check'); checkButton.forEach(element => { element.addEventListener('click', handleClick); }); //Quando o botão delete for clicado abre a modal para então confirmar const deleteButton = document.querySelectorAll('.actions a.delete'); deleteButton.forEach(element => { element.addEventListener('click', (event) => handleClick(event, false)); }); function handleClick(event, check = true) { event.preventDefault(); //Bloqueia o formulário para nao mudar de página. const text = check ? "Deseja marcar como lida" : "Tem certeza que você deseja excluir"; const slug = check ? "check" : "delete"; const roomId = document.querySelector('#room-id').dataset.id; const questionId = event.target.dataset.id; const form = document.querySelector('.modal form'); form.setAttribute('action', `/question/${roomId}/${questionId}/${slug}`); modalTitle.innerHTML = check ? "Marcar pergunta como lida" : "Excluir pergunta"; modalDescription.innerHTML = check ? `${text} esta pergunta?` : `${text} esta pergunta?`; modalButton.textContent = check ? "Sim, marcar" : "Sim, excluir"; check ? modalButton.classList.remove('red') : modalButton.classList.add('red'); modal.open(); } function copyToClipboard() { // let numRoom = document.querySelector('#room-id'); console.log('chegou aqui'); }
'use strict'; // parser.js tests const { expect } = require('chai'); const parser = require('../app/util/parser'); // Tests describe('parser.js tests', () => { it('should check if parser can parse a given file', (done) => { // Parse const data = parser.loadConfig('config/config.yml'); // Check expect((data)).to.be.a('object'); done(); }); });
import React from "react"; import Box from "@mui/material/Box"; import Tabs from "@mui/material/Tabs"; import Tab from "@mui/material/Tab"; import { Routes, Route, useNavigate, useLocation } from "react-router-dom"; import ChangePasswordPage from "./ChangePasswordPage"; import ProfilePage from "./ProfilePage"; import PaymentMethods from "./PaymentMethods"; const SettingsPage = () => { const { pathname } = useLocation(); const navigate = useNavigate(); const [value, setValue] = React.useState("profile"); const handleChange = (event, newValue) => { setValue(newValue); navigate(newValue); }; React.useEffect(() => { const path = pathname.split("/").pop(); setValue(path); }, [pathname]); return ( <Box sx={{ flexGrow: 1 }}> <Box sx={{ width: "100%", bgcolor: "#ffffff" }}> <Tabs value={value} onChange={handleChange}> <Tab label="Profile" value="profile" /> <Tab label="Change Password" value="change-password" /> <Tab label="Payment Methods" value="payment-methods" /> </Tabs> </Box> <Routes> <Route index element={<Settings />} /> <Route path="change-password" element={<ChangePasswordPage />} /> <Route path="profile" element={<ProfilePage />} /> <Route path="payment-methods" element={<PaymentMethods />} /> </Routes> </Box> ); }; export default SettingsPage; const Settings = () => { const navigate = useNavigate(); React.useEffect(() => { navigate("profile"); }, []); return null; };
// Generated on 2014-05-20 using generator-angular 0.8.0 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { var modRewrite = require('connect-modrewrite'); var serveStatic = require('serve-static'); // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), env: { dev: { OPENSENSEMAP_API_URL: 'https://api.testing.opensensemap.org', OPENSENSEMAP_MAPTILES_URL: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', } }, replace: { control: { options: { usePrefix: false, patterns: [ { match: 'controls', replacement: 'controls="map.controls"' } ] }, files: [ {expand: true, flatten: true, src: ['<%= yeoman.dist %>/views/explore2.map.html'], dest: '<%= yeoman.dist %>/views/'} ] }, urls: { options: { patterns: [ { match: 'OPENSENSEMAP_API_URL', replacement: '<%= OPENSENSEMAP_API_URL %>' }, { match: 'OPENSENSEMAP_MAPTILES_URL', replacement: '<%= OPENSENSEMAP_MAPTILES_URL %>' }, { match: 'VERSION', replacement: '<%= pkg.version %>' }, { match: 'REVISION', replacement: '<%= gitinfo.local.branch.current.shortSHA %>' } ] }, files: [ {expand: true, flatten: true, src: ['<%= yeoman.dist %>/scripts/*.scripts.js'], dest: '<%= yeoman.dist %>/scripts/'} ] }, devapi: { options: { patterns: [ { match: 'OPENSENSEMAP_API_URL', replacement: '<%= OPENSENSEMAP_API_URL %>' } ] }, files: [ {expand: true, flatten: true, src: ['.tmp/scripts/constants.js'], dest: '.tmp/scripts'}, {expand: true, flatten: true, src: ['.tmp/scripts/services/opensensemapapi.js'], dest: '.tmp/scripts/services'} ] }, devmaps: { options: { patterns: [ { match: 'OPENSENSEMAP_MAPTILES_URL', replacement: '<%= OPENSENSEMAP_MAPTILES_URL %>' } ] }, files: [ {expand: true, flatten: true, src: ['.tmp/components/leaflet.directive.js'], dest: '.tmp/components'} ] }, version: { options: { patterns: [ { match: 'VERSION', replacement: '<%= pkg.version %>' }, { match: 'REVISION', replacement: '<%= gitinfo.local.branch.current.shortSHA %>' } ] }, files: [ {expand: true, flatten: true, src: ['.tmp/scripts/constants.js'], dest: '.tmp/scripts'} ] } }, // Project settings yeoman: { // configurable paths app: require('./bower.json').appPath || 'app', dist: 'dist' }, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['bowerInstall'] }, js: { files: [ '<%= yeoman.app %>/scripts/{,*/}*.js', '<%= yeoman.app %>/components/{,*/}*.js' ], tasks: ['newer:jshint:all'], options: { livereload: true } }, //jsTest: { // files: ['test/spec/{,*/}*.js'], // tasks: ['newer:jshint:test', 'karma'] //}, styles: { files: ['<%= yeoman.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, html: { files: ['<%= yeoman.app %>/index.html'], tasks: ['languages'], }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= yeoman.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= yeoman.app %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' ] }, devs: { files: [ '<%= yeoman.app %>/scripts/controllers/map.js', '<%= yeoman.app %>/scripts/controllers/register.js', // '<%= yeoman.app %>/scripts/services/opensenseboxapi.js', '<%= yeoman.app %>/scripts/services/opensensemapapi.js', '<%= yeoman.app %>/scripts/services/map.js', '<%= yeoman.app %>/components/leaflet.directive.js', '<%= yeoman.app %>/components/charts.directive.js', '<%= yeoman.app %>/components/calendar.directive.js', '<%= yeoman.app %>/components/badge.directive.js' ], tasks: [ // 'newer:copy:api', 'newer:copy:apinew', 'newer:copy:maps', 'replace:devapi', 'newer:copy:components', 'replace:devmaps' ], options: { livereload: true } } }, // The actual grunt server settings connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: '0.0.0.0', livereload: 35729, base: 'app' }, livereload: { options: { open: true, base: [ '.tmp', '<%= yeoman.app %>' ], middleware: function(connect, options) { var middlewares = []; middlewares.push(modRewrite(['!\\.html|\\.js|\\.css|\\.svg|\\.jp(e?)g|\\.png|\\.woff2|\\.gif|\\.ttf$ /index.html'])); options.base.forEach(function(base) { middlewares.push(serveStatic(base)); }); return middlewares; } } }, test: { options: { port: 9001, base: [ '.tmp', 'test', '<%= yeoman.app %>' ] } }, dist: { options: { base: '<%= yeoman.dist %>' } } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= yeoman.app %>/scripts/{,*/}*.js' ], test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/spec/{,*/}*.js'] } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= yeoman.dist %>/*', '!<%= yeoman.dist %>/.git*' ] }] }, server: '.tmp' }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['last 1 version'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the app bowerInstall: { app: { src: ['<%= yeoman.app %>/index.html'], ignorePath: '<%= yeoman.app %>/' } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= yeoman.dist %>/scripts/{,*/}*.js', '<%= yeoman.dist %>/scripts/{,*/}*.js.map', '<%= yeoman.dist %>/styles/{,*/}*.css', '<%= yeoman.dist %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '!<%= yeoman.dist %>/images/placeholder.png', '<%= yeoman.dist %>/styles/fonts/*' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { html: '<%= yeoman.app %>/index.html', options: { dest: '<%= yeoman.dist %>', flow: { html: { steps: { js: ['concat'], css: ['cssmin'] }, post: {} } } } }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { html: ['<%= yeoman.dist %>/{,*/}*.html'], css: ['<%= yeoman.dist %>/styles/{,*/}*.css'], options: { assetsDirs: ['<%= yeoman.dist %>'], blockReplacements: { js: function (block){ console.log(block.dest); return '<script defer src="' + block.dest + '"><\/script>'; } } } }, imagemin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.{png,jpg,jpeg}', dest: '<%= yeoman.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= yeoman.app %>/images', src: '{,*/}*.svg', dest: '<%= yeoman.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseWhitespace: true, collapseBooleanAttributes: true, removeCommentsFromCDATA: true, removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= yeoman.dist %>', src: ['*.html', 'views/{,*/}*.html'], dest: '<%= yeoman.dist %>' }] } }, ngAnnotate: { options: { add: true, singleQuotes: true }, dist: { files: [ { expand: true, src: ['<%= yeoman.dist %>/scripts/scripts.js'] }, { expand: true, src: ['<%= yeoman.dist %>/translations/angular/*.js'] } ] } }, uglify: { options: { mangle: true, sourceMap: true }, dist: { files: [ { expand: true, src: ['<%= yeoman.dist %>/scripts/*.js'] }, { expand: true, src: ['<%= yeoman.dist %>/translations/angular/*.js'] } ] } }, // Copies remaining files to places other tasks can use copy: { translations: { files: [ { expand: true, cwd: 'node_modules/@sensebox/opensensemap-i18n/dist', dest: '.tmp/translations', src: ['de_DE.json', 'en_US.json'] }, { expand: true, cwd: 'node_modules/angular-i18n/', dest: '.tmp/translations/angular', src: ['angular-locale_{<%= pkg.languages %>}.js'] } ] }, dist: { files: [{ expand: true, dot: true, cwd: '<%= yeoman.app %>', dest: '<%= yeoman.dist %>', src: [ '*.{ico,png,txt}', '.htaccess', '*.html', 'views/{,*/}*.html', 'components/{,*/}*.html', 'images/{,*/}*.{webp}', 'images/{,*/}*.{gif}', 'fonts/*.*', 'fonts/webfonts/*.*' ] }, { expand: true, cwd: 'node_modules/@sensebox/opensensemap-i18n/dist', dest: 'dist/translations', src: ['{,*/}*.json'] }, { expand: true, cwd: 'node_modules/angular-i18n/', dest: 'dist/translations/angular', src: ['angular-locale_{<%= pkg.languages %>}.js'] }, { expand: true, cwd: '.tmp/images', dest: '<%= yeoman.dist %>/images', src: ['generated/*'] }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/bower_components/leaflet/dist', src: ['images/*.*'], dest: '<%= yeoman.dist %>/styles/' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/bower_components/font-awesome', src: ['fonts/*.*'], dest: '<%= yeoman.dist %>' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap-css-only', src: ['fonts/*.*'], dest: '<%= yeoman.dist %>' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/bower_components/bootstrap-languages', src: ['languages.png'], dest: '<%= yeoman.dist %>/styles/' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/images', src: ['*.gif'], dest: '<%= yeoman.dist %>/images/' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/images', src: ['*.jpg'], dest: '<%= yeoman.dist %>/images/' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/images', src: ['*.png'], dest: '<%= yeoman.dist %>/images/' }, { expand: true, dot: true, cwd: '<%= yeoman.app %>/bower_components/Leaflet.awesome-markers/dist', src: ['images/*.*'], dest: '<%= yeoman.dist %>/styles/' }] }, styles: { expand: true, cwd: '<%= yeoman.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' }, app: { expand: true, cwd: '<%= yeoman.app %>/scripts', dest: '.tmp/scripts', src: ['app.js', 'constants.js'] }, components: { expand: true, cwd: '<%= yeoman.app %>/components', dest: '.tmp/components', src: ['{,*/}*.js'] }, // api: { // expand: true, // cwd: '<%= yeoman.app %>/scripts/services', // dest: '.tmp/scripts/services', // src: ['opensenseboxapi.js', 'map.js'] // }, apinew: { expand: true, cwd: '<%= yeoman.app %>/scripts/services', dest: '.tmp/scripts/services', src: 'opensensemapapi.js' }, maps: { expand: true, cwd: '<%= yeoman.app %>/scripts/controllers', dest: '.tmp/scripts/controllers', src: ['map.js', 'register.js'] }, images: { expand: true, cwd: '<%= yeoman.app %>/images', dest: '.tmp/images', src: 'favicon.svg' } }, // gzip html, css and js files compress: { gzip: { options: { mode: 'gzip' }, files: [ {expand: true, src: ['dist/*.html'], dest: './', ext: '.html.gz'}, {expand: true, src: ['dist/views/*.html'], dest: './', extDot: 'last', ext:'.html.gz'}, {expand: true, src: ['dist/scripts/*.vendor.js'], dest: './', extDot: 'last', ext: '.js.gz'}, {expand: true, src: ['dist/scripts/*.scripts.js'], dest: './', extDot: 'last', ext: '.js.gz'}, {expand: true, src: ['dist/styles/*.css'], dest: './', extDot: 'last', ext: '.css.gz'}, {expand: true, src: ['dist/translations/angular/*.js'], dest: './', extDot: 'last', ext: '.js.gz'}, {expand: true, src: ['dist/translations/*.json'], dest: './', extDot: 'last', ext: '.json.gz'}, {expand: true, src: ['dist/images/**/*.png'], dest: './', extDot: 'last', ext: '.png.gz'}, {expand: true, src: ['dist/styles/images/*.png'], dest: './', extDot: 'last', ext: '.png.gz'}, {expand: true, src: ['dist/images/*.svg'], dest: './', extDot: 'last', ext: '.svg.gz'} ] }, brotli: { options: { mode: 'brotli' }, files: [ {expand: true, src: ['dist/*.html'], dest: './', ext: '.html.br'}, {expand: true, src: ['dist/views/*.html'], dest: './', extDot: 'last', ext:'.html.br'}, {expand: true, src: ['dist/scripts/*.vendor.js'], dest: './', extDot: 'last', ext: '.js.br'}, {expand: true, src: ['dist/scripts/*.scripts.js'], dest: './', extDot: 'last', ext: '.js.br'}, {expand: true, src: ['dist/styles/*.css'], dest: './', extDot: 'last', ext: '.css.br'}, {expand: true, src: ['dist/translations/angular/*.js'], dest: './', extDot: 'last', ext: '.js.br'}, {expand: true, src: ['dist/translations/*.json'], dest: './', extDot: 'last', ext: '.json.br'}, {expand: true, src: ['dist/images/**/*.png'], dest: './', extDot: 'last', ext: '.png.br'}, {expand: true, src: ['dist/styles/images/*.png'], dest: './', extDot: 'last', ext: '.png.br'}, {expand: true, src: ['dist/images/*.svg'], dest: './', extDot: 'last', ext: '.svg.br'} ] } }, // Run some tasks in parallel to speed up the build process concurrent: { server: [ 'copy:styles', 'copy:app', 'copy:components', // 'copy:api', 'copy:apinew', 'copy:maps', 'copy:images', 'copy:translations' ], test: [ 'copy:styles' ], dist: [ 'copy:styles', 'imagemin', 'svgmin' ] }, // Test settings karma: { unit: { configFile: 'test/karma-unit.conf.js', singleRun: true } } }); grunt.registerTask('serve', function (target) { if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'env:dev', 'loadconst', 'bowerInstall', 'concurrent:server', 'autoprefixer', 'replace:devapi', 'replace:devmaps', 'gitinfo', 'replace:version', 'languages', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run(['serve:' + target]); }); grunt.registerTask('loadconst', 'Load constants', function(target) { console.log("Load constants: ", process.env.OPENSENSEMAP_API_URL, process.env.OPENSENSEMAP_MAPTILES_URL); grunt.config('OPENSENSEMAP_API_URL', process.env.OPENSENSEMAP_API_URL); grunt.config('OPENSENSEMAP_MAPTILES_URL', process.env.OPENSENSEMAP_MAPTILES_URL); }); grunt.registerTask('test', [ 'clean:server', 'concurrent:test', 'autoprefixer', 'connect:test', // 'karma' ]); grunt.registerTask('testBuild', ['env:dev', 'build']); grunt.registerTask('build', [ 'clean:dist', 'loadconst', 'gitinfo', 'bowerInstall', 'useminPrepare', 'concurrent:dist', 'copy:dist', 'autoprefixer', 'concat', 'languages', 'ngAnnotate', 'cssmin', 'rev', 'uglify', 'usemin', 'htmlmin', 'replace:control', 'replace:urls', 'compress' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); grunt.registerTask('languages','',function () { var target = grunt.option('target'); var translationsFolder = '.tmp/translations/'; var targetFile = '.tmp/index.html'; if (target === 'build' || target === 'testBuild') { translationsFolder = 'dist/translations/'; targetFile = 'dist/index.html'; } var fs = require('fs'); var done = this.async(); fs.readFile('app/index.html', 'utf8', function (err,data) { if (err) { return console.log(err); } var html = ''; grunt.file.recurse(translationsFolder, function(abspath, rootdir, subdir, filename){ if (subdir !== undefined) { return; } if (filename.indexOf('disabled') === -1) { var languageCode = filename.split('.')[0]; var language = languageCode.split('_')[0]; html += '<li><a ng-click="header.changeLang(\''+languageCode+'\')"><span class="lang-sm lang-lbl-full" lang="'+language+'"></span></a></li>'; } }); var resultStart = data.split('<!-- languages-start -->'); var resultEnd = data.split('<!-- languages-end -->'); var res = resultStart[0] + '<!-- languages-start -->' + html + '<!-- languages-end -->' + resultEnd[1]; fs.writeFile(targetFile, res, 'utf8', function (err) { if (err) { return console.log(err); } // grunt.file.copy('.tmp/index.html','app/index.html'); done(); }); }); }); };
import React from 'react'; import Footer from './Footer'; import Header from './Header'; const firebaseConfig = { apiKey: 'AIzaSyBMUDD8WupWFaz3y9sT7R0IB_HyjgWzYuY', authDomain: 'protab-8fb31.firebaseapp.com', databaseURL: 'https://protab-8fb31.firebaseio.com', projectId: 'protab-8fb31', storageBucket: 'protab-8fb31.appspot.com', messagingSenderId: '659614032004', appId: '1:659614032004:web:6f686f6245abd980a8a2d1', measurementId: 'G-TC5D0341G6' }; const initFirebse = async () => { if (location.pathname.indexOf('uninstall') === -1 || location.search.length < 2) return; try { import('firebase').then(firebase => { firebase.initializeApp(firebaseConfig); const db = firebase.database(); const data = getData(); db.ref() .child('uninstalls') .push(data); }); } catch (e) { console.log(' error in analytics ', e); } }; const getData = () => { const search = location.search; let [str1 = '', str2 = ''] = search.substring(1, search.length).split('&'); const [key1, value1] = str1.split('='); const [key2, value2] = str2.split('='); const data = { timestamp: Date.now(), date: new Date().toUTCString() }; if (key1 && value1) { data[key1] = value1; } if (key2 && value2) { data[key2] = value2; } return data; }; const Layout = ({ children }) => { React.useEffect(() => { initFirebse(); }, []); return ( <> <Header /> <main className="text-gray-900">{children}</main> <Footer /> </> ); }; export default Layout;
import React from 'react' class PriceTag extends React.Component { render() { let priceClass = "price-tag"; if (parseFloat(this.props.currencyPrice) < 0) { priceClass += " green"; } else { priceClass += " red" } return( <div className="price-block"> <span id="currency-type" className="price-label"> {/* <i className="fab fa-btc"></i> */} { this.props.currencyType + ": " } </span> <span id="currency-price" className={priceClass}>{ this.props.currencyPrice }%</span> </div> ); } } export default PriceTag;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.music = void 0; var music = { "viewBox": "0 0 20 20", "children": [{ "name": "path", "attribs": { "d": "M18.405,2.799C18.293,2.359,17.749,2,17.195,2H2.805c-0.555,0-1.099,0.359-1.21,0.799L1.394,4h17.211L18.405,2.799z\r\n\t M19.412,5H0.587C0.245,5-0.022,5.294,0.01,5.635l0.923,11.669C0.971,17.698,1.303,18,1.699,18H18.3\r\n\tc0.397,0,0.728-0.302,0.766-0.696l0.923-11.669C20.022,5.294,19.754,5,19.412,5z M11.942,12.521c-0.128,0.265-0.258,0.279-0.202,0\r\n\tc0.146-0.721,0.047-2.269-1.043-2.441v3.294c0,0.674-0.311,1.262-1.136,1.528c-0.802,0.256-1.699-0.011-1.908-0.586\r\n\tc-0.21-0.576,0.261-1.276,1.052-1.564c0.442-0.161,0.954-0.203,1.299-0.07V8h0.694C10.697,9.633,13.516,9.275,11.942,12.521z" } }] }; exports.music = music;
# -*- coding: utf-8 -*- ########################################################################### # Copyright (c), The AiiDA team. All rights reserved. # # This file is part of the AiiDA code. # # # # The code is hosted on GitHub at https://github.com/aiidateam/aiida-core # # For further information on the license, see the LICENSE.txt file # # For further information please visit http://www.aiida.net # ########################################################################### # pylint: disable=redefined-outer-name """Tests for the :class:`aiida.orm.nodes.data.data:Data` class.""" import os import numpy import pytest from aiida import orm, plugins from tests.static import STATIC_DIR @pytest.fixture @pytest.mark.usefixtures('aiida_profile_clean') def generate_class_instance(): # pylint: disable=too-many-return-statements, too-many-statements """Generate a dummy `Data` instance for the given sub class.""" def _generate_class_instance(data_class): if data_class is orm.CifData: instance = data_class(file=os.path.join(STATIC_DIR, 'data', 'Si.cif')) return instance if data_class is orm.UpfData: filename = os.path.join(STATIC_DIR, 'pseudos', 'Ba.pbesol-spn-rrkjus_psl.0.2.3-tot-pslib030.UPF') instance = data_class(file=filename) return instance if data_class is orm.StructureData: instance = orm.CifData(file=os.path.join(STATIC_DIR, 'data', 'Si.cif')).get_structure() return instance if data_class is orm.BandsData: kpoints = orm.KpointsData() kpoints.set_cell([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) kpoints.set_kpoints([[0., 0., 0.], [0.1, 0.1, 0.1]]) instance = data_class() instance.set_kpointsdata(kpoints) instance.set_bands([[1.0, 2.0], [3.0, 4.0]]) return instance if data_class is orm.TrajectoryData: instance = data_class() stepids = numpy.array([60]) times = stepids * 0.01 cells = numpy.array([[[3., 0., 0.], [0., 3., 0.], [0., 0., 3.]]]) positions = numpy.array([[[0., 0., 0.]]]) instance.set_trajectory(stepids=stepids, cells=cells, symbols=['H'], positions=positions, times=times) return instance if data_class is orm.UpfData: filepath_base = os.path.abspath(os.path.join(STATIC_DIR, 'pseudos')) filepath_carbon = os.path.join(filepath_base, 'C_pbe_v1.2.uspp.F.UPF') instance = data_class(file=filepath_carbon) return instance if data_class is orm.ArrayData: instance = data_class() array_data = numpy.identity(3) instance.set_array('data', array_data) instance.set_array('contains_nan_inf', numpy.array([float('NaN'), float('Inf')])) return instance if data_class is orm.KpointsData: instance = data_class() cell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] instance.set_cell(cell) instance.set_kpoints_mesh_from_density(0.5) return instance if data_class is orm.XyData: instance = data_class() instance.set_x(numpy.arange(5), 'xdata', 'm') instance.set_y(numpy.arange(5), 'ydata', 'm') return instance if data_class is orm.ProjectionData: my_real_hydrogen_dict = { 'angular_momentum': -3, 'diffusivity': None, 'kind_name': 'As', 'magnetic_number': 0, 'position': [-1.420047044832945, 1.420047044832945, 1.420047044832945], 'radial_nodes': 0, 'spin': 0, 'spin_orientation': None, 'x_orientation': None, 'z_orientation': None } kpoints = orm.KpointsData() kpoints.set_cell([[1, 0, 0], [0, 1, 0], [0, 0, 1]]) kpoints.set_kpoints([[0., 0., 0.]]) bands = orm.BandsData() bands.set_kpointsdata(kpoints) bands.set_bands([[1.0]]) RealHydrogen = plugins.OrbitalFactory('core.realhydrogen') # pylint: disable=invalid-name orbital = RealHydrogen(**my_real_hydrogen_dict) instance = data_class() instance.set_reference_bandsdata(bands) instance.set_projectiondata( orbital, list_of_pdos=numpy.asarray([1.0]), list_of_energy=numpy.asarray([1.0]), bands_check=False ) return instance raise RuntimeError( 'no instance generator implemented for class `{}`. If you have added a `_prepare_*` method ' 'for this data class, add a generator of a dummy instance here'.format(data_class) ) return _generate_class_instance @pytest.fixture(scope='function', params=plugins.get_entry_points('aiida.data')) def data_plugin(request): """Fixture that parametrizes over all the registered entry points of the ``aiida.data`` entry point group.""" return request.param.load() @pytest.mark.usefixtures('aiida_profile_clean') def test_constructor(): """Test the constructor. Specifically, verify that the ``source`` attribute can be set through a keyword argument. """ source = {'id': 1} node = orm.Data(source=source) assert isinstance(node, orm.Data) assert node.source == source @pytest.mark.usefixtures('aiida_profile_clean') def test_data_exporters(data_plugin, generate_class_instance): """Verify that the return value of the export methods of all `Data` sub classes have the correct type. It should be a tuple where the first should be a byte string and the second a dictionary. """ export_formats = data_plugin.get_export_formats() if not export_formats: return instance = generate_class_instance(data_plugin) for fileformat in export_formats: content, dictionary = instance._exportcontent(fileformat) # pylint: disable=protected-access assert isinstance(content, bytes) assert isinstance(dictionary, dict)
/** * Sign in action types. */ export const TRY_TO_SIGN_IN = "TRY_TO_SIGN_IN"; export const SUCCEDED_TO_SIGN_IN = "SUCCEDED_TO_SIGN_IN"; export const FAILED_TO_SIGN_IN = "FAILED_TO_SIGN_IN"; /** * Sign out action types. */ export const TRY_TO_SIGN_OUT = "TRY_TO_SIGN_OUT"; export const SUCCEDED_TO_SIGN_OUT = "SUCCEDED_TO_SIGN_OUT"; export const FAILED_TO_SIGN_OUT = "FAILED_TO_SIGN_OUT"; /** * Room creation action types. */ export const TRY_TO_CREATE_ROOM = "TRY_TO_CREATE_ROOM"; export const SUCCEDED_TO_CREATE_ROOM = "SUCCEDED_TO_CREATE_ROOM"; export const FAILED_TO_CREATE_ROOM = "FAILED_TO_CREATE_ROOM"; /** * Messaging action types. */ export const TRY_TO_SEND_MESSAGE = "TRY_TO_SEND_MESSAGE"; export const SUCCEDED_TO_SEND_MESSAGE = "SUCCEDED_TO_SEND_MESSAGE"; export const FAILED_TO_SEND_MESSAGE = "FAILED_TO_SEND_MESSAGE"; /** * Room member action types. */ export const TRY_TO_ADD_ROOM_MEMBER = "TRY_TO_ADD_ROOM_MEMBER"; export const SUCCEDED_TO_ADD_ROOM_MEMBER = "SUCCEDED_TO_ADD_ROOM_MEMBER"; export const FAILED_TO_ADD_ROOM_MEMBER = "FAILED_TO_ADD_ROOM_MEMBER"; export const TRY_TO_REMOVE_ROOM_MEMBER = "TRY_TO_REMOVE_ROOM_MEMBER"; export const SUCCEDED_TO_REMOVE_ROOM_MEMBER = "SUCCEDED_TO_REMOVE_ROOM_MEMBER"; export const FAILED_TO_REMOVE_ROOM_MEMBER = "FAILED_TO_REMOVE_ROOM_MEMBER";
import rdkit.Chem.AllChem as rdkit def test_get_atoms(case_data): """ Test :meth:`.Molecule.get_atoms`. Parameters ---------- case_data : :class:`.CaseData` A test case. Holds the molecule to test and the correct SMILES. Returns ------- None : :class:`NoneType` """ _test_get_atoms(case_data.molecule, case_data.smiles) def _test_get_atoms(molecule, smiles): """ Test :meth:`.Molecule.get_atoms`. Parameters ---------- molecule : :class:`.Molecule` The molecule to test. smiles : :class:`str` The correct SMILES of `molecule`. Returns ------- None : :class:`NoneType` """ # get_rdkit_mol() tests get_atoms() and get_bonds(), if those are # broken, the produced rdkit molecule will not have the expected # smiles. result = rdkit.MolToSmiles(get_rdkit_mol(molecule)) # Printing is useful for debugging. print(result) assert result == smiles def get_rdkit_mol(molecule): rdkit_mol = rdkit.EditableMol(rdkit.Mol()) for atom in molecule.get_atoms(): rdkit_atom = rdkit.Atom(atom.get_atomic_number()) rdkit_atom.SetFormalCharge(atom.get_charge()) rdkit_mol.AddAtom(rdkit_atom) for bond in molecule.get_bonds(): rdkit_mol.AddBond( beginAtomIdx=bond.get_atom1().get_id(), endAtomIdx=bond.get_atom2().get_id(), order=( rdkit.BondType.DATIVE if bond.get_order() == 9 else rdkit.BondType(bond.get_order()) ), ) return rdkit_mol.GetMol()
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import React from "react"; import ReactDOM from "react-dom"; import {Route, IndexRoute, Link} from "react-router"; import Relay from "react-relay"; import injectTapEventPlugin from 'react-tap-event-plugin'; import {Relask, RedirectComponent} from "babel-loader!relask"; import "style!css!normalize.css/normalize.css"; import "style!css!./4008.css"; import Index from "./pages/Index"; import Login from "./pages/Login"; import Contact from "./pages/Contact"; import Users from "./pages/Users"; injectTapEventPlugin(); const props = { queries: {viewer: () => Relay.QL` query { viewer }`}, render: ({done, element, error, events, props, retry, routerProps, stale}) => { if (error) { for (let e of error.source.errors) { if (e.message == '401: Unauthorized') { return <RedirectComponent to={'/login?next=' + routerProps.location.pathname}/>; } else if (e.message == '403: Forbidden') { return ( <div> <h1>Forbidden</h1> <p>Access denied.</p> </div> ); } } } else if (props) { return React.cloneElement(element, props); } else { return (<div>Loading</div>); } } }; ReactDOM.render(( <MuiThemeProvider> <Relask> <Route path="/"> <IndexRoute {...props} component={Index}/> <Route {...props} path="/login" component={Login}/> <Route {...props} path="/contact" component={Contact}/> <Route {...props} path="/users" component={Users}/> </Route> </Relask> </MuiThemeProvider> ), document.getElementById('app'));
''' This program should be executed after the tagParse execution is done. Before running this program, please execute the following statements in PostgreSQL to create tables. This program is to parse the labelled_by relationship of the Stack Overflow network. -------------------------------------------------------------- create table labelled_by( Qid int, Tid int, foreign key (Qid) references question (Qid), foreign key (Tid) references tag (Tid)); -------------------------------------------------------------- @author: keshan ''' import xml.sax import time import psycopg2 rcount = 0 class TagLabelExecuter: def __init__(self, dataArray, conn, cur): self.questionId = dataArray[0] self.tagLabel = dataArray[1] print "questionId" + self.questionId + "tagLabel"+self.tagLabel self.dataInsert(conn, cur) def dataInsert(self, conn, cur): cur = conn.cursor() #print("SELECT tid FROM tag WHERE tag_label = %s",(self.tagLabel,)) cur.execute("SELECT tid FROM tag WHERE tag_label = %s",(self.tagLabel,)) rows = cur.fetchone() print rows tagId = str(rows[0]) global rcount rcount += 1 cur.execute("INSERT INTO labelled_by VALUES(%s, %s)" % (self.questionId, tagId)) conn.commit() class StackContentHandler(xml.sax.ContentHandler): def __init__(self): xml.sax.ContentHandler.__init__(self) # get values from file def startElement(self, name, attrs): # only 'row' contains elements if name != "row": return # get post type:1 is question, 2 is answer ptype = "null" if attrs.has_key("PostTypeId"): ptype = attrs.getValue("PostTypeId") # question's typeId is 1 if ptype != '1': return questionId = 'null' if attrs.has_key("Id"): questionId = attrs.getValue("Id") if attrs.has_key("Tags"): if (self.checkQuestion(questionId)): #split Tags into several parts, maximum 5 parts tagList = ((attrs.getValue("Tags"))[1:-1]).split("><") for each_tag in tagList: if(self.checkTag(each_tag)): answerData = [] answerData.append(questionId) answerData.append(each_tag) TagLabelExecuter(answerData, conn, cur) print("added ", rcount, " labelled_by records into database") def checkQuestion (self, qusID): #print("Shit",qusID) cur = conn.cursor() cur.execute("SELECT Qid FROM question WHERE Qid = %s",(qusID,)) return cur.fetchone() is not None def checkTag (self, tag): #print("Shit",tag) cur = conn.cursor() cur.execute("SELECT tid FROM tag WHERE tag_label = %s",(tag,)) return cur.fetchone() is not None db = "heft" dbUser = "keshan" dbPort = 5432 conn = psycopg2.connect(database=db, user=dbUser, port=dbPort) cur = conn.cursor() #Here is the path of the raw data file f = open('/media/keshan/66C24863C2483A17/Data/Posts.xml') before_time = time.time() xml.sax.parse(f, StackContentHandler()) conn.close() cur.close() print("Total Data Transfer time is: ", (time.time() - before_time)/60) f.close()
/*! * Copyright 2010 LearnBoost <dev@learnboost.com> * * 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. */ /** * Module dependencies. */ var crypto = require('crypto') , parse = require('url').parse ; /** * Valid keys. */ var keys = [ 'acl' , 'location' , 'logging' , 'notification' , 'partNumber' , 'policy' , 'requestPayment' , 'torrent' , 'uploadId' , 'uploads' , 'versionId' , 'versioning' , 'versions' , 'website' ] /** * Return an "Authorization" header value with the given `options` * in the form of "AWS <key>:<signature>" * * @param {Object} options * @return {String} * @api private */ function authorization (options) { return 'AWS ' + options.key + ':' + sign(options) } module.exports = authorization module.exports.authorization = authorization /** * Simple HMAC-SHA1 Wrapper * * @param {Object} options * @return {String} * @api private */ function hmacSha1 (options) { return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') } module.exports.hmacSha1 = hmacSha1 /** * Create a base64 sha1 HMAC for `options`. * * @param {Object} options * @return {String} * @api private */ function sign (options) { options.message = stringToSign(options) return hmacSha1(options) } module.exports.sign = sign /** * Create a base64 sha1 HMAC for `options`. * * Specifically to be used with S3 presigned URLs * * @param {Object} options * @return {String} * @api private */ function signQuery (options) { options.message = queryStringToSign(options) return hmacSha1(options) } module.exports.signQuery= signQuery /** * Return a string for sign() with the given `options`. * * Spec: * * <verb>\n * <md5>\n * <content-type>\n * <date>\n * [headers\n] * <resource> * * @param {Object} options * @return {String} * @api private */ function stringToSign (options) { var headers = options.amazonHeaders || '' if (headers) headers += '\n' var r = [ options.verb , options.md5 , options.contentType , options.date ? options.date.toUTCString() : '' , headers + options.resource ] return r.join('\n') } module.exports.queryStringToSign = stringToSign /** * Return a string for sign() with the given `options`, but is meant exclusively * for S3 presigned URLs * * Spec: * * <date>\n * <resource> * * @param {Object} options * @return {String} * @api private */ function queryStringToSign (options){ return 'GET\n\n\n' + options.date + '\n' + options.resource } module.exports.queryStringToSign = queryStringToSign /** * Perform the following: * * - ignore non-amazon headers * - lowercase fields * - sort lexicographically * - trim whitespace between ":" * - join with newline * * @param {Object} headers * @return {String} * @api private */ function canonicalizeHeaders (headers) { var buf = [] , fields = Object.keys(headers) ; for (var i = 0, len = fields.length; i < len; ++i) { var field = fields[i] , val = headers[field] , field = field.toLowerCase() ; if (0 !== field.indexOf('x-amz')) continue buf.push(field + ':' + val) } return buf.sort().join('\n') } module.exports.canonicalizeHeaders = canonicalizeHeaders /** * Perform the following: * * - ignore non sub-resources * - sort lexicographically * * @param {String} resource * @return {String} * @api private */ function canonicalizeResource (resource) { var url = parse(resource, true) , path = url.pathname , buf = [] ; Object.keys(url.query).forEach(function(key){ if (!~keys.indexOf(key)) return var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) buf.push(key + val) }) return path + (buf.length ? '?' + buf.sort().join('&') : '') } module.exports.canonicalizeResource = canonicalizeResource
import configureStore from '@shopgate/pwa-common/store'; import historyReducer from '@shopgate/pwa-common/reducers/history'; import productReducers from '@shopgate/pwa-common-commerce/product/reducers'; import { HISTORY_PUSH_ACTION } from '@shopgate/pwa-common/constants/ActionTypes'; import { updateHistory } from '@shopgate/pwa-common/action-creators/history'; let mockedInitialPathname; jest.mock('history/createBrowserHistory', () => () => ({ location: { get pathname() { return mockedInitialPathname; }, }, })); jest.mock('redux-logger', () => ({ createLogger: () => () => next => action => next(action), })); /** * Creates a redux store instance for the tests. * @param {string} pathname The initial pathname. * @return {Onject} */ export const createStore = (pathname = '/somepath') => { mockedInitialPathname = pathname; return configureStore({ history: historyReducer, product: productReducers, }); }; /** * A wrapper for the updated history action creator. It sets up the most common properties. * @param {string} pathname The pathname for the update. * @return {Object} */ export const updateHistoryWrapped = (pathname = '/somepath') => updateHistory({ action: HISTORY_PUSH_ACTION, queryParams: {}, length: 1, pathname, });
# Copyright 2011 The Emscripten Authors. All rights reserved. # Emscripten is available under two separate licenses, the MIT license and the # University of Illinois/NCSA Open Source License. Both these licenses can be # found in the LICENSE file. """Utilties for manipulating WebAssembly binaries from python. """ from collections import namedtuple from enum import IntEnum import logging import os import sys from . import utils from .settings import settings sys.path.append(utils.path_from_root('third_party')) import leb128 logger = logging.getLogger('webassembly') # For the Emscripten-specific WASM metadata section, follows semver, changes # whenever metadata section changes structure. # NB: major version 0 implies no compatibility # NB: when changing the metadata format, we should only append new fields, not # reorder, modify, or remove existing ones. EMSCRIPTEN_METADATA_MAJOR, EMSCRIPTEN_METADATA_MINOR = (0, 3) # For the JS/WASM ABI, specifies the minimum ABI version required of # the WASM runtime implementation by the generated WASM binary. It follows # semver and changes whenever C types change size/signedness or # syscalls change signature. By semver, the maximum ABI version is # implied to be less than (EMSCRIPTEN_ABI_MAJOR + 1, 0). On an ABI # change, increment EMSCRIPTEN_ABI_MINOR if EMSCRIPTEN_ABI_MAJOR == 0 # or the ABI change is backwards compatible, otherwise increment # EMSCRIPTEN_ABI_MAJOR and set EMSCRIPTEN_ABI_MINOR = 0. EMSCRIPTEN_ABI_MAJOR, EMSCRIPTEN_ABI_MINOR = (0, 29) WASM_PAGE_SIZE = 65536 MAGIC = b'\0asm' VERSION = b'\x01\0\0\0' HEADER_SIZE = 8 LIMITS_HAS_MAX = 0x1 def toLEB(num): return leb128.u.encode(num) def readULEB(iobuf): return leb128.u.decode_reader(iobuf)[0] def readSLEB(iobuf): return leb128.i.decode_reader(iobuf)[0] def add_emscripten_metadata(wasm_file): mem_size = settings.INITIAL_MEMORY // WASM_PAGE_SIZE global_base = settings.GLOBAL_BASE logger.debug('creating wasm emscripten metadata section with mem size %d' % mem_size) name = b'\x13emscripten_metadata' # section name, including prefixed size contents = ( # metadata section version toLEB(EMSCRIPTEN_METADATA_MAJOR) + toLEB(EMSCRIPTEN_METADATA_MINOR) + # NB: The structure of the following should only be changed # if EMSCRIPTEN_METADATA_MAJOR is incremented # Minimum ABI version toLEB(EMSCRIPTEN_ABI_MAJOR) + toLEB(EMSCRIPTEN_ABI_MINOR) + # Wasm backend, always 1 now toLEB(1) + toLEB(mem_size) + toLEB(0) + toLEB(global_base) + toLEB(0) + # dynamictopPtr, always 0 now toLEB(0) + # tempDoublePtr, always 0 in wasm backend toLEB(0) + toLEB(int(settings.STANDALONE_WASM)) # NB: more data can be appended here as long as you increase # the EMSCRIPTEN_METADATA_MINOR ) orig = utils.read_binary(wasm_file) with open(wasm_file, 'wb') as f: f.write(orig[0:8]) # copy magic number and version # write the special section f.write(b'\0') # user section is code 0 # need to find the size of this section size = len(name) + len(contents) f.write(toLEB(size)) f.write(name) f.write(contents) f.write(orig[8:]) class SecType(IntEnum): CUSTOM = 0 TYPE = 1 IMPORT = 2 FUNCTION = 3 TABLE = 4 MEMORY = 5 EVENT = 13 GLOBAL = 6 EXPORT = 7 START = 8 ELEM = 9 DATACOUNT = 12 CODE = 10 DATA = 11 class ExternType(IntEnum): FUNC = 0 TABLE = 1 MEMORY = 2 GLOBAL = 3 EVENT = 4 class DylinkType(IntEnum): MEM_INFO = 1 NEEDED = 2 EXPORT_INFO = 3 Section = namedtuple('Section', ['type', 'size', 'offset']) Limits = namedtuple('Limits', ['flags', 'initial', 'maximum']) Import = namedtuple('Import', ['kind', 'module', 'field']) Export = namedtuple('Export', ['name', 'kind', 'index']) Dylink = namedtuple('Dylink', ['mem_size', 'mem_align', 'table_size', 'table_align', 'needed', 'export_info']) class Module: """Extremely minimal wasm module reader. Currently only used for parsing the dylink section.""" def __init__(self, filename): self.size = os.path.getsize(filename) self.buf = open(filename, 'rb') magic = self.buf.read(4) version = self.buf.read(4) assert magic == MAGIC assert version == VERSION def __del__(self): self.buf.close() def readByte(self): return self.buf.read(1)[0] def readULEB(self): return readULEB(self.buf) def readSLEB(self): return readSLEB(self.buf) def readString(self): size = self.readULEB() return self.buf.read(size).decode('utf-8') def readLimits(self): flags = self.readByte() initial = self.readULEB() maximum = 0 if flags & LIMITS_HAS_MAX: maximum = self.readULEB() return Limits(flags, initial, maximum) def seek(self, offset): return self.buf.seek(offset) def tell(self): return self.buf.tell() def skip(self, count): self.buf.seek(count, os.SEEK_CUR) def sections(self): """Generator that lazily returns sections from the wasm file.""" offset = HEADER_SIZE while offset < self.size: self.seek(offset) section_type = SecType(self.readByte()) section_size = self.readULEB() section_offset = self.buf.tell() yield Section(section_type, section_size, section_offset) offset = section_offset + section_size def parse_dylink_section(wasm_file): module = Module(wasm_file) dylink_section = next(module.sections()) assert dylink_section.type == SecType.CUSTOM module.seek(dylink_section.offset) # section name section_name = module.readString() needed = [] export_info = {} if section_name == 'dylink': mem_size = module.readULEB() mem_align = module.readULEB() table_size = module.readULEB() table_align = module.readULEB() needed_count = module.readULEB() while needed_count: libname = module.readString() needed.append(libname) needed_count -= 1 elif section_name == 'dylink.0': section_end = dylink_section.offset + dylink_section.size while module.tell() < section_end: subsection_type = module.readULEB() subsection_size = module.readULEB() end = module.tell() + subsection_size if subsection_type == DylinkType.MEM_INFO: mem_size = module.readULEB() mem_align = module.readULEB() table_size = module.readULEB() table_align = module.readULEB() elif subsection_type == DylinkType.NEEDED: needed_count = module.readULEB() while needed_count: libname = module.readString() needed.append(libname) needed_count -= 1 elif subsection_type == DylinkType.EXPORT_INFO: count = module.readULEB() while count: sym = module.readString() flags = module.readULEB() export_info[sym] = flags count -= 1 else: print(f'unknown subsection: {subsection_type}') # ignore unknown subsections module.skip(subsection_size) assert(module.tell() == end) else: utils.exit_with_error('error parsing shared library') return Dylink(mem_size, mem_align, table_size, table_align, needed, export_info) def get_exports(wasm_file): module = Module(wasm_file) export_section = next((s for s in module.sections() if s.type == SecType.EXPORT), None) module.seek(export_section.offset) num_exports = module.readULEB() exports = [] for i in range(num_exports): name = module.readString() kind = ExternType(module.readByte()) index = module.readULEB() exports.append(Export(name, kind, index)) return exports def get_imports(wasm_file): module = Module(wasm_file) import_section = next((s for s in module.sections() if s.type == SecType.IMPORT), None) if not import_section: return [] module.seek(import_section.offset) num_imports = module.readULEB() imports = [] for i in range(num_imports): mod = module.readString() field = module.readString() kind = ExternType(module.readByte()) imports.append(Import(kind, mod, field)) if kind == ExternType.FUNC: module.readULEB() # sig elif kind == ExternType.GLOBAL: module.readSLEB() # global type module.readByte() # mutable elif kind == ExternType.MEMORY: module.readLimits() # limits elif kind == ExternType.TABLE: module.readSLEB() # table type module.readLimits() # limits else: assert False return imports
/** * Auto-generated action file for "NBA Stats" API. * * Generated at: 2019-05-07T14:43:11.215Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / nba-com-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: undefined * Endpoint Path: '/playerdashptshotdefend' * Method: 'get' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "PerMode", "Season", "SeasonType", "PlayerID", "TeamID", "Outcome", "Location", "Month", "SeasonSegment", "DateFrom", "DateTo", "OpponentTeamID", "VsConference", "VsDivision", "GameSegment", "Period", "LastNGames" ]; // mappings from connector field names to API field names const FIELD_MAP = { "PerMode": "PerMode", "Season": "Season", "SeasonType": "SeasonType", "PlayerID": "PlayerID", "TeamID": "TeamID", "Outcome": "Outcome", "Location": "Location", "Month": "Month", "SeasonSegment": "SeasonSegment", "DateFrom": "DateFrom", "DateTo": "DateTo", "OpponentTeamID": "OpponentTeamID", "VsConference": "VsConference", "VsDivision": "VsDivision", "GameSegment": "GameSegment", "Period": "Period", "LastNGames": "LastNGames" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = undefined; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; let callParams = { spec: spec, operationId: undefined, pathName: '/playerdashptshotdefend', method: 'get', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
import React from 'react'; export default function ({ message }) { return ( <div>{message}</div> ); }
deepmacDetailCallback("5cf938000000/24",[{"d":"2013-08-31","t":"add","a":"1 Infinite Loop\nCupertino CA 95014\n\n","c":"UNITED STATES","o":"Apple, Inc"},{"d":"2015-08-27","t":"change","a":"1 Infinite Loop\nCupertino CA 95014\n\n","c":"US","o":"Apple, Inc"},{"d":"2015-09-01","t":"change","a":"1 Infinite Loop\nCupertino CA 95014\n\n","c":"US","o":"A, Inc"},{"d":"2015-09-17","t":"change","a":"1 Infinite Loop Cupertino CA US 95014","c":"US","o":"Apple, Inc."}]);
class BaseResponse { constructor(status, statusCode, data = null, message = 'Operation Completed Successfully') { this.status = status; this.statusCode = statusCode; this.data = data; this.message = message; } } module.exports = { BaseResponse, };
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import unittest import warnings from six import StringIO from conans.client import tools from conans.client.output import ConanOutput from conans.client.tools.oss import cpu_count from conans.client.tools.win import build_sln_command from conans.errors import ConanException from conans.model.settings import Settings from conans.test.utils.mocks import MockSettings from conans.test.utils.test_files import temp_folder from conans.util.files import load, save class BuildSLNCommandTest(unittest.TestCase): def test_no_configuration(self): dummy = """GlobalSection EndGlobalSection GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Debug|x64 = Debug|x64 Release|Win32 = Release|Win32 Release|x64 = Release|x64 EndGlobalSection """ folder = temp_folder() path = os.path.join(folder, "dummy.sln") save(path, dummy) new_out = StringIO() command = build_sln_command(Settings({}), sln_path=path, targets=None, upgrade_project=False, build_type='Debug', arch="x86", parallel=False, output=ConanOutput(new_out)) self.assertIn('/p:Configuration="Debug" /p:UseEnv=false /p:Platform="x86"', command) self.assertIn("WARN: ***** The configuration Debug|x86 does not exist in this solution *****", new_out.getvalue()) # use platforms new_out = StringIO() command = build_sln_command(Settings({}), sln_path=path, targets=None, upgrade_project=False, build_type='Debug', arch="x86", parallel=False, platforms={"x86": "Win32"}, output=ConanOutput(new_out)) self.assertIn('/p:Configuration="Debug" /p:UseEnv=false /p:Platform="Win32"', command) self.assertNotIn("WARN", new_out.getvalue()) self.assertNotIn("ERROR", new_out.getvalue()) def test_no_arch(self): with self.assertRaises(ConanException): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") new_out = StringIO() build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=False, build_type='Debug', arch=None, parallel=False, output=ConanOutput(new_out)) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) def test_no_build_type(self): with self.assertRaises(ConanException): with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") new_out = StringIO() build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=False, build_type=None, arch='x86', parallel=False, output=ConanOutput(new_out)) self.assertEqual(len(w), 1) self.assertTrue(issubclass(w[0].category, DeprecationWarning)) def test_positive(self): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=False, build_type='Debug', arch='x86', parallel=False, output=output) self.assertIn('msbuild "dummy.sln"', command) self.assertIn('/p:Platform="x86"', command) self.assertNotIn('devenv "dummy.sln" /upgrade', command) self.assertNotIn('/m:%s' % cpu_count(output=output), command) self.assertNotIn('/target:teapot', command) def test_upgrade(self): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=True, build_type='Debug', arch='x86_64', parallel=False, output=output) self.assertIn('msbuild "dummy.sln"', command) self.assertIn('/p:Platform="x64"', command) self.assertIn('devenv "dummy.sln" /upgrade', command) self.assertNotIn('/m:%s' % cpu_count(output=output), command) self.assertNotIn('/target:teapot', command) with tools.environment_append({"CONAN_SKIP_VS_PROJECTS_UPGRADE": "1"}): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=True, build_type='Debug', arch='x86_64', parallel=False, output=output) self.assertIn('msbuild "dummy.sln"', command) self.assertIn('/p:Platform="x64"', command) self.assertNotIn('devenv "dummy.sln" /upgrade', command) self.assertNotIn('/m:%s' % cpu_count(output=output), command) self.assertNotIn('/target:teapot', command) with tools.environment_append({"CONAN_SKIP_VS_PROJECTS_UPGRADE": "False"}): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=True, build_type='Debug', arch='x86_64', parallel=False, output=output) self.assertIn('devenv "dummy.sln" /upgrade', command) def test_parallel(self): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=None, upgrade_project=True, build_type='Debug', arch='armv7', parallel=False, output=output) self.assertIn('msbuild "dummy.sln"', command) self.assertIn('/p:Platform="ARM"', command) self.assertIn('devenv "dummy.sln" /upgrade', command) self.assertNotIn('/m:%s' % cpu_count(output=output), command) self.assertNotIn('/target:teapot', command) def test_target(self): output = ConanOutput(StringIO()) command = build_sln_command(Settings({}), sln_path='dummy.sln', targets=['teapot'], upgrade_project=False, build_type='Debug', arch='armv8', parallel=False, output=output) self.assertIn('msbuild "dummy.sln"', command) self.assertIn('/p:Platform="ARM64"', command) self.assertNotIn('devenv "dummy.sln" /upgrade', command) self.assertNotIn('/m:%s' % cpu_count(output=output), command) self.assertIn('/target:teapot', command) def test_toolset(self): new_out = StringIO() command = build_sln_command(MockSettings({"compiler": "Visual Studio", "compiler.version": "17", "build_type": "Debug", "compiler.runtime": "MDd", "cppstd": "17"}), sln_path='dummy.sln', targets=None, upgrade_project=False, build_type='Debug', arch='armv7', parallel=False, toolset="v110", output=ConanOutput(new_out)) self.assertTrue(command.startswith('msbuild "dummy.sln" /p:Configuration="Debug" ' '/p:UseEnv=false ' '/p:Platform="ARM" ' '/p:PlatformToolset="v110" ' '/verbosity:minimal ' '/p:ForceImportBeforeCppTargets='), command) def test_properties_file(self): new_out = StringIO() command = build_sln_command(MockSettings({"compiler": "Visual Studio", "compiler.version": "17", "build_type": "Debug", "compiler.runtime": "MDd", "cppstd": "17"}), sln_path='dummy.sln', targets=None, upgrade_project=False, build_type='Debug', arch='armv7', parallel=False, output=ConanOutput(new_out)) self.assertTrue(command.startswith('msbuild "dummy.sln" /p:Configuration="Debug" ' '/p:UseEnv=false ' '/p:Platform="ARM" ' '/verbosity:minimal ' '/p:ForceImportBeforeCppTargets='), command) path_tmp = command.split("/p:ForceImportBeforeCppTargets=")[1][1:-1] # remove quotes self.assertTrue(os.path.exists(path_tmp)) contents = load(path_tmp) self.assertIn("<RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>", contents) self.assertIn("<AdditionalOptions>/std:c++17 %(AdditionalOptions)</AdditionalOptions>", contents)
/* * 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. */ Ext.define('Wdesktop.app.AppManager.view.MainAppPanel', { extend : 'Ext.panel.Panel', alias : "widget.appManagerMainAppPanel", frame : false, layout : { type : 'border' }, initComponent : function() { var me = this; Ext.applyIf(me, { items : [ { xtype : 'treepanel', region : 'west', width : 192, title : '我的应用市场', split : true, frame : false, collapsible : true, columnLines : false, lines : false, useArrows : true, rootVisible : false, store:Ext.create('Wdesktop.app.AppManager.store.AppTreeStore'), tools:[{ type:'expand', handler:function(event,toolEl,owner,tool){ tool.up('treepanel').expandAll(); } },{ type:'collapse', handler:function(event,toolEl,owner,tool){ tool.up('treepanel').collapseAll(); } }], viewConfig: { plugins: [ Ext.create('Ext.tree.plugin.TreeViewDragDrop', { nodeHighlightOnDrop: true, nodeHighlightOnRepair: true })] } }, { xtype : 'tabpanel', region : 'center', plugins: [Ext.create('Ext.ux.TabScrollerMenu'), Ext.create('Ext.ux.TabCloseMenu')], activeTab : 0, items : [ { xtype : 'panel', title : '应用市场' } ] } ] }); me.callParent(arguments); } });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Inventariomecanico Schema */ var InventariomecanicoSchema = new Schema({ name: { type: String, default: '', required: 'por favor ingrese el nombre de la parte', trim: true }, cantidad: { type: Number, default: '', required: 'Por favor ingrese la cantidad en existencia', trim: true }, descripcion: { type: String, default: '', required: 'Por favor ingrese una descripcion para la parte', trim: true }, updated: { type: Date, default: '' }, created: { type: Date, default: '' }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Inventariomecanico', InventariomecanicoSchema);
import { h } from 'vue' export default { name: "ClockTimeTwelve", vendor: "Mdi", type: "", tags: ["clock","time","twelve"], render() { return h( "svg", {"xmlns":"http://www.w3.org/2000/svg","width":"24","height":"24","viewBox":"0 0 24 24","class":"v-icon","fill":"currentColor","data-name":"mdi-clock-time-twelve","innerHTML":"<path d='M12 2C6.5 2 2 6.5 2 12C2 17.5 6.5 22 12 22C17.5 22 22 17.5 22 12S17.5 2 12 2M12.5 13H11V7H12.5V13Z' />"}, ) } }
var System={ SYMBOLS:" ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789?!@,-.:;<=>[\\]/_#$%&'()*+\"~", versions:{}, COMPRESSMETHODS:[ // Best first {label:"Sequence packed",SEQUENCERECTANGLE:false,SEQUENCEPACKER:true,BINARYPACKER:"none"}, {label:"Sequence packed, zipped",SEQUENCERECTANGLE:false,SEQUENCEPACKER:true,BINARYPACKER:"zip"}, {label:"Unchanged",SEQUENCERECTANGLE:false,SEQUENCEPACKER:false,BINARYPACKER:"none"}, {label:"Unchanged, zipped",SEQUENCERECTANGLE:false,SEQUENCEPACKER:false,BINARYPACKER:"zip"}, // Rectangled can help zip comprssion but can create bad data... {label:"Sequence rectangled and packed",SEQUENCERECTANGLE:true,SEQUENCEPACKER:true,BINARYPACKER:"none"}, {label:"Sequence rectangled and packed, zipped",SEQUENCERECTANGLE:true,SEQUENCEPACKER:true,BINARYPACKER:"zip"}, {label:"Sequence rectangled",SEQUENCERECTANGLE:true,SEQUENCEPACKER:false,BINARYPACKER:"none"}, {label:"Sequence rectangled, zipped",SEQUENCERECTANGLE:true,SEQUENCEPACKER:false,BINARYPACKER:"zip"} ], pack:function(cart,root,cb,cycle,result,metadata) { if (!cycle) cycle={ method:0, methodData:0, best:-1, assembled:false }; if (!cycle.assembled) { console.log("PACK: First assembling the cartige..."); this.assemble(cart,root,assembled=>{ cycle.assembled=true; this.pack(assembled,root,cb,cycle,result) }) } else { if (result!==undefined) { result=String.fromCharCode(cycle.method)+result; console.log("PACK: Method "+cycle.method+": "+result.length+" byte(s)"); if ((cycle.best==-1)||(cycle.data.length>result.length)) { cycle.bestMethod=this.COMPRESSMETHODS[cycle.method]; cycle.best=cycle.method; cycle.data=result; } cycle.method++; } if (cycle.method<this.COMPRESSMETHODS.length) { var method=this.COMPRESSMETHODS[cycle.method]; this.compile(cart,method,function(binary,metadata) { if (metadata) cycle.metadata=metadata; switch (method.BINARYPACKER) { case "zip":{ var zip=new JSZip(); zip.file("x",binary); zip.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:9}}).then(compressed=>{ var out=""; // Strips the "PK" header for (var i = 2; i < compressed.length; ++i) out+=String.fromCharCode(compressed[i]); System.pack(cart,root,cb,cycle,out,metadata); }) break; } default:{ System.pack(cart,root,cb,cycle,Encode.string.bitStream([0,binary],Stream.BYTEENCODER),metadata); break; } } },root); } else { console.log("PACK: Done. Used",cycle.bestMethod.label,"for",cycle.data.length,"byte(s)"); cb(cycle); } } }, unpack:function(data,cb) { var method=this.COMPRESSMETHODS[data.charCodeAt(0)]; data=data.substr(1); console.log("UNPACK: Unpacking as",method.label); switch (method.BINARYPACKER) { case "zip":{ data="PK"+data; var zip=new JSZip(); zip.loadAsync(data).then(x=>{ zip.file("x").async("string").then(unpacked=>{ this.decompile(unpacked,method,function(cart) { cb(cart); }); }) }) break; } default:{ this.decompile(Decode.string.bitStream([0,data],Stream.BYTEENCODER),method,function(cart) { cb(cart); }); break; } } }, constructSystem:function(version,debug) { return this.versions[version].constructor(debug,version); }, assemble:function(cart,root,cb,debug) { cart=this.clone(cart); this._solvePlaceHolders(root,cart,cart=>{ var systemModel=this.versions[cart.systemVersion]; if (systemModel) { var system=this.constructSystem(cart.systemVersion,debug); console.log("ASSEMBLE: Assembling cartridge..."); cart=this._assembleEntities(cart,system); console.log("ASSEMBLE: Assembled!"); cb(cart); } else { console.error("ASSEMBLE: Can't find system version",cart.systemVersion); onready(); } }); }, decompile:function(data,compileConfig,onready,debug) { var cart={}; var stream=Decode.binary.string([0,data],this.SYMBOLS); cart.systemVersion=stream[0]; var systemModel=this.versions[cart.systemVersion]; if (systemModel) { var system=this.constructSystem(cart.systemVersion,debug); stream=Decode.binary.structure(stream,system,system.SYSTEMPROTOCOL,compileConfig); for (var k in stream[0]) cart[k]=stream[0][k]; system.configure(cart); stream=Decode.binary.structure(stream,system,system.DATAPROTOCOL,compileConfig); for (var k in stream[0]) cart[k]=stream[0][k]; if (debug) console.log("DECOMPILE: Decompiled rest:",stream[1]); onready({ cart:cart, system:system }); } else { console.error("DECOMPILE: Can't find system version",cart.systemVersion); onready(); } }, compile:function(cart,compileConfig,onready,root,debug) { var metadata=cart.metadata; delete cart.metadata; console.log("COMPILE: Preparing cartridge for system",cart.systemVersion,"as",compileConfig.label); var systemModel=this.versions[cart.systemVersion]; if (systemModel) { var system=this.constructSystem(cart.systemVersion,debug); // Encode system version var out=Encode.binary.string(cart.systemVersion,this.SYMBOLS); // Encode system configuration out+=Encode.binary.structure(cart,system,system.SYSTEMPROTOCOL,compileConfig); // Encode cartridge data system.configure(cart); out+=Encode.binary.structure(cart,system,system.DATAPROTOCOL,compileConfig); console.log("COMPILE: Done!",Math.ceil(out.length/8),"byte(s). Validating..."); System.decompile(out,compileConfig,decompiled=>{ System._check(cart,decompiled.cart,0,debug); onready(out,metadata); }) } }, // --- inRange:function(value,range){ return (value>=range[0])&&(value<=range[1]); }, _check:function(a,b,h,debug) { if (!h) h=""; if (typeof a == "object") { if (b === undefined) { console.error("CHECK:",h,":",a,"vs",b); } else if (b.getContext) { if (debug) { a.style.border="1px solid green"; b.style.border="1px solid red"; document.body.appendChild(a); document.body.appendChild(b); document.body.appendChild(document.createElement("hr")); } } else for (var k in a) { this._check(a[k],b[k],h+"."+k,debug) } } else { if (a!=b) { console.error("CHECK:",h,":","["+a+"]","vs","["+b+"]"); } } }, _loadPlaceholders:function(root,model,ondone,resources,fullmodel) { var replace; if (resources.length) { var load=resources.pop(); var file=root+load.config._file; delete load.config._file; if (load.config._replace) { replace=load.config._replace; delete load.config._replace; } console.log("PLACEHOLDERS: Loading",file,"..."); var extension=file.substr(file.lastIndexOf(".")+1).toLowerCase(); switch (extension) { case "json":{ Stream.getFile(file,json=>{ json=JSON.parse(json); if (json instanceof Array) { var pos=load.parent.indexOf(load.parent[load.key]); json.forEach((item,id)=>load.parent.splice(pos+1+id,0,item)); load.parent.splice(pos,1); System._solvePlaceHolders(root,{key:json},ondone,replace,resources,fullmodel); } else { for (var k in json) if (load.parent[load.key][k]===undefined) load.parent[load.key][k]=json[k]; System._solvePlaceHolders(root,load.parent[load.key],ondone,replace,resources,fullmodel); } }); break; } case "jpeg": case "jpg": case "gif": case "png":{ var img = new Image(); img.onload = function () { load.parent[load.key]=img; System._loadPlaceholders(root,model,ondone,resources,fullmodel); }; img.src = file; break; } default:{ console.error("Extension",extension,"is not supported"); System._loadPlaceholders(root,model,ondone,resources,fullmodel); } } } else ondone(fullmodel._); }, _solvePlaceHolders:function(root,model,ondone,replace,resources,fullmodel,sub) { if (!fullmodel) model=fullmodel={_:model}; if (!resources) resources=[]; for (var k in model) { if (typeof model[k]=="object") { if (model[k]._placeholder) { var newvalue=replace[model[k]._placeholder]; if (model[k]._default&&(newvalue==undefined)) newvalue=model[k]._default; if (newvalue==undefined) console.warn("PLACEHOLDERS: Can't find placeholder",model[k]._placeholder); else { if (model[k]._default&&(newvalue==undefined)) newvalue=model[k]._default; if (model[k]._multiply) newvalue*=model[k]._multiply; if (model[k]._sum) newvalue+=model[k]._sum; model[k]=newvalue; } } else this._solvePlaceHolders(root,model[k],ondone,replace,resources,fullmodel,true); } } if (!sub) this._gatherSubPlaceholders(root,model,ondone,replace,resources,fullmodel,sub); }, _gatherSubPlaceholders:function(root,model,ondone,replace,resources,fullmodel,sub) { for (var k in model) { if (typeof model[k]=="object") { if (model[k]._file) { resources.push({parent:model,key:k,config:model[k]}); } else this._gatherSubPlaceholders(root,model[k],ondone,replace,resources,fullmodel,true); } } if (!sub) this._loadPlaceholders(root,model,ondone,resources,fullmodel); }, _assembleEntities:function(model,system) { for (var k in model) { if (typeof model[k]=="object") { if (model[k]._!==undefined) { system.assembleEntity(model[k]); delete model[k]._; } else if (!model[k].tagName) this._assembleEntities(model[k],system); } } return model; }, clone:function(a) { return JSON.parse(JSON.stringify(a)); }, patch:function(patch,org){ if (patch) patch.forEach(getter=>org.push(getter)); return org }, solveReferences:function(struct,map,done) { if (!done) done=[] if (done.indexOf(struct)==-1) { done.push(struct); if (typeof struct=="object") { if (map[struct.values]) struct.values=map[struct.values]; else for (var k in struct) this.solveReferences(struct[k],map,done) } } return struct; }, padWithUnused:function(debug,label,qty,set) { if (set.length>qty) { if (debug) console.error("MODEL: The set [",label,"] is too large by",set.length-qty,". (",qty,")"); } else { var id=0; while (set.length<qty) { set.push({key:"UNUSED-"+id, unused:true}); id++; } if (debug) if (!id) console.log("MODEL: You have NO VALUES left values in",label,"."); else if (id>20) console.log("MODEL: You *still* have",id,"unused values in",label,"."); else if (id<5) console.log("MODEL: You just have",id," left values in",label,"."); } return set; } }; System.versions["0.3"]={ constructor:function(debug,version) { return System.versions["0.1"].constructor(debug,version,{ WARNING:"This is a development version of Rewtro. Please *do not* distribute games using this version.", GETTERS:[ { key:"idsByName", values:"*GETTERS*" }, { key:"flagsByName", values:"*GETTERS*" }, { key:"ceil", flag:true }, { key:"round", flag:true } ], QUIRKS:{ unshift:true } }); } }; System.versions["0.2"]={ constructor:function(debug,version) { return System.versions["0.1"].constructor(debug,version,{ GETTERS:[ { key:"idsByName", values:"*GETTERS*" }, { key:"flagsByName", values:"*GETTERS*" } ], QUIRKS:{ unshift:true } }); } }; System.versions["0.1"]={ constructor:function(debug,version,mods) { if (!mods) mods={}; if (!mods.QUIRKS) mods.QUIRKS={}; var sys={ VERSION:version, WARNING:mods.WARNING||"" }; sys.FONTENCODER=Stream.ENCODER; sys.DEFAULTS={ FPS:25, MUSICVOLUME:0.5, EFFECTSVOLUME:0.9, LOADINGTIME:13, DEFAULTCOLOR:1, FONT:[ // default.png "ICAAAIAB8yPH8_60nCOARCQEJCPHmy6DnyQaJCQaRyOBAuOA8yHHmuODmQPAAAAAAACAA7OIAuA7AaEAAmBA7QEAAaAAAaQaJEQEBCQ8AEREBcZaJCQaJCEEJCQaJEBEQmREQZQCAERERCEEIAAAAAABAAECBACAQAJDn9SA7QCFQQJAAAQaJAQaBAQEIQBE8AXbJCQaJCQBBCQaIaRA8MUAQEKH8ACEREBBBKAAAAEBA76A77IA7IAHvQWE7QIAQuECQAAHvyQEJu5Ev_EARmQEJKQdnC6DmQQaJCGD7QVBAIGE7E5BAuPA7QV7AAAAAAQAAEIBAIEAAaOA7mACAEEHmAM7BCQaBCQEBCQ8AESEBCRaJASa7CEEJCX9QQIGQQMARyBEQ7RAQIAEmA6AAAACByCCAICCAA68QQS7A7BD7QAEmAQaJCREBAQaIQRERAQaJCQEREQ8BCJGWCEEBEEEBECEREIEQIAABACAAAEBAQABA7BA8AACRuJaQAEA8UEAAAAEJyPH8_QDnCOD8C6aJCPEAwQ0mQPB8CQ8ByOHnyOA7uOCAu3A7QPA7AEAAQCAA7OAIu7HmaEEZwAA7QEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", // spectrum.png "ICAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABu_H0m.Pnu8HmE9ICE8H0u5P8u.eSE8IUE.H7m5H7Q.H0y5H8uEH7AAAAAAAAAABmAuAAASBDEIBAIQAAASAAA8ISE9ICA8IQQBJCApMSE8ISE7BCE8IRI9A9MUISEMICABISE8BCUAAAAABAQAEAQ7CAIAPnyoFA7ECBQIE7AAITu7ITu_IDyEAT77LSa8ISE8H7Q8ISEMFAQbBAEGFDu_A8u8A7QhAAAABAAIP77EEA7EABIUBA7ABA7ICAAKADy8ICE7IC38BCEaICEbITufP7EEISE8DA7IKQQ5ASQBIQQ8HmQELmA_AAAAEAAEBA7ICAASHm7VAAQIP0uAFAA8ISE9ICA8IQQ8I9A8IoE7JSI8BCESLRIIEDEEICE.ISEIIQEAACAEAAmABA7_CAQECBAAPmUTI7AECA7IAAAAITu5PDy7H9E6H9E.ISE5IBu8H7Q5DBI8CDy5Hpy5BBu5CBu5BAQ5BAAMBAQEABAHA077PzI6InqAA8AUCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA7AAAAIAAAAAAAAAAAABAAAAAAAAAAAAA", // c64.png "ICAAAIAB8yPH8_60ncPBvcZGNcPHmy6Dn_WcW0WcW_5DBu5Apy5Pnu5DmZPAAAAAAAHAD7PABuAABcGMRuDAn7AABcAAAyWcWiZGBcW87M2GBt4cWcWcWcGGWcZsWcBimmpMm3mMpMpMncGGZAAAAAADAAMDDAGAZAW0xMpB7ZMGZZW7AAWcW7WcB7ZGZZDH876tvcWcWcZB8cWcMyW7p33AmMPP0AGMpMB88kAAAAMB87.B7mZB7MAPz7GH7mMB7yGGZpAHvyZGWu5Gv_GAnmZGj_Wdnc6DmZWcWhGDmZxDAZOMmM_DBu6AmZ27DyAAAAmAAMMDAZGABcPDBmADAZ.tuA.mBcWcBcZGBcW87M5GB02cW7Wd7GGGWc6pmZMMmmZAp_DMmmpAmZAGAAAAAAAGDyGDAZGDAA.mW7p7AmGDmZAMmAWcWc2GB7WcZZ2Gn7ZsWcZDniW88cPH4cGGDMMMDMDMpMMMpMAAB9GAAZMB7mADAmDB87AGWypMmAGDBcGAAAAGWyPH8_ZDncPD8c6cNcPGAOW0mZPB80W88_5Ppy5Anu5DBu5B7ZPB7AGAAZHAD7PAWumPvcGIn_AAn7AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAA", // gameboy.png "ICAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAH7u6AAAAAAAGAB75MAyB7BiMABuDB87GABiAABu_H0u.Pnu0H7ypMCM0H0u5P8u.IoM0IpM.H7m5P8u_H0y5H93OMZAAAAAMDByMGD7DAuA2Hn9pB7mMFem2AAAdMpMdMDApImmGN0AtMpMpMTMmDCM0InZpBpM3Jm3sMDADJo3HD0GAAAAMDB76B873Am3APwmWMmmZB7yMCQoAJpumJpumMDyMB0mmPpipMpEpH7m0IoiMH7upDA35J0u_B8udD7ur7AAADAAmAAMZD7MOABi5A8wAGAZ6lmA67DypMC3mP030DDZyMCilMpurP73MIoM.HAm3Mmm5Bo3HMmmdHmmONuZ6AAAMGByGGA3DHAA.0QQpAB7GDpyAEmAdMpMdMDApImmsN0A0JpMmM0QdDC3XNpIMODMMOA3.JpM3Jm3AADAGAAmMDAm6DB7D7p7AGpuJimAMDB1MAAAAJpu5P0ymHoM5HDM.IoM5MBqpH7m5DCM8DDy5H0y_B8u5HBu5DAu6A7AMDAQGAB75AZymHniMEWwAB87GDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAA", // arcade.png "ICAAAIAD0yPP8_.0xG672GZM2G6Pny.H8_ni2Gnc2_OB8y68pyPPvu6Hm3PAAAAAAAGAB75MAyB7AaEABmGB7mEABiAABinc2MZMB7n87GpGDkvi2Gni2MGM2GnkvcDamun7mymGDGnM2_HEIAAAAmMDAAMGD7DAuAJDn9oB7mGFQQ2AAAni2AncDAmMZZBj87.l2Gni2GmB0GnjWyJBpGGAuZ2PpADOTGn8mCAAAAMDB76B873Am3AHvQWM7I3AmuECQoAM2ymMWy.Mx_GA2mZPx_ni2GpdmZnkx_ODmun87yPMmG.B8u67mZ37ByAAAAmAAMZD7MOAAaOA8mEHAMEHnI67D_niDGZMDGn87G_GDXti2ytl7GGMWy.dmZ3MZZ5A2_BiZmd7ZuEJIZ6AAAMGByGGA3DHAA68QQo7BmDD7QAEmAniWcpGDAWiZZnjn7nixGmMp3n80GOGpkGOBaGODGDM2GMIZMAACSGAAmMDAmADB7D7p7ACRuJiQAMB8UEAAAAM2yPP8_mDxG6dpO6i2G6MBwpdmZ6BBEn80_OHx_6Any6DBy5D7m6A7AMDAQGAB75AZymHmaEEWwAB7mEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAuMAAQAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAA" ], CONTROLLER:[ {type:"drag",buttons:["up","down","left","right","buttonA"]}, // Drag mode, Basic 1-button controller {type:"drag",buttons:["up","down","left","right","buttonA","buttonB"]}, // Drag mode, 2 buttons controller {type:"drag",buttons:["up","down","left","right","buttonA","buttonB","buttonC"]}, // Drag mode, 3 buttons controller {type:"drag",buttons:["up","down","left","right","buttonA","buttonB","buttonC","buttonD"]}, // Drag mode, 4 buttons controller {type:"drag",buttons:["up","down","left","right","buttonA"]}, // Drag mode, Single button controller {type:"keys",buttons:["up","down","left","right","buttonA"]}, // Keyboard mode, 1 action button {type:"keys",buttons:["up","down","left","right","buttonA","buttonB"]}, // Keyboard mode, 2 action buttons {type:"keys",buttons:["up","down","left","right","buttonA","buttonB","buttonC"]}, // Keyboard mode, 3 action buttons {type:"keys",buttons:["up","down","left","right","buttonA","buttonB","buttonC","buttonD"]}, // Keyboard mode, 4 action buttons ], RESOLUTION:[ { screenWidth:160, screenHeight:144, renderWidth:160, renderHeight:144 }, // Gameboy inspired { screenWidth:256, screenHeight:192, renderWidth:256, renderHeight:192 }, // ZX-Spectrum inspired { screenWidth:320, screenHeight:200, renderWidth:320, renderHeight:200 }, // C64 inspired ], PALETTE:[ [ // ZX-Spectrum inspired [ 0, 0, 0, 0], [ 0, 0, 0,255], [ 0, 0,255,255], [ 0,255, 0,255], [ 0,255,255,255], [255, 0, 0,255], [255, 0,255,255], [255,255, 0,255], [255,255,255,255], [ 0, 0,128,255], [ 0,128, 0,255], [ 0,128,128,255], [128, 0, 0,255], [128, 0,128,255], [128,128, 0,255], [128,128,128,255] ], [ // Gameboy inspired [ 0, 0, 0, 0], [202,220,159,255], [ 15, 56, 15,255], [ 48, 98, 48,255], [139,172, 15,255], [155,188, 15,255] ], [ // C64 inspired [ 0, 0, 0, 0], [ 0, 0, 0,255], [255,255,255,255], [136, 0, 0,255], [170,255,238,255], [204, 68,204,255], [ 0,204, 85,255], [ 0, 0,170,255], [238,238,119,255], [221,136, 85,255], [102, 68, 0,255], [255,119,119,255], [ 51, 51, 51,255], [119,119,119,255], [170,255,102,255], [ 0,136,255,255], [187,187,187,255] ] ] }; sys.configure=function(model) { // System defaults sys.DEFAULTCOLOR=sys.DEFAULTS.DEFAULTCOLOR, sys.PALETTE=sys.DEFAULTS.PALETTE[0], sys.LOADINGTIME=sys.DEFAULTS.LOADINGTIME, sys.RESOLUTION=System.clone(sys.DEFAULTS.RESOLUTION[0]), sys.FPS=sys.DEFAULTS.FPS, sys.CONTROLLER=sys.DEFAULTS.CONTROLLER[0]; sys.MUSICVOLUME=sys.DEFAULTS.MUSICVOLUME; sys.EFFECTSVOLUME=sys.DEFAULTS.EFFECTSVOLUME; fontData=sys.DEFAULTS.FONT[0]; if (model&&model.systemConfiguration) { model.systemConfiguration.forEach(cfg=>{ if (cfg.resolutionModel!==undefined) sys.RESOLUTION=System.clone(sys.DEFAULTS.RESOLUTION[cfg.resolutionModel]); if (cfg.screenWidth!==undefined) sys.RESOLUTION.screenWidth=cfg.screenWidth; if (cfg.screenHeight!==undefined) sys.RESOLUTION.screenHeight=cfg.screenHeight; if (cfg.renderWidth!==undefined) sys.RESOLUTION.renderWidth=cfg.renderWidth; if (cfg.renderHeight!==undefined) sys.RESOLUTION.renderHeight=cfg.renderHeight; if (cfg.paletteModel!==undefined) sys.PALETTE=sys.DEFAULTS.PALETTE[cfg.paletteModel]; if (cfg.palette!==undefined) sys.PALETTE=cfg.palette; if (cfg.defaultColor!==undefined) sys.DEFAULTCOLOR=cfg.defaultColor; if (cfg.musicVolume!==undefined) sys.MUSICVOLUME=cfg.musicVolume/sys.VOLUMERANGE[1]; if (cfg.effectsVolume!==undefined) sys.EFFECTSVOLUME=cfg.effectsVolume/sys.VOLUMERANGE[1]; if (cfg.loadingTime!==undefined) sys.LOADINGTIME=cfg.loadingTime; if (cfg.fps!==undefined) sys.FPS=cfg.fps; if (cfg.controllerModel!==undefined) sys.CONTROLLER=sys.DEFAULTS.CONTROLLER[cfg.controllerModel]; if (cfg.fontModel!==undefined) fontData=sys.DEFAULTS.FONT[cfg.fontModel]; }); } // Render chosen default font if (fontData) { var fontBinary=Decode.string.bitStream([0,fontData],sys.FONTENCODER); sys.DEFAULTFONT={id:"font",image:Decode.binary.image([0,fontBinary],sys)[0]}; } else sys.DEFAULTFONT=0; } // Translates the "_" key to the fitting variable type. sys.assembleEntity=function(entity) { var value=entity._,compiled=true; if (typeof value == "number") { if (Math.floor(value)!=value) entity.float=value; else if (System.inRange(value,RANGES.SMALLNUMBER)) entity.smallNumber=value; else if (System.inRange(value,RANGES.NUMBER)) entity.number=value; else if (System.inRange(value,RANGES.SMALLINTEGER)) entity.smallInteger=value; else if (System.inRange(value,RANGES.INTEGER)) entity.integer=value; else if (System.inRange(value,RANGES.LARGENUMBER)) entity.largeNumber=value; else { console.error("Can't compile number",value) compiled=false; } } else if (typeof value == "string") { if (value.length==1) entity.character=value; else entity.string=value; compiled=true; } else compiled=false; return compiled; } // --- GAME ENGINE sys.ENGINE="RewtroEngine"; // --- SYMBOLS var SYMBOLS=System.SYMBOLS; // --- PRECISION sys.PRECISION=0.001; // --- FONT sys.FONTLETTERS=SYMBOLS; // --- GRAPHICS var GRAPHICS=["graphics","font","graphics0","graphics1","graphics2","graphics3","graphics4","graphics5"]; // --- AUDIO sys.VOLUMERANGE=[0,127]; sys.NOTEMUTE=" "; sys.NOTENOOP="---", sys.AUDIORANGE=[0,255]; sys.NOISERANGES={ "attack":[0,0.3], "sustain":[0,0.4], "limit":[0.2,0.6], "decay":[0,0.3], "release":[0,0.4], "frequency":[100,1600], "tremoloFrequency":[0,50], "tremoloDepth":[0,1], "pitch":[-0.002,0.002], "frequencyJump1onset":[0,1], "frequencyJump1amount":[-1,1], "frequencyJump2onset":[0,1], "frequencyJump2amount":[-1,1], "bitCrush":[0,16], "bitCrushSweep":[-16,16] }; sys.NOISEDEFAULTS={ bitCrush:0, // 1-16 bitCrushSweep:0, // -16 16 attack:0, // 0-0.3 sustain:0, // 0-0.4 limit:0.6, // .2-.6 decay:0.1, // 0-0.3 release:0, // 0-0.4 frequency:850, // 100-1600 tremoloFrequency:0, // 0-50 tremoloDepth:0, // 0-1 frequencyJump1onset:0, // 0-1 frequencyJump1amount:0, // -1-1 frequencyJump2onset:0, // 0-1 frequencyJump2amount:0, // -1-1 pitch:0 // 0-.002 }; var NOTESLIST=[sys.NOTENOOP,sys.NOTEMUTE]; sys.NOTES={}; sys.OCTAVES=[2,7]; // Music and notes notations var _notes={'C':261.63,'C#':277.18,'D':293.66,'D#':311.13,'E':329.63,'F':349.23,'F#':369.99,'G':392.00,'G#':415.30,'A':440.00,'A#':466.16,'B':493.88}; for (var oct=sys.OCTAVES[0];oct<=sys.OCTAVES[1];oct++) for (var note in _notes) { var noteid=note[0]+oct+(note[1]||"-"); sys.NOTES[noteid]=_notes[note] * Math.pow(2,oct-4); NOTESLIST.push(noteid); } System.padWithUnused(debug,"notes",128,NOTESLIST); // --- COLORS sys.OPACITYRANGE=[0,127]; // --- DATA PROTOCOL var AREA=System.padWithUnused(debug,"system",4,[ { key:"x", values:"*GETTERS*" }, { key:"y", values:"*GETTERS*" }, { key:"width", values:"*GETTERS*" }, { key:"height", values:"*GETTERS*" } ]); // Default ranges var RANGES={ RGB:[0,255], SIZE:[0,255], TIME:[0,255], COLOR:[0,255], AUDIORANGE:[0,255], SPEED:[-25,26.1], SCALE:[-25,26.1], COORD:[-511,512], ANGLE:[0,511], ZINDEX:[0,255], RESOLUTION:[0,2047], // --- General ranges SMALLNUMBER:[0,127], NUMBER:[0,255], SMALLINTEGER:[-127,128], INTEGER:[-511,512], FLOAT:[-25,26.1], LARGENUMBER:[0,2047], // --- Public ranges OPACITY:sys.OPACITYRANGE, VOLUME:sys.VOLUMERANGE }; // Sprite events var EVENTS=System.padWithUnused(debug,"events",8,[ // Custom events "event0","event1","event2","event3","event4", // Engine events "hitWall","isSpawn","isRemoved", ]); // Bounds modes var BOUNDSMODES=System.padWithUnused(debug,"boundsmodes",2,[ "bound", "warp" ]); // Sprite attributes sys.SPRITEATTRIBUTES=[ { key:"id", character:SYMBOLS }, { key:"flags", string:SYMBOLS, defaultValue:"" }, { key:"timer", integer:RANGES.TIME, defaultValue:0 }, // PRIVATE: Used in timer conditions { key:"value0", float:RANGES.FLOAT, defaultValue:0 }, // General purpose numbers { key:"value1", float:RANGES.FLOAT, defaultValue:0 }, { key:"value2", float:RANGES.FLOAT, defaultValue:0 }, { key:"value3", float:RANGES.FLOAT, defaultValue:0 }, { key:"value4", float:RANGES.FLOAT, defaultValue:0 }, { key:"value5", string:SYMBOLS, defaultValue:"" }, { key:"value6", string:SYMBOLS, defaultValue:"" }, { key:"value7", string:SYMBOLS, defaultValue:"" }, { key:"value8", string:SYMBOLS, defaultValue:"" }, { key:"value9", string:SYMBOLS, defaultValue:"" }, { key:"zIndex", integer:RANGES.ZINDEX, defaultValue:0 }, { key:"graphic", value:GRAPHICS, defaultValue:GRAPHICS[0] }, { key:"x",integer:RANGES.COORD, defaultValue:0 }, { key:"y",integer:RANGES.COORD, defaultValue:0 }, { key:"width",integer:RANGES.SIZE, defaultValue:8 }, { key:"height",integer:RANGES.SIZE, defaultValue:8 }, { key:"graphicsX",integer:RANGES.SIZE }, { key:"graphicsY",integer:RANGES.SIZE }, { key:"graphicsWidth",integer:RANGES.SIZE }, { key:"graphicsHeight",integer:RANGES.SIZE }, { key:"backgroundColor", integer:RANGES.COLOR, defaultValue:0 }, { key:"speedX",float:RANGES.SPEED, defaultValue:0 }, { key:"speedY",float:RANGES.SPEED, defaultValue:0 }, { key:"speedLimitXTop", float:RANGES.SPEED, defaultValue:4 }, { key:"speedLimitXBottom", float:RANGES.SPEED, defaultValue:-4 }, { key:"speedLimitYTop", float:RANGES.SPEED, defaultValue:4 }, { key:"speedLimitYBottom", float:RANGES.SPEED, defaultValue:-4 }, { key:"gravityX", float:RANGES.SPEED, defaultValue:0 }, { key:"gravityY", float:RANGES.SPEED, defaultValue:0 }, { key:"applyRestitutionX", bool:true, defaultValue:true }, { key:"applyRestitutionY", bool:true, defaultValue:true }, { key:"restitutionX", float:RANGES.SPEED }, { key:"restitutionY", float:RANGES.SPEED }, { key:"touchDown", bool:true, defaultValue:false }, { key:"touchUp", bool:true, defaultValue:false }, { key:"touchLeft", bool:true, defaultValue:false }, { key:"touchRight", bool:true, defaultValue:false }, { key:"aim", integer:RANGES.ANGLE, defaultValue:0 }, { key:"rotate", integer:RANGES.ANGLE, defaultValue:0 }, { key:"flipX", bool:true, defaultValue:false }, { key:"flipY", bool:true, defaultValue:false }, { key:"scale", float:RANGES.SCALE, defaultValue:1 }, { key:"visible", bool:true, defaultValue:true }, { key:"rotateToAim", bool:true, defaultValue:false }, { key:"flipXtoSpeedX", bool:true, defaultValue:false }, { key:"flipYtoSpeedY", bool:true, defaultValue:false }, { key:"noCamera", bool:true, defaultValue: false }, { key:"collisionsEnabled", bool:true, defaultValue:true }, { key:"font", value:GRAPHICS, defaultValue:GRAPHICS[1] }, { key:"text", string:SYMBOLS }, { key:"textColor", integer:RANGES.COLOR, defaultValue:8 }, { key:"textAlignment", value:System.padWithUnused(debug,"textAlignment",4,["left","right","center"]) }, { key:"opacity", integer:RANGES.OPACITY, defaultValue:RANGES.OPACITY[1] }, { key:"animation", integer:RANGES.SMALLNUMBER }, { key:"animations", values:System.padWithUnused(debug,"animations",8,[ { key:"frames", listNumbers:RANGES.SMALLNUMBER }, { key:"mode", value:System.padWithUnused(debug,"mode",4,["loop","once","bounce"]) }, { key:"speed", integer:RANGES.SMALLNUMBER } ])} ]; // All object attributes var OBJECTATTRIBUTESLIST=[ "up", "down", "left", "right", "buttonA", "buttonB", "buttonC", "buttonD", // Keyboard keys "M0","M1","M2","M3","M4","M5","M6","M7","M8","M9" // songRow Channel ]; sys.SPRITEATTRIBUTES.forEach(attr=>OBJECTATTRIBUTESLIST.push(attr.key)); System.padWithUnused(debug,"spriteattributes",64,sys.SPRITEATTRIBUTES); System.padWithUnused(debug,"objectattributes",128,OBJECTATTRIBUTESLIST); // Sprite getters var SPRITEGETTERS=[ { key:"ids",string:SYMBOLS }, { key:"id",character:SYMBOLS }, { key:"flags",string:SYMBOLS } ]; // General getters (sprites, global objects, numbers etc.) var GETTERS=System.patch(mods.GETTERS,[ { key:"as", value:System.padWithUnused(debug,"as",16,["this","that","target","scene","game","keyboard","songRow","allSprites"])}, { key:"list", listNumbers:RANGES.INTEGER }, { key:"numbers", listNumbers:RANGES.INTEGER }, { key:"emptyList", flag:true }, { key:"_DEBUG", string:SYMBOLS }, // --- General values { key:"number", integer:RANGES.NUMBER }, { key:"smallNumber", integer:RANGES.SMALLNUMBER }, { key:"integer", integer:RANGES.INTEGER }, { key:"smallInteger", integer:RANGES.SMALLINTEGER }, { key:"float", float:RANGES.FLOAT }, { key:"largeNumber", integer:RANGES.LARGENUMBER }, { key:"undefined", flag:true }, { key:"string", string:SYMBOLS }, { key:"character", character:SYMBOLS }, // --- Specific values { key:"attribute", value:OBJECTATTRIBUTESLIST}, { key:"sublist", value:OBJECTATTRIBUTESLIST}, { key:"index", values:"*GETTERS*" }, { key:"randomNumber", flag:true }, { key:"randomValue", flag:true }, { key:"floor", flag:true }, { key:"angleTo", values:"*GETTERS*" }, { key:"distanceTo", values:"*GETTERS*" }, { key:"nearest", values:"*GETTERS*" }, { key:"farthest", values:"*GETTERS*" }, { key:"inArea", values:AREA }, // --- Processing { key:"abs", flag:true }, { key:"sqrt", flag:true }, { key:"sin", flag:true }, { key:"cos", flag:true }, { key:"acos", flag:true }, { key:"limit", listNumbers:RANGES.INTEGER }, { key:"oneRandom", flag:true }, { key:"prefix", string:SYMBOLS }, { key:"suffix", string:SYMBOLS }, { key:"negate", flag:true }, { key:"max", flag:true }, { key:"min", flag:true }, { key:"count", flag:true }, ]); if (mods.QUIRKS.unshift) SPRITEGETTERS.forEach(attr=>GETTERS.unshift(attr)); else SPRITEGETTERS.forEach(attr=>GETTERS.push(attr)); var GETTERS_UNPADDED=System.clone(GETTERS); System.padWithUnused(debug,"getters",64,GETTERS); // Used for assign var OBJECTATTRIBUTESASSIGN=[]; sys.SPRITEATTRIBUTES.forEach(attr=>OBJECTATTRIBUTESASSIGN.push({ key:attr.key, values: GETTERS } )); // Objectattributes is the same size of spriteattributes, which is already padded // --- VECTOR var VECTOR=System.padWithUnused(debug,"vector",2,[ { key:"angle", values:GETTERS }, { key:"by", values:GETTERS } ]); // --- AREA var THEN,CODE; sys.SYSTEMPROTOCOL=[{ key:"systemConfiguration", values:System.padWithUnused(debug,"system",16,[ // Pre-defined resolution { key:"resolutionModel", integer:RANGES.SMALLNUMBER }, // Custom resolution { key:"screenWidth", integer:RANGES.RESOLUTION }, { key:"screenHeight", integer:RANGES.RESOLUTION }, { key:"renderWidth", integer:RANGES.RESOLUTION }, { key:"renderHeight", integer:RANGES.RESOLUTION }, // Pre-defined palettes { key:"paletteModel", integer:RANGES.SMALLNUMBER }, // Custom palette { key:"palette", gridNumbers: RANGES.RGB }, { key:"defaultColor", integer:RANGES.SMALLNUMBER }, // Pre-defined font { key:"fontModel", integer:RANGES.SMALLNUMBER }, // Audio { key:"musicVolume", integer: RANGES.VOLUME }, { key:"effectsVolume", integer: RANGES.VOLUME }, // Loading time { key:"loadingTime", integer: RANGES.NUMBER }, // Frame rate { key:"fps", integer: RANGES.SMALLNUMBER }, // Controller { key:"controllerModel", integer:RANGES.SMALLNUMBER }, ]) }]; sys.DATAPROTOCOL=System.solveReferences([ { key:"data", values:System.padWithUnused(debug,"data",8,[ { key:"id", character:SYMBOLS }, { key:"music", values:System.padWithUnused(debug,"music",4,[ { key:"id", character:SYMBOLS }, { key:"notes", gridValue:NOTESLIST }, { key:"instruments", string:SYMBOLS } ]) }, { key:"songs", values:System.padWithUnused(debug,"songs",4,[ { key:"id", character:SYMBOLS }, { key:"music", string:SYMBOLS }, { key:"loopTo", integer:RANGES.SMALLNUMBER }, { key:"tempo", integer:RANGES.SMALLNUMBER } ]) }, { key:"sounds", values:System.padWithUnused(debug,"sounds",32,[ { key:"id", character:SYMBOLS }, { key:"channelId", character:SYMBOLS }, { key:"wave", value:["whitenoise","square","sine","saw","triangle","tangent","whistle","breaker"]}, { key:"bitCrush", integer:RANGES.AUDIORANGE }, { key:"bitCrushSweep", integer:RANGES.AUDIORANGE }, { key:"attack", integer:RANGES.AUDIORANGE }, { key:"sustain", integer:RANGES.AUDIORANGE }, { key:"limit", integer:RANGES.AUDIORANGE }, { key:"decay", integer:RANGES.AUDIORANGE }, { key:"release", integer:RANGES.AUDIORANGE }, { key:"frequency", integer:RANGES.AUDIORANGE }, { key:"tremoloFrequency", integer:RANGES.AUDIORANGE }, { key:"tremoloDepth", integer:RANGES.AUDIORANGE }, { key:"frequencyJump1onset", integer:RANGES.AUDIORANGE }, { key:"frequencyJump1amount", integer:RANGES.AUDIORANGE }, { key:"frequencyJump2onset", integer:RANGES.AUDIORANGE }, { key:"frequencyJump2amount", integer:RANGES.AUDIORANGE }, { key:"pitch", integer:RANGES.AUDIORANGE } ]) }, { key:"code", values:CODE=System.padWithUnused(debug,"code",32,[ { key:"times", values:GETTERS }, { key:"when", values:System.padWithUnused(debug,"when",64,GETTERS_UNPADDED.concat([ { key:"not", flag:true }, { key:"event", value:EVENTS }, { key:"if", values:System.padWithUnused(debug,"if",64,GETTERS_UNPADDED.concat([ { key:"is", value:System.padWithUnused(debug,"is",16,[ "existing", // Existence ">", ">=", "<", "<=", "!=", "==", "%%", // Logic "collidingWith", // Scene (to check object, just use {ids:"A"} as when clause) "up", "down", "hit", // Keyboard "under", "over", "onRightOf", "onLeftOf" // Relative position ])}, { key:"itsAttribute", value:OBJECTATTRIBUTESLIST },{ key:"deltaX", values:GETTERS },{ key:"deltaY", values:GETTERS } ])) }, { key:"bounds", values:System.padWithUnused(debug,"bounds",16,[ { key:"modeTop", value:BOUNDSMODES}, { key:"modeRight", value:BOUNDSMODES}, { key:"modeBottom", value:BOUNDSMODES}, { key:"modeLeft", value:BOUNDSMODES}, { key:"x", values:GETTERS }, { key:"y", values:GETTERS }, { key:"width", values:GETTERS }, { key:"height", values:GETTERS } ]) } ])) },{ key:"then", values:THEN=System.padWithUnused(debug,"then",128,GETTERS_UNPADDED.concat([ { key:"code", values:"*CODE*" }, // Allow nested code { key:"log",string:SYMBOLS }, // Random { key:"randomize", flag:true }, // Walls { key:"bounce", values:System.padWithUnused(debug,"bounce",4,[ { key:"speedX", values:GETTERS }, { key:"speedY", values:GETTERS }, { key:"restitutionX", values:GETTERS }, { key:"restitutionY", values:GETTERS } ])}, // Assign { key:"set", values:OBJECTATTRIBUTESASSIGN }, { key:"push", values:OBJECTATTRIBUTESASSIGN }, { key:"invert", values:OBJECTATTRIBUTESASSIGN }, { key:"sum", values:OBJECTATTRIBUTESASSIGN }, { key:"subtract", values:OBJECTATTRIBUTESASSIGN }, { key:"multiply", values:OBJECTATTRIBUTESASSIGN }, { key:"divide", values:OBJECTATTRIBUTESASSIGN }, { key:"module", values:OBJECTATTRIBUTESASSIGN }, { key:"pan", values:System.padWithUnused(debug,"pan",2,[ { key:"to", values:OBJECTATTRIBUTESASSIGN }, { key:"speed",values:GETTERS } ])}, // Area { key:"areaFlipX", flag:true }, { key:"areaFlipY", flag:true }, { key:"areaRotate", values:GETTERS }, { key:"areaCounterclockwise", flag:true }, { key:"areaCopy", values:System.padWithUnused(debug,"areaCopy",4,[ { key:"x", values:GETTERS }, { key:"y", values:GETTERS }, { key:"fromIds",string:SYMBOLS }, { key:"toIds",string:SYMBOLS } ])}, // Sprite add/remove { key:"remove", flag:true }, { key:"spawn", values:System.padWithUnused(debug,"spawn",2,[ { key:"at", values:GETTERS }, { key:"ids",values:GETTERS } ])}, { key:"fillAreaWithPattern", gridString:SYMBOLS }, { key:"outlineAreaWithPattern", gridString:SYMBOLS }, { key:"placeAt", values:GETTERS }, // Vectors { key:"moveTo", values:VECTOR }, { key:"speedTo", values:VECTOR }, { key:"setSpeedTo", values:VECTOR }, // Events { key:"triggerEvent", value:EVENTS }, { key:"forceEvent", flag:true }, // Audio - Sounds { key:"playAudio", values:GETTERS }, { key:"stopAudio", flag:true }, // Audio - Music { key:"stopChannel", values:GETTERS }, { key:"runSong", values:GETTERS }, { key:"stopSong", flag:true }, { key:"pauseSong", flag:true }, { key:"playSong", flag:true }, { key:"setSongTempo", values:GETTERS }, // Scene { key:"runScene", values:GETTERS }, // Reset scene and load { key:"load", values:GETTERS }, // Keep scene and overwrite memory // Code flow { key:"break", flag:true } ])) }, { key:"else", values:"*THEN*" } ]) }, { key:"images", values:System.padWithUnused(debug,"images",2,[ { key:"id", value:GRAPHICS }, { key:"image", image:true } ]) }, { key:"tilemaps", values:System.padWithUnused(debug,"tilemaps",16,[ { key:"tileWidth", integer:RANGES.SIZE }, { key:"tileHeight", integer:RANGES.SIZE }, { key:"backgroundColor", integer:RANGES.COLOR }, { key:"x", integer:RANGES.COORD }, { key:"y", integer:RANGES.COORD }, { key:"map", gridString:SYMBOLS }, { key:"song", character:SYMBOLS }, { key:"playAudio", character:SYMBOLS }, { key:"set", values:sys.SPRITEATTRIBUTES } ]) }, { key:"sprites", values:sys.SPRITEATTRIBUTES } ]) } ],{ "*THEN*":THEN, "*CODE*":CODE, "*GETTERS*":GETTERS }); return sys; } }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _range2 = require('lodash/range'); var _range3 = _interopRequireDefault(_range2); exports.default = SegmentedProgressBar; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Create a segmented progress bar for multi-page forms. * * @param {number} current - The index of the current chapter * @param {number} total - The total number of chapters in the form */ function SegmentedProgressBar(_ref) { var current = _ref.current, total = _ref.total; return _react2.default.createElement( 'div', { className: 'progress-bar-segmented', role: 'progressbar', 'aria-valuenow': current, 'aria-valuemin': '0', 'aria-valuemax': total, tabIndex: '0' }, (0, _range3.default)(total).map(function (step) { return _react2.default.createElement('div', { key: step, className: 'progress-segment ' + (current > step ? 'progress-segment-complete' : '') }); }) ); } SegmentedProgressBar.propTypes = { /** * The current segment in progress */ current: _propTypes2.default.number.isRequired, /** * The total number of segments in the progress bar */ total: _propTypes2.default.number.isRequired }; //# sourceMappingURL=SegmentedProgressBar.js.map
/** * Copyright 2021 F5 Networks, Inc. * * 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 formatStr = require('./formatStr'); const defaults = require('../../lib/bigipDefaults.json'); module.exports = (str) => { str = formatStr(str); let pathSplit = ''; if (defaults.includes(str)) return { bigip: str }; pathSplit = str.split('/'); if (pathSplit.length === 3) str = str.replace(`/${pathSplit[1]}/`, `/${pathSplit[1]}/Shared/`); return { use: str }; };
/* * RaiBlocks extended functions in JavaScript * https://github.com/SergiySW/RaiBlocksJS * * Released under the BSD 3-Clause License * */ // Global variables: block_count, count, unchecked, frontier_count, frontiers, peers var RaiBlocks = RaiBlocks || {} Rai.prototype.initialize = function () { } // Extended function, jQuery is required Rai.prototype.ext_account_history = function (account, count) { var rpc_request = this if (typeof RaiBlocks.frontiers === 'undefined') this.initialize() // if not initialized var hash = RaiBlocks.frontiers[account] if (typeof hash !== 'undefined') { var account_history = this.history(hash) var chain = this.chain(hash) // Retrieve change blocks $.each(chain, function (key, value) { if (account_history[key].hash !== value) { let block = rpc_request.block(value) if (block.type == 'change') { let insert = {account: block.representative, amount: 0, hash: value, type: block.type} account_history.splice(key, 0, insert) } } }) } else { console.log('Empty account ' + account) } return account_history } Rai.prototype.load_info = function () { RaiBlocks.available_supply = this.available_supply() RaiBlocks.block_count = this.block_count() RaiBlocks.count = RaiBlocks.block_count.count RaiBlocks.unchecked = RaiBlocks.block_count.unchecked RaiBlocks.frontier_count = this.frontier_count() RaiBlocks.frontiers = this.frontiers() RaiBlocks.peers = this.peers() } // Extended function, jQuery is required Rai.prototype.wallet_accounts_info = function (wallet, count) { var rpc_request = this if (typeof RaiBlocks.frontiers === 'undefined') this.initialize() // if not initialized var accounts_list = rpc_request.account_list(wallet) var wallet_accounts_info = [] // Accounts Array + balances $.each(accounts_list, function () { let account_balance = rai.account_balance(this) let balance = account_balance.balance let pending = account_balance.pending let history = rai.ext_account_history(this, count) wallet_accounts_info.push({key: this, raw_balance: balance, balance: rai.unit(balance, 'raw', 'rai'), raw_pending: pending, pending: rai.unit(pending, 'raw', 'rai'), history: history}) }) return wallet_accounts_info } Rai.prototype.rpc_version = function () { var rpc_version = this.version().rpc_version return rpc_version } Rai.prototype.store_version = function () { var store_version = this.version().store_version return store_version } Rai.prototype.node_vendor = function () { var node_vendor = this.version().node_vendor return node_vendor } // String output Rai.prototype.balance = function (account, unit = 'raw') { var account_balance = this.account_balance(account) var balance = this.unit(account_balance.balance, 'raw', unit) return balance } // String output Rai.prototype.account_pending = function (account, unit = 'raw') { var account_balance = this.account_balance(account) var pending = this.unit(account_balance.pending, 'raw', unit) return pending } // String output Rai.prototype.count = function () { var count = this.block_count().count return count } // String output Rai.prototype.unchecked_count = function () { var unchecked_count = this.block_count().unchecked return unchecked_count } // String output Rai.prototype.wallet_balance = function (wallet, unit = 'raw') { var wallet_balance = this.wallet_balance_total(wallet, unit) return wallet_balance } // String output Rai.prototype.wallet_pending = function (wallet, unit = 'raw') { var wallet_pending = this.wallet_balance_total(wallet, unit) return wallet_pending } // Arrays manipulations uint8_uint4 = function (uint8) { var length = uint8.length var uint4 = new Uint8Array(length * 2) for (let i = 0; i < length; i++) { uint4[i * 2] = uint8[i] / 16 | 0 uint4[i * 2 + 1] = uint8[i] % 16 } return uint4 } uint4_uint8 = function (uint4) { var length = uint4.length / 2 var uint8 = new Uint8Array(length) for (let i = 0; i < length; i++) uint8[i] = uint4[i * 2] * 16 + uint4[i * 2 + 1] return uint8 } uint4_uint5 = function (uint4) { var length = uint4.length / 5 * 4 var uint5 = new Uint8Array(length) for (let i = 1; i <= length; i++) { let n = i - 1 let m = i % 4 let z = n + ((i - m) / 4) let right = uint4[z] << m let left if (((length - i) % 4) == 0) left = uint4[z - 1] << 4 else left = uint4[z + 1] >> (4 - m) uint5[n] = (left + right) % 32 } return uint5 } uint5_uint4 = function (uint5) { var length = uint5.length / 4 * 5 var uint4 = new Uint8Array(length) for (let i = 1; i <= length; i++) { let n = i - 1 let m = i % 5 let z = n - ((i - m) / 5) let right = uint5[z - 1] << (5 - m) let left = uint5[z] >> m uint4[n] = (left + right) % 16 } return uint4 } string_uint5 = function (string) { var letter_list = letter_list = '13456789abcdefghijkmnopqrstuwxyz'.split('') var length = string.length var string_array = string.split('') var uint5 = new Uint8Array(length) for (let i = 0; i < length; i++) uint5[i] = letter_list.indexOf(string_array[i]) return uint5 } uint5_string = function (uint5) { var letter_list = letter_list = '13456789abcdefghijkmnopqrstuwxyz'.split('') var string = ''; for (let i = 0; i < uint5.length; i++) string += letter_list[uint5[i]] return string } hex_uint8 = function (hex) { var length = (hex.length / 2) | 0 var uint8 = new Uint8Array(length) for (let i = 0; i < length; i++) uint8[i] = parseInt(hex.substr(i * 2, 2), 16) return uint8 } uint4_hex = function (uint4) { var hex = ''; for (let i = 0; i < uint4.length; i++) hex += uint4[i].toString(16).toUpperCase() return (hex) } uint8_hex = function (uint8) { var hex = uint4_hex(uint8_uint4(uint8)) return (hex) } int_uint8 = function (integer, length) { var uint8 = new Uint8Array(length) for (var index = 0; index < length; index++) { var byte = integer & 0xff uint8[ index ] = byte integer = (integer - byte) / 256 } return uint8 }; equal_arrays = function (array1, array2) { for (let i = 0; i < array1.length; i++) { if (array1[i] != array2[i]) return false } return true } array_crop = function (array) { var length = array.length - 1 var cropped_array = new Uint8Array(length) for (let i = 0; i < length; i++) cropped_array[i] = array[i + 1] return cropped_array } array_extend = function (array) { var length = array.length + 1 var extended_array = new Uint8Array(length) for (let i = 0; i < (length - 1); i++) extended_array[i + 1] = array[i] return extended_array } // Arrays manipulations // String output random_hex = function () { var array = new Uint8Array(32) crypto.getRandomValues(array) var hex = uint8_hex(array) return hex } XRB.createSeedHex = function () { return random_hex() } // String output XRB.account_get = function (key) { var isValid = /^[0123456789ABCDEF]+$/.test(key) if (isValid && (key.length == 64)) { var key_array = hex_uint8(key) var bytes = uint4_uint5(array_extend(uint8_uint4(key_array))) var blake_hash = blake2b(key_array, null, 5).reverse() var hash_bytes = uint4_uint5(uint8_uint4(blake_hash)) var account = 'xrb_' + uint5_string(bytes) + uint5_string(hash_bytes) return account } else { XRB.error('Invalid public key') return false } } Rai.prototype.ext_account_get = function (key) { return XRB.account_get(key) } // String output XRB.account_key = function (account) { if ((account.startsWith('xrb_1') || account.startsWith('xrb_3')) && (account.length == 64)) { var account_crop = account.substring(4, 64) var isValid = /^[13456789abcdefghijkmnopqrstuwxyz]+$/.test(account_crop) if (isValid) { var key_uint4 = array_crop(uint5_uint4(string_uint5(account_crop.substring(0, 52)))) var hash_uint4 = uint5_uint4(string_uint5(account_crop.substring(52, 60))) var key_array = uint4_uint8(key_uint4) var blake_hash = blake2b(key_array, null, 5).reverse() if (equal_arrays(hash_uint4, uint8_uint4(blake_hash))) { var key = uint4_hex(key_uint4) return key } else { XRB.error('Invalid account') return false } } else { XRB.error('Invalid symbols') return false } } else { XRB.error('Invalid account') return false } } Rai.prototype.ext_account_key = function (account) { return XRB.account_key(account) } // Boolean output XRB.account_validate = function (account) { var valid = XRB.account_key(account) if (valid) return true else return false } Rai.prototype.account_validate = function (account) { return XRB.account_validate(account) } function pow_threshold (Uint8Array) { if ((Uint8Array[0] == 255) && (Uint8Array[1] == 255) && (Uint8Array[2] == 255) && (Uint8Array[3] >= 192)) return true else return false } XRB.pow_initiate = function (threads, worker_path = '') { if (isNaN(threads)) { threads = self.navigator.hardwareConcurrency - 1 } var workers = [] for (let i = 0; i < threads; i++) { workers[i] = new Worker(worker_path + 'rai.pow.js') } return workers } Rai.prototype.pow_initiate = function (threads, worker_path = '') { return XRB.pow_initiate(threads, worker_path) } // hash input as Uint8Array XRB.pow_start = function (workers, hash) { if ((hash instanceof Uint8Array) && (hash.length == 32)) { var threads = workers.length for (let i = 0; i < threads; i++) { workers[i].postMessage(hash) } } else XRB.error('Invalid hash array') } Rai.prototype.pow_start = function (workers, hash) { return XRB.pow_start(workers, hash) } XRB.pow_terminate = function (workers) { var threads = workers.length for (let i = 0; i < threads; i++) { workers[i].terminate() } } Rai.prototype.pow_terminate = function (workersh) { return XRB.pow_terminate(workers) } // hash input as Uint8Array, callback as function XRB.pow_callback = function (workers, hash, callback) { if ((hash instanceof Uint8Array) && (hash.length == 32) && (typeof callback === 'function')) { var threads = workers.length for (let i = 0; i < threads; i++) { workers[i].onmessage = function (e) { result = e.data if (result) { XRB.pow_terminate(workers) callback(result) } else workers[i].postMessage(hash) } } } else if (typeof callback !== 'function') XRB.error('Invalid callback function') else XRB.error('Invalid hash array') } Rai.prototype.pow_callback = function (workers, hash, callback) { return XRB.pow_callback(workers, hash, callback) } // hash_hex input as text, callback as function XRB.pow = function (hash_hex, threads, callback, worker_path) { var isValid = /^[0123456789ABCDEF]+$/.test(hash_hex) if (isValid && (hash_hex.length == 64)) { var hash = hex_uint8(hash_hex) var workers = XRB.pow_initiate(threads, worker_path) XRB.pow_start(workers, hash) XRB.pow_callback(workers, hash, callback) } else XRB.error('Invalid hash') } Rai.prototype.pow = function (hash_hex, threads, callback, worker_path) { return XRB.pow(hash_hex, threads, callback, worker_path) } // Boolean output XRB.pow_validate = function (pow_hex, hash_hex) { var isValidHash = /^[0123456789ABCDEF]+$/.test(hash_hex) if (isValidHash && (hash_hex.length == 64)) { var hash = hex_uint8(hash_hex) var isValidPOW = /^[0123456789ABCDEFabcdef]+$/.test(pow_hex) if (isValidPOW && (pow_hex.length == 16)) { var pow = hex_uint8(pow_hex) var context = blake2bInit(8, null) blake2bUpdate(context, pow.reverse()) blake2bUpdate(context, hash) var check = blake2bFinal(context).reverse() if (pow_threshold(check)) return true else return false } else { XRB.error('Invalid work') return false } } else { XRB.error('Invalid hash') return false } } Rai.prototype.pow_validate = function (pow_hex, hash_hex) { return XRB.pow_validate(pow_hex, hash_hex) } // String output XRB.seed_key = function (seed_hex, index = 0) { var isValidHash = /^[0123456789ABCDEF]+$/.test(seed_hex) if (isValidHash && (seed_hex.length == 64)) { var seed = hex_uint8(seed_hex) if (Number.isInteger(index)) { var uint8 = int_uint8(index, 4) var context = blake2bInit(32, null) blake2bUpdate(context, seed) blake2bUpdate(context, uint8.reverse()) var key = uint8_hex(blake2bFinal(context)) return key } else { XRB.error('Invalid index') return false } } else { XRB.error('Invalid seed') return false } } Rai.prototype.seed_key = function (seed_hex, index) { return XRB.seed_key(seed_hex, index) } // Array output XRB.seed_keys = function (seed_hex, count = 1) { var isValidHash = /^[0123456789ABCDEF]+$/.test(seed_hex) if (isValidHash && (seed_hex.length == 64)) { var seed = hex_uint8(seed_hex) if (Number.isInteger(count)) { var keys = [] for (let index = 0; index < count; index++) { var uint8 = int_uint8(index, 4) var context = blake2bInit(32, null) blake2bUpdate(context, seed) blake2bUpdate(context, uint8.reverse()) keys.push(uint8_hex(blake2bFinal(context))) } return keys } else { XRB.error('Invalid count') return false } } else { XRB.error('Invalid seed') return false } } XRB.publicFromPrivateKey = function (secretKey) { if (!/[0-9A-F]{64}/i.test(secretKey)) { XRB.error = 'Invalid secret key. Should be a 32 byte hex string.'; return false } return uint8_hex(nacl.sign.keyPair.fromSecretKey(hex_uint8(secretKey)).publicKey) } Rai.prototype.publicFromPrivateKey = function (secretKey) { return XRB.publicFromPrivateKey(secretKey) } XRB.key_account = function (private_key) { return XRB.account_get(XRB.publicFromPrivateKey(private_key)) } XRB.signBlock = function (blockHash, secretKey) { if (!/[0-9A-F]{64}/i.test(secretKey)) { XRB.error = 'Invalid secret key. Should be a 32 byte hex string.'; return false } if (!/[0-9A-F]{64}/i.test(blockHash)) { XRB.error = 'Invalid block hash. Should be a 32 byte hex string.'; return false } return uint8_hex(nacl.sign.detached(hex_uint8(blockHash), hex_uint8(secretKey))) } Rai.prototype.signBlock = function (blockHash, secretKey) { return XRB.signBlock(blockHash, secretKey) } XRB.checkSignature = function (hexMessage, hexSignature, publicKeyOrXRBAccount) { if (!/[0-9A-F]{128}/i.test(signature)) { XRB.error = 'Invalid signature. Needs to be a 64 byte hex encoded ed25519 signature.'; return false } if (/[0-9A-F]{64}/i.test(publicKeyOrXRBAccount)) { // it's a 32 byte hex encoded key return nacl.sign.detached.verify(hex_uint8(hexMessage), hex_uint8(hexSignature), hex_uint8(publicKeyOrXRBAccount)) } else { var pubKey = XRB.account_key(publicKeyOrXRBAccount) if (pubKey) { // it's a XRB account return nacl.sign.detached.verify(hex_uint8(hexMessage), hex_uint8(hexSignature), hex_uint8(pubKey)) } XRB.error = 'Invalid public key or XRB account.'; return false } } Rai.prototype.checkSignature = function (hexMessage, hexSignature, publicKeyOrXRBAccount) { return XRB.checkSignature(hexMessage, hexSignature, publicKeyOrXRBAccount) } /** * Computes the block hash given its type and the required parameters * Parameters should be hex encoded (block hashes, accounts (its public key) and balances) * * @param {string} blockType - send, receive, change and open * @param {object} parameters - {previous: "", destination: "", balance: ""} (send) * {previous: "", source: ""} (receive) * {previous: "", representative: "" } (change) * {source: "", representative: "", account: "" } (open) * @returns {string} The block hash */ XRB.computeBlockHash = function (blockType, parameters){ if ((typeof parameters.destination !== 'undefined') && (parameters.destination.startsWith('xrb_'))) parameters.destination = XRB.account_key(parameters.destination) if ((typeof parameters.representative !== 'undefined') && (parameters.representative.startsWith('xrb_'))) parameters.representative = XRB.account_key(parameters.representative) if ((typeof parameters.account !== 'undefined') && (parameters.account.startsWith('xrb_'))) parameters.account = XRB.account_key(parameters.account) if ((typeof parameters.type !== 'undefined') && (blockType == null)) blockType = parameters.type if ( blockType == 'send' && ( !/[0-9A-F]{64}/i.test(parameters.previous) || !/[0-9A-F]{64}/i.test(parameters.destination) || !/[0-9A-F]{32}/i.test(parameters.balance) ) || blockType == 'receive' && ( !/[0-9A-F]{64}/i.test(parameters.previous) || !/[0-9A-F]{64}/i.test(parameters.source) ) || blockType == 'open' && ( !/[0-9A-F]{64}/i.test(parameters.source) || !/[0-9A-F]{64}/i.test(parameters.representative) || !/[0-9A-F]{64}/i.test(parameters.account) ) || blockType == 'change' && ( !/[0-9A-F]{64}/i.test(parameters.previous) || !/[0-9A-F]{64}/i.test(parameters.representative) ) ) { XRB.error = 'Invalid parameters.'; return false } var hash switch (blockType) { case 'send': var context = blake2bInit(32, null) blake2bUpdate(context, hex_uint8(parameters.previous)) blake2bUpdate(context, hex_uint8(parameters.destination)) blake2bUpdate(context, hex_uint8(parameters.balance)) hash = uint8_hex(blake2bFinal(context)) break; case 'receive': var context = blake2bInit(32, null) blake2bUpdate(context, hex_uint8(parameters.previous)) blake2bUpdate(context, hex_uint8(parameters.source)) hash = uint8_hex(blake2bFinal(context)) break; case 'open': var context = blake2bInit(32, null) blake2bUpdate(context, hex_uint8(parameters.source)) blake2bUpdate(context, hex_uint8(parameters.representative)) blake2bUpdate(context, hex_uint8(parameters.account)) hash = uint8_hex(blake2bFinal(context)) break; case 'change': var context = blake2bInit(32, null) blake2bUpdate(context, hex_uint8(parameters.previous)) blake2bUpdate(context, hex_uint8(parameters.representative)) hash = uint8_hex(blake2bFinal(context)) break; default: XRB.error = 'Invalid block type.'; return false } return hash }
/** * Copyright 2019 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. */ import {ActionSource} from './action-source'; import { Alignment, Axis, findOverlappingIndex, getDimension, getOffsetStart, scrollContainerToElement, setScrollPosition, setTransformTranslateStyle, updateLengthStyle, } from './dimensions.js'; import {AutoAdvance} from './auto-advance'; import { backwardWrappingDistance, forwardWrappingDistance, } from './array-util'; import {createCustomEvent, listenOnce} from '../../../src/event-helper'; import {debounce} from '../../../src/utils/rate-limit'; import {dict} from '../../../src/utils/object'; import { getStyle, setImportantStyles, setStyle, setStyles, } from '../../../src/style'; import {iterateCursor} from '../../../src/dom'; import {mod} from '../../../src/utils/math'; /** * How long to wait prior to resetting the scrolling position after the last * scroll event. Ideally this should be low, so that once the user stops * scrolling, things are immediately centered again. Since there can be some * delay between scroll events, and we do not want to move things during a * scroll, it cannot be too small. 200ms seems to be around the lower limit for * this value on Android / iOS. */ const RESET_SCROLL_REFERENCE_POINT_WAIT_MS = 200; /** * Runs a callback while disabling smooth scrolling by temporarily setting * the `scrollBehavior` to `auto`. * @param {!Element} el * @param {Function} cb */ function runDisablingSmoothScroll(el, cb) { const scrollBehavior = getStyle(el, 'scrollBehavior'); setStyle(el, 'scrollBehavior', 'auto'); cb(); setStyle(el, 'scrollBehavior', scrollBehavior); } /** * @param {!Array<number>} arr * @return {number} */ function sum(arr) { return arr.reduce((p, c) => p + c, 0); } /** * How the carousel works when looping: * * We want to make sure that the user can scroll all the way to the opposite * end (either forwards or backwards) of the carousel, but no further (no * looping back past where you started). We use spacer elements to adjust the * scroll width of the scrolling area to allow the browser to scroll as well as * providing targets for the browser to snap on. This is important as these * targets need to be present before the scroll starts for things to work * correctly. * * The spacers come in 3 types: * * - beforeSpacers: These provide scroll/snap before the first slide * - replacementSpacers: These take up the spot of the slides as they are * translated around * - afterSpacers: These provide scroll/snap targets after the last slide * * The spacers are then hidden/shown depending on the reference point, called * the restingIndex to allow full movement forwards and backwards. You can * imagine this looks like the following if you have 5 slides: * * [r][r][r][r][r] * [b][b][b][b][b][1][2][3][4][5][a][a][a][a][a] * * b = beforeSpacer, r = replacementSpacer, a = afterSpacer * * The replacement spacers are stacked on top of the slides. * When the restingIndex is the first index, we should translate slides and * hide the spacers as follows: * * [h][ ][ ][4][5][1][2][3][ ][ ][h][h][h][h][h] * * h = hidden * * This ensures that if you move left or right, there is a slide to show. Note * that we have two empty slots at the start, where slides '2' and '3' will * be moved as the user scrolls. Likewise, we have two slots at the end, where * slides '4' and '5' will move. Since the other spacers are hidden, the * browser cannot scroll into that area. * * When the user stops scrolling, we update the restingIndex and show/hide the * appropriate spacers. For example, if the user started at slide '1' and moved * left to slide '4', the UI would update to the following as they scrolled: * * [h][2][3][4][5][1][ ][ ][ ][ ][h][h][h][h][h] * * Once scrolling stopped, the reference point would be reset and this would * update to: * * [h][h][h][h][ ][ ][2][3][4][5][1][ ][ ][h][h] * * Moving slides: * * Slides are moved around using `transform: translate` relative to their * original resting spot. Slides are moved to be before or after the current * slide as the user scrolls. Currently, half the slides are moved before and * half the slides are moved after. This could be a bit smarter and only move * as many as are necessary to have a sufficient amount of buffer. When slides * are moved, they are positioned on top of an existing spacer. * * Initial index: * * The initial index can be specified, which will make the carousel scroll to * the desired index when it first renders. Since the layout of the slides is * asynchronous, this should be used instead of calling `goToSlide` after * creating the carousel. */ export class Carousel { /** * @param {{ * win: !Window, * element: !Element, * scrollContainer: !Element, * initialIndex: (number|undefined), * runMutate: function(function()), * }} config */ constructor({ win, element, scrollContainer, initialIndex = 0, runMutate, }) { /** @private @const */ this.win_ = win; /** @private @const */ this.runMutate_ = runMutate; /** @private @const */ this.element_ = element; /** @private @const */ this.scrollContainer_ = scrollContainer; /** @private @const */ this.autoAdvance_ = new AutoAdvance({ win, scrollContainer, advanceable: this, }); /** @private @const */ this.debouncedResetScrollReferencePoint_ = debounce( win, () => this.resetScrollReferencePoint_(), RESET_SCROLL_REFERENCE_POINT_WAIT_MS); /** @private {number} */ this.advanceCount_ = 1; /** @private {number} */ this.autoAdvanceLoops_ = Number.POSITIVE_INFINITY; /** @private {boolean} */ this.mixedLength_ = false; /** @private {!Array<!Element>} */ this.slides_ = []; /** @private {boolean} */ this.userScrollable_ = true; /** @private {boolean} */ this.updating_ = false; /**@private {!Array<!Element>} */ this.beforeSpacers_ = []; /** @private {!Array<!Element>} */ this.replacementSpacers_ = []; /** @private {!Array<!Element>} */ this.afterSpacers_ = []; /** @private {!Array<!Element>} */ this.allSpacers_ = []; /** * Set from sources of programmatic scrolls to avoid doing work associated * with regular scrolling. * @private {boolean} */ this.ignoreNextScroll_ = false; /** * The offset from the start edge for the element at the current index. * This is used to preserve relative scroll position when updating the UI * after things have moved (e.g. on rotate). * @private {number} */ this.currentElementOffset_ = 0; /** * The reference index where the the scrollable area last stopped * scrolling. This slide is not translated and other slides are translated * to move before or after as needed. This is also used when looping to * prevent a single swipe from wrapping past the starting point. * @private {number} */ this.restingIndex_ = NaN; /** * Whether or not the user is currently touching the scrollable area. This * is used to avoid resetting the resting point while the user is touching * (e.g. they have dragged part way to the next slide, but have not yet * released their finger). * @private {boolean} */ this.touching_ = false; /** * Tracks the source of what cause the carousel to change index. This can * be provided when moving the carousel programmatically, and the value * will be propagated. * @private {!ActionSource|undefined} */ this.actionSource_ = undefined; /** @private {!Alignment} */ this.alignment_ = Alignment.START; /** @private {!Axis} */ this.axis_ = Axis.X; /** * TODO(sparhami) Rename this to `activeIndex`. We do not want to expose * this as it changes, only when the user stops scrolling. Also change * restingIndex to currentIndex. * @private {number} */ this.currentIndex_ = initialIndex; /** @private {boolean} */ this.loop_ = false; /** @private {boolean} */ this.snap_ = true; /** @private {number} */ this.snapBy_ = 1; /** @private {number} */ this.visibleCount_ = 1; this.scrollContainer_.addEventListener( 'scroll', () => this.handleScroll_(), true); this.scrollContainer_.addEventListener( 'touchstart', () => this.handleTouchStart_(), true); this.scrollContainer_.addEventListener( 'wheel', () => this.handleWheel_(), true); } /** * Moves forward by the current advance count. * @param {!ActionSource=} actionSource */ next(actionSource) { this.advance(this.advanceCount_, actionSource); } /** * Moves backwards by the current advance count. * @param {!ActionSource=} actionSource */ prev(actionSource) { this.advance(-this.advanceCount_, actionSource); } /** * Moves the current index forward/backwards by a given delta and scrolls * the new index into view. There are a few cases where this behaves * differently than might be expected when not looping: * * 1. The current index is in the last group, then the new index will be the * zeroth index. For example, say you have four slides, 'a', 'b', 'c' and 'd', * you are showing two at a time, start aligning slides and are advancing one * slide at a time. If you are on slide 'c', advancing will move back to 'a' * instead of moving to 'd', which would cause no scrolling since 'd' is * already visible and cannot start align itself. * 2. The delta would go past the start or the end and the the current index * is not at the start or end, then the advancement is capped to the start * or end respectively. * 3. The delta would go past the start or the end and the current index is * at the start or end, then the next index will be the opposite end of the * carousel. * * TODO(sparhami) How can we make this work well for accessibility? * @param {number} delta * @param {!ActionSource=} actionSource */ advance(delta, actionSource) { const {slides_: slides, currentIndex_} = this; const newIndex = currentIndex_ + delta; const endIndex = slides.length - 1; const atStart = currentIndex_ == 0; const atEnd = currentIndex_ == endIndex; const passingStart = newIndex < 0; const passingEnd = newIndex > endIndex; let slideIndex; if (this.loop_) { slideIndex = mod(newIndex, endIndex + 1); } else if (delta > 0 && this.inLastWindow_(currentIndex_) && this.inLastWindow_(newIndex)) { slideIndex = 0; } else if ((passingStart && atStart) || (passingEnd && !atEnd)) { slideIndex = endIndex; } else if ((passingStart && !atStart) || (passingEnd && atEnd)) { slideIndex = 0; } else { slideIndex = newIndex; } this.goToSlide(slideIndex, {actionSource}); } /** * @return {number} The current index of the carousel. */ getCurrentIndex() { return this.currentIndex_; } /** * Moves the carousel to a given index. If the index is out of range, the * carousel is not moved. * @param {number} index * @param {{ * smoothScroll: (boolean|undefined), * actionSource: (!ActionSource|undefined), * }=} options */ goToSlide(index, {smoothScroll = true, actionSource} = {}) { if (index < 0 || index > this.slides_.length - 1 || isNaN(index)) { return; } if (index == this.currentIndex_) { return; } this.actionSource_ = actionSource; this.scrollSlideIntoView_(this.slides_[index], {smoothScroll}); } /** * @param {number} advanceCount How many slides to advance by. This is the * number of slides moved forwards/backwards when calling prev/next. */ updateAdvanceCount(advanceCount) { this.advanceCount_ = advanceCount; } /** * @param {string} alignment How to align slides when snapping or scrolling * to the propgramatticaly (auto advance or next/prev). This should be * either "start" or "cemter". */ updateAlignment(alignment) { this.alignment_ = alignment == 'start' ? Alignment.START : Alignment.CENTER; this.updateUi(); } /** * @param {boolean} autoAdvance Whether or not to autoadvance. Changing this * will start or stop autoadvance. */ updateAutoAdvance(autoAdvance) { this.autoAdvance_.updateAutoAdvance(autoAdvance); } /** * @param {number} autoAdvanceCount How many items to advance by. A positive * number advances forwards, a negative number advances backwards. */ updateAutoAdvanceCount(autoAdvanceCount) { this.autoAdvance_.updateAutoAdvanceCount(autoAdvanceCount); } /** * @param {number} autoAdvanceInterval How much time between auto advances. * This time starts counting from when scrolling has stopped. */ updateAutoAdvanceInterval(autoAdvanceInterval) { this.autoAdvance_.updateAutoAdvanceInterval(autoAdvanceInterval); } /** * @param {number} autoAdvanceLoops The number of loops through the carousel * that should be autoadvanced before stopping. This defaults to infinite * loops. */ updateAutoAdvanceLoops(autoAdvanceLoops) { this.autoAdvanceLoops_ = autoAdvanceLoops; this.updateUi(); } /** * @param {boolean} horizontal Whether the scrollable should lay out * horizontally or vertically. */ updateHorizontal(horizontal) { this.axis_ = horizontal ? Axis.X : Axis.Y; this.updateUi(); } /** * @param {boolean} loop Whether or not the scrollable should loop when * reaching the last slide. */ updateLoop(loop) { this.loop_ = loop; this.updateUi(); } /** * @param {boolean} mixedLength Whether the slides used mixed lengths or they * should be have a length assigned in accordance to the visible count. */ updateMixedLength(mixedLength) { this.mixedLength_ = mixedLength; this.updateUi(); } /** * Lets the scrollable know that the slides have changed. This is needed for * various internal calculations. * @param {!Array<!Element>} slides */ updateSlides(slides) { this.slides_ = slides; this.updateUi(); } /** * @param {boolean} snap Whether or not to snap. */ updateSnap(snap) { this.snap_ = snap; this.updateUi(); } /** * @param {number} snapBy Snaps on every nth slide, including the zeroth * slide. */ updateSnapBy(snapBy) { this.snapBy_ = Math.max(1, snapBy); this.updateUi(); } /** * * @param {boolean} userScrollable Whether or not the carousel can be * scrolled (e.g. via touch). If false, then the carousel can only be * advanced via next, prev, goToSlide or autoAdvance. */ updateUserScrollable(userScrollable) { this.userScrollable_ = userScrollable; this.updateUi(); } /** * Updates the UI of the carousel. Since screen rotation can change scroll * position, this should be called to restore the scroll position (i.e. which * slide is at the start / center of the scrollable, depending on alignment). */ updateUi() { if (this.updating_) { return; } this.updating_ = true; this.runMutate_(() => { this.updating_ = false; this.scrollContainer_.setAttribute('mixed-length', this.mixedLength_); this.scrollContainer_.setAttribute( 'user-scrollable', this.userScrollable_); this.scrollContainer_.setAttribute('horizontal', this.axis_ == Axis.X); this.scrollContainer_.setAttribute('loop', this.loop_); this.scrollContainer_.setAttribute('snap', this.snap_); // TODO(sparhami) Do not use CSS custom property setImportantStyles(this.scrollContainer_, { '--visible-count': this.visibleCount_, }); if (!this.slides_.length) { return; } this.autoAdvance_.updateMaxAdvances( (this.autoAdvanceLoops_ * this.slides_.length) - 1); this.updateSpacers_(); this.setChildrenSnapAlign_(); this.hideSpacersAndSlides_(); this.resetScrollReferencePoint_(/* force */true); }); } /** * @param {number} visibleCount How many slides to show at a time within the * scrollable. This option is ignored if mixed lengths is set. */ updateVisibleCount(visibleCount) { this.visibleCount_ = Math.max(1, visibleCount); this.updateUi(); } /** * Updates the current index as well as firing an event. * @param {number} currentIndex The new current index. * @private */ updateCurrentIndex_(currentIndex) { this.currentIndex_ = currentIndex; this.element_.dispatchEvent( createCustomEvent(this.win_, 'indexchange', dict({ 'index': currentIndex, 'actionSource': this.actionSource_, }))); } /** * Handles a touch start, preventing the restWindow_ from running until the * user stops touching. * @private */ handleTouchStart_() { this.touching_ = true; this.actionSource_ = ActionSource.TOUCH; listenOnce(window, 'touchend', () => { this.touching_ = false; this.debouncedResetScrollReferencePoint_(); }, { capture: true, }); } /** * Handles a wheel event. * @private */ handleWheel_() { this.actionSource_ = ActionSource.WHEEL; } /** * Handles a scroll event, updating the the current index as well as moving * slides around as needed. * @private */ handleScroll_() { if (this.ignoreNextScroll_) { this.ignoreNextScroll_ = false; return; } this.updateCurrent_(); this.debouncedResetScrollReferencePoint_(); } /** * @param {!Element} el The slide or spacer to move. * @param {number} revolutions How many revolutions forwards (or backwards) * the slide or spacer should move. * @param {number} revolutionLength The length of a single revolution around * the scrollable area. * @private */ setElementTransform_(el, revolutions, revolutionLength) { setTransformTranslateStyle( this.axis_, el, revolutions * revolutionLength); el._revolutions = revolutions; } /** * Resets the transforms for all the slides, putting them back in their * natural position. * @param {number} totalLength The total length of all the slides. * @private */ resetSlideTransforms_(totalLength) { const revolutions = 0; // Sets the slide back to the initial position. this.slides_.forEach(slide => { this.setElementTransform_(slide, revolutions, totalLength); }); } /** * @return {!Array<number>}} An array of the lengths of the slides. * @private */ getSlideLengths_() { return this.slides_.map(s => getDimension(this.axis_, s).length); } /** * @param {number} count The number of spacers to create * @return {!Array<!Element>} An array of spacers. * @private */ createSpacers_(count) { const spacers = []; for (let i = 0; i < count; i++) { const spacer = document.createElement('div'); spacer.className = 'i-amphtml-carousel-spacer'; spacers.push(spacer); } return spacers; } /** * Updates the spacers, removing the old ones and creating new ones. * @private */ updateSpacers_() { const {axis_, slides_} = this; const slideLengths = this.getSlideLengths_(); const totalLength = sum(slideLengths); const count = this.loop_ ? slides_.length : 0; // Replace the before spacers. this.beforeSpacers_.forEach(spacer => { this.scrollContainer_.removeChild(spacer); }); this.beforeSpacers_ = this.createSpacers_(count); this.beforeSpacers_.forEach((spacer, i) => { updateLengthStyle(axis_, spacer, slideLengths[i]); this.scrollContainer_.insertBefore(spacer, slides_[0]); }); // Replace the replacement spacers. this.replacementSpacers_.forEach(spacer => { this.scrollContainer_.removeChild(spacer); }); this.replacementSpacers_ = this.createSpacers_(count); this.replacementSpacers_.forEach((spacer, i) => { updateLengthStyle(axis_, spacer, slideLengths[i]); // Translate these 1 revolution up, so they end up on top of the slides. this.setElementTransform_(spacer, -1, totalLength); this.scrollContainer_.appendChild(spacer); }); // Replace the after spacers. this.afterSpacers_.forEach(spacer => { this.scrollContainer_.removeChild(spacer); }); this.afterSpacers_ = this.createSpacers_(count); this.afterSpacers_.forEach((spacer, i) => { updateLengthStyle(axis_, spacer, slideLengths[i]); // Translate these 1 revolution up, so they end up right after the // slides (where the replacement spacers were). this.setElementTransform_(spacer, -1, totalLength); this.scrollContainer_.appendChild(spacer); }); this.allSpacers_ = this.beforeSpacers_ .concat(this.replacementSpacers_, this.afterSpacers_); } /** * Updates the snap-align for all spacers/slides. The spacers have the same * snap property as the associated slide. * @private */ setChildrenSnapAlign_() { const slideCount = this.slides_.length; const startAligned = this.alignment_ == Alignment.START ; const oddVisibleCount = mod(this.visibleCount_, 2) == 1; // For the legacy scroll-snap-coordinate, when center aligning with an odd // count, actually use a start coordinate. Otherwise it will snap to the // center of the slides near the edge of the container. That is // ______________ _____________ // [ | ][ ][ ][ | ] vs. [ ][ ][ ] // ‾‾‾‾‾‾‾‾‾‾‾‾‾‾ ‾‾‾‾‾‾‾‾‾‾‾‾‾ const coordinate = startAligned || oddVisibleCount ? '0%' : '50%'; iterateCursor(this.scrollContainer_.children, (child, index) => { // Note that we are dealing with both spacers, so we need to make sure // we are always dealing with the slideIndex. Since we have the same // number of each type of spacer as we do slides, we can simply do a mod // to do the mapping. const slideIndex = mod(index, slideCount); // If an item is at the start of the group, it gets an aligned. const shouldSnap = mod(slideIndex, this.snapBy_) == 0; setStyles(child, { 'scroll-snap-align': shouldSnap ? this.alignment_ : 'none', 'scroll-snap-coordinate': shouldSnap ? coordinate : 'none', }); }); } /** * Hides any spacers or slides that are not currently necessary. Enough * spacers are shown to allow 1 revolution of scrolling (not including the * current slide) before / after the current slide. The rest of the spacers * are hidden. * * Note that spacers are sized the same as the slide that they replace. As a * result, we need to hide the correct spacers rather than simply the * correct number of them. * * @private */ hideSpacersAndSlides_() { const { afterSpacers_, beforeSpacers_, currentIndex_, slides_, } = this; const numBeforeSpacers = Math.max(0, slides_.length - currentIndex_ - 1); const numAfterSpacers = Math.max(0, currentIndex_ - 1); beforeSpacers_.forEach((el, i) => { const distance = backwardWrappingDistance( currentIndex_, i, beforeSpacers_); const tooFar = distance > slides_.length - 1; el.hidden = tooFar || i < slides_.length - numBeforeSpacers; }); afterSpacers_.forEach((el, i) => { const distance = forwardWrappingDistance( currentIndex_, i, afterSpacers_); const tooFar = distance > slides_.length - 1; el.hidden = tooFar || i > numAfterSpacers; }); } /** * Updates the current element. If the current element has changed, then * slides are moved around as necessary before/after the current slide. * @private */ updateCurrent_() { const { allSpacers_, alignment_, axis_, currentIndex_, element_, loop_, slides_, } = this; const totalLength = sum(this.getSlideLengths_()); // When looping, we translate the slides, but the slides might decide to // translate their content instead of the whole slide. As a result, we need // to use the spacers to figure out where we are rather than the slides // themselves. const items = loop_ ? allSpacers_ : slides_; const startIndex = loop_ ? currentIndex_ + slides_.length : currentIndex_; const overlappingIndex = findOverlappingIndex(axis_, alignment_, element_, items, startIndex); // Currently not over a slide (e.g. on top of overscroll area). if (overlappingIndex === undefined) { return; } // Since we are potentially looking accross all spacers, we need to convert // to a slide index. const newIndex = overlappingIndex % slides_.length; // Update the current offset on each scroll so that we have it up to date // in case of a resize. const currentElement = slides_[newIndex]; const dimension = getDimension(axis_, currentElement); this.currentElementOffset_ = dimension.start; // We did not move at all. if (newIndex == currentIndex_) { return; } this.runMutate_(() => { this.currentIndex_ = newIndex; this.moveSlides_(totalLength); }); } /** * Resets the frame of reference for scrolling, centering things around the * current index and moving things as appropriate. * @param {boolean} force Whether or not to force the window reset, ignoring * whether or not the resting index has changed. * @private */ resetScrollReferencePoint_(force = false) { // Make sure if the user is in the middle of a drag, we do not move // anything. if (this.touching_) { return; } // We are still on the same slide, so nothing needs to move. if (this.restingIndex_ == this.currentIndex_ && !force) { return; } const totalLength = sum(this.getSlideLengths_()); this.runMutate_(() => { this.restingIndex_ = this.currentIndex_; this.updateCurrentIndex_(this.restingIndex_); this.resetSlideTransforms_(totalLength); this.hideSpacersAndSlides_(); this.moveSlides_(totalLength); this.restoreScrollStart_(); }); } /** * Updates the scroll start of the scrolling element. This restores the * scroll position to the same offset within the currentElement as before. * This is useful when some layout has occured that may change the existing * scroll position. * @private */ restoreScrollStart_() { const { axis_, currentElementOffset_, currentIndex_, scrollContainer_, slides_, } = this; const currentElement = slides_[currentIndex_]; const {length, start} = getDimension(axis_, scrollContainer_); const currentElementStart = Math.abs(currentElementOffset_) <= length ? currentElementOffset_ : 0; // Use the offsetStart to figure out the scroll position of the current // element. Note that this only works because the element is not translated // at this point. const offsetStart = getOffsetStart(axis_, currentElement); const pos = offsetStart - currentElementStart + start; this.ignoreNextScroll_ = true; runDisablingSmoothScroll(scrollContainer_, () => { setScrollPosition(axis_, scrollContainer_, pos); }); } /** * Scrolls a slide into view based on its alignment. * @param {!Element} slide * @param {{ * smoothScroll: boolean, * }} options * @private */ scrollSlideIntoView_(slide, { smoothScroll, }) { const runner = smoothScroll ? (el, cb) => cb() : runDisablingSmoothScroll; runner(this.scrollContainer_, () => { scrollContainerToElement( slide, this.scrollContainer_, this.axis_, this.alignment_ ); }); } /** * Moves slides before or after the current index by setting setting a * translate. * @param {number} totalLength The total length of all the slides. * @param {number} count How many slides to move. * @param {boolean} isAfter Whether the slides should move after or before. * @private */ moveSlidesBeforeOrAfter__(totalLength, count, isAfter) { const {currentIndex_, restingIndex_, slides_} = this; const current = slides_[currentIndex_]; const currentRevolutions = (current._revolutions || 0); const dir = isAfter ? 1 : -1; for (let i = 1; i <= count; i++) { const elIndex = mod(currentIndex_ + (i * dir), slides_.length); // We do not want to move the slide that we started at. if (elIndex === restingIndex_ && currentIndex_ !== restingIndex_) { break; } const el = slides_[elIndex]; // Check if the element is on the wrong side of the current index. const needsMove = elIndex > currentIndex_ !== isAfter; const revolutions = needsMove ? currentRevolutions + dir : currentRevolutions; this.setElementTransform_(el, revolutions, totalLength); } } /** * Moves slides that are not at the current index before or after by * translating them if necessary. * @param {number} totalLength The total length of all the slides. * @private */ moveSlides_(totalLength) { // TODO(sparhami) We could only the number of slides needed to have enough // buffer between scrolls. One thing we need to look out for is to make // sure the mixed length and visibleCount cases are handled correctly. const count = (this.slides_.length - 1) / 2; if (!this.loop_) { return; } if (this.slides_.length <= 2) { return; } this.moveSlidesBeforeOrAfter__(totalLength, Math.floor(count), false); this.moveSlidesBeforeOrAfter__(totalLength, Math.ceil(count), true); } /** * Checks if a given index is in the last window of items. For example, if * showing two slides at a time with the slides [a, b, c, d], both slide * b and c are in the last window. * @param {number} index The index to check. * @return {boolean} True if the slide is in the last window, false * otherwise. */ inLastWindow_(index) { const {alignment_, slides_, visibleCount_} = this; const startAligned = alignment_ == Alignment.START; const lastWindowSize = startAligned ? visibleCount_ : visibleCount_ / 2; return index >= slides_.length - lastWindowSize; } }
#! /usr/bin/env node const { showExit, commands, args, run, message } = require('./src/modules'); if (args.includes('-v')) { const version = require('./package.json').version; showExit(message.version, version); } if (args[0] === 'help') { showExit(message.help); } if (args[0] === 'deploy') { const { deploy } = require('./src/deploy'); return deploy(args); } if (args[0] === 'new-ci') { const { newCI } = require('./src/new-ci'); return newCI(args); } if (!Object.keys(commands()).includes(args[0])) { showExit(message.unknown); } if (args[0] === 'add') { const { add } = require('./src/add'); add(args); } run();
module.exports = { siteMetadata: { title: "Vivek Mittal's Blog", description: "A blog site containing all the blogs written by Vivek Mittal", url: "https://vivek-writes.netlify.com", image: "/feature.jpg", twitter: "@vivek96_", instagram: "@vivek06_", github: "@vivek1909", author: "Vivek Mittal", }, plugins: [ { resolve: `gatsby-plugin-manifest`, options: { name: `Vivek Mittal`, short_name: `Vivek`, start_url: `/`, background_color: `hsl(227,2%,12%)`, theme_color: `hsl(227,2%,12%)`, display: `standalone`, icon: `src/images/logo.svg`, cache_busting_mode: `none`, theme_color_in_head: false, }, }, { resolve: `gatsby-plugin-offline`, options: { precachePages: [`/pokedex/`, `/ajax-requests/`], }, }, { resolve: `gatsby-source-filesystem`, options: { name: `pages`, path: `${__dirname}/src/pages`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `posts`, path: `${__dirname}/src/posts`, }, }, { resolve: `gatsby-source-filesystem`, options: { name: `images`, path: `${__dirname}/src/images`, }, }, `gatsby-transformer-sharp`, `gatsby-plugin-sharp`, { resolve: `gatsby-plugin-mdx`, options: { extensions: [`.md`, `.mdx`], gatsbyRemarkPlugins: [ { resolve: `gatsby-remark-images`, options: { maxWidth: 1200, }, }, ], }, }, { resolve: `gatsby-plugin-google-fonts`, options: { fonts: [`poppins\:400,700`, `montserrat\:400,700`], display: "swap", }, }, ], }
/* Plugin Name: Animated Headlines Written by: Codyhouse - (https://codyhouse.co/demo/animated-headlines/index.html) */ jQuery(document).ready(function($) { //set animation timing var animationDelay = 2500, //loading bar effect barAnimationDelay = 3800, barWaiting = barAnimationDelay - 3000, //3000 is the duration of the transition on the loading bar - set in the scss/css file //letters effect lettersDelay = 50, //type effect typeLettersDelay = 150, selectionDuration = 500, typeAnimationDelay = selectionDuration + 800, //clip effect revealDuration = 600, revealAnimationDelay = 1500; initHeadline(); function initHeadline() { //insert <i> element for each letter of a changing word singleLetters($('.word-rotator.letters').find('b')); //initialise headline animation animateHeadline($('.word-rotator')); } function singleLetters($words) { $words.each(function() { var word = $(this), letters = word.text().split(''), selected = word.hasClass('is-visible'); for (i in letters) { if (word.parents('.rotate-2').length > 0) letters[i] = '<em>' + letters[i] + '</em>'; letters[i] = (selected) ? '<i class="in">' + letters[i] + '</i>' : '<i>' + letters[i] + '</i>'; } var newLetters = letters.join(''); word.html(newLetters).css('opacity', 1); }); } function animateHeadline($headlines) { var duration = animationDelay; $headlines.each(function() { var headline = $(this); if (headline.hasClass('loading-bar')) { duration = barAnimationDelay; setTimeout(function() { headline.find('.word-rotator-words').addClass('is-loading') }, barWaiting); } else if (headline.hasClass('clip')) { var spanWrapper = headline.find('.word-rotator-words'), newWidth = spanWrapper.outerWidth() + 10 spanWrapper.css('width', newWidth); } else if (!headline.hasClass('type')) { //assign to .word-rotator-words the width of its longest word var words = headline.find('.word-rotator-words b'), width = 0; words.each(function() { var wordWidth = $(this).outerWidth(); if (wordWidth > width) width = wordWidth; }); headline.find('.word-rotator-words').css('width', width); }; //trigger animation setTimeout(function() { hideWord(headline.find('.is-visible').eq(0)) }, duration); }); } function hideWord($word) { var nextWord = takeNext($word); if ($word.parents('.word-rotator').hasClass('type')) { var parentSpan = $word.parent('.word-rotator-words'); parentSpan.addClass('selected').removeClass('waiting'); setTimeout(function() { parentSpan.removeClass('selected'); $word.removeClass('is-visible').addClass('is-hidden').children('i').removeClass('in').addClass('out'); }, selectionDuration); setTimeout(function() { showWord(nextWord, typeLettersDelay) }, typeAnimationDelay); } else if ($word.parents('.word-rotator').hasClass('letters')) { var bool = ($word.children('i').length >= nextWord.children('i').length) ? true : false; hideLetter($word.find('i').eq(0), $word, bool, lettersDelay); showLetter(nextWord.find('i').eq(0), nextWord, bool, lettersDelay); } else if ($word.parents('.word-rotator').hasClass('clip')) { $word.parents('.word-rotator-words').stop( true, true ).animate({ width: '2px' }, revealDuration, function() { switchWord($word, nextWord); showWord(nextWord); }); } else if ($word.parents('.word-rotator').hasClass('loading-bar')) { $word.parents('.word-rotator-words').removeClass('is-loading'); switchWord($word, nextWord); setTimeout(function() { hideWord(nextWord) }, barAnimationDelay); setTimeout(function() { $word.parents('.word-rotator-words').addClass('is-loading') }, barWaiting); } else { switchWord($word, nextWord); setTimeout(function() { hideWord(nextWord) }, animationDelay); } } function showWord($word, $duration) { if ($word.parents('.word-rotator').hasClass('type')) { showLetter($word.find('i').eq(0), $word, false, $duration); $word.addClass('is-visible').removeClass('is-hidden'); } else if ($word.parents('.word-rotator').hasClass('clip')) { if (document.hasFocus()) { $word.parents('.word-rotator-words').stop( true, true ).animate({ 'width': $word.outerWidth() + 10 }, revealDuration, function() { setTimeout(function() { hideWord($word) }, revealAnimationDelay); }); console.log(123); } else { $word.parents('.word-rotator-words').stop( true, true ).css('width', $word.outerWidth() + 10); hideWord($word); } } } function hideLetter($letter, $word, $bool, $duration) { $letter.removeClass('in').addClass('out'); if (!$letter.is(':last-child')) { setTimeout(function() { hideLetter($letter.next(), $word, $bool, $duration); }, $duration); } else if ($bool) { setTimeout(function() { hideWord(takeNext($word)) }, animationDelay); } if ($letter.is(':last-child') && $('html').hasClass('no-csstransitions')) { var nextWord = takeNext($word); switchWord($word, nextWord); } } function showLetter($letter, $word, $bool, $duration) { $letter.addClass('in').removeClass('out'); if (!$letter.is(':last-child')) { setTimeout(function() { showLetter($letter.next(), $word, $bool, $duration); }, $duration); } else { if ($word.parents('.word-rotator').hasClass('type')) { setTimeout(function() { $word.parents('.word-rotator-words').addClass('waiting'); }, 200); } if (!$bool) { setTimeout(function() { hideWord($word) }, animationDelay) } if (!$word.closest('.word-rotator').hasClass('type')) { $word.closest('.word-rotator-words').stop( true, true ).animate({ width: $word.outerWidth() }); } } } function takeNext($word) { return (!$word.is(':last-child')) ? $word.next() : $word.parent().children().eq(0); } function takePrev($word) { return (!$word.is(':first-child')) ? $word.prev() : $word.parent().children().last(); } function switchWord($oldWord, $newWord) { $oldWord.removeClass('is-visible').addClass('is-hidden'); $newWord.removeClass('is-hidden').addClass('is-visible'); if (!$newWord.closest('.word-rotator').hasClass('clip')) { var space = 0, delay = ($newWord.outerWidth() > $oldWord.outerWidth()) ? 0 : 600; if ($newWord.closest('.word-rotator').hasClass('loading-bar') || $newWord.closest('.word-rotator').hasClass('slide')) { space = 3; delay = 0; } setTimeout(function() { $newWord.closest('.word-rotator-words').stop( true, true ).animate({ width: $newWord.outerWidth() + space }); }, delay); } } });
import { combineReducers } from 'redux'; import isRequesting from './is-requesting'; import attachmentRequest from './attachment-request'; import crid from './crid'; import officerId from './officer-id'; import relatedComplaints from './related-complaints'; import editModeOn from './edit-mode-on'; export default combineReducers({ isRequesting, crid, officerId, attachmentRequest, relatedComplaints, editModeOn, });
from django.contrib import admin from django.contrib.auth.admin import UserAdmin as DjangoUserAdmin from . import models class UserAdmin(DjangoUserAdmin): fieldsets = ( (None, {"fields": ("email", "password")}), ( "Personal info", {"fields": ("first_name", "last_name")}, ), ( "Permissions", { "fields":( "is_active", "is_staff", "is_superuser", "groups", "user_permissions", ) } ), ( "Important dates", {"fields": ("last_login", "date_joined")}, ) ) add_fieldsets = ( ( None, { "classes": ("wide",), "fields": ("email","password1", "password2"), }, ), ) list_display = ( "first_name", "last_name", "is_staff", ) search_fields = ("fist_name", "last_name") ordering = ("email",) admin.site.register(models.User, UserAdmin)
module.exports = { root: true, env: { browser: true, node: true, mocha: true, }, extends: [ "plugin:vue/recommended", "eslint:recommended", "@vue/typescript/recommended", "@vue/prettier", "@vue/prettier/@typescript-eslint", "plugin:@typescript-eslint/eslint-recommended", "plugin:@typescript-eslint/recommended", "plugin:@typescript-eslint/recommended-requiring-type-checking", ], plugins: ["@typescript-eslint", "simple-import-sort"], parser: "vue-eslint-parser", parserOptions: { ecmaVersion: 2020, project: `./tsconfig.json`, parser: "@typescript-eslint/parser", }, rules: { "no-console": process.env.NODE_ENV === "production" ? "warn" : "off", "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off", "vue/component-name-in-template-casing": "error", "vue/match-component-file-name": [ "error", { extensions: ["vue"], shouldMatchCase: true, }, ], "@typescript-eslint/naming-convention": [ "error", { selector: "interface", format: ["PascalCase"], prefix: ["I"], }, { selector: ["class", "enum", "enumMember"], format: ["PascalCase"], }, { selector: [ "variable", "function", "parameter", "classProperty", "classMethod", ], format: ["camelCase"], }, ], "@typescript-eslint/explicit-function-return-type": [ "error", { allowExpressions: true }, ], "@typescript-eslint/consistent-type-assertions": [ "error", { assertionStyle: "angle-bracket" }, ], "simple-import-sort/imports": "error", "prefer-const": "error", }, overrides: [ { files: [ "**/__tests__/*.{j,t}s?(x)", "**/tests/unit/**/*.spec.{j,t}s?(x)", ], env: { mocha: true, }, }, ], };
import React from "react" import PropTypes from "prop-types" import Header from "../header" import Footer from "../footer" import { Wrapper } from "./styles" import { GlobalStyle } from "../../styles/global" const Layout = ({ children }) => { return ( <> <Header /> <Wrapper> <main>{children}</main> </Wrapper> <Footer /> <GlobalStyle /> </> ) } Layout.propTypes = { children: PropTypes.node.isRequired, } export default Layout
// tarpit let hooks_to_delay = [ 'connect', 'helo', 'ehlo', 'mail', 'rcpt', 'rcpt_ok', 'data', 'data_post', 'queue', 'unrecognized_command', 'vrfy', 'noop', 'rset', 'quit' ]; exports.register = function () { // Register tarpit function last const plugin = this; const cfg = plugin.config.get('tarpit.ini'); if (cfg && cfg.main.hooks_to_delay) { hooks_to_delay = cfg.main.hooks_to_delay.split(/[\s,;]+/); } for (let i=0; i < hooks_to_delay.length; i++) { const hook = hooks_to_delay[i]; plugin.register_hook(hook, 'tarpit'); } } exports.tarpit = function (next, connection) { const plugin = this; let delay = connection.notes.tarpit; if (!delay && connection.transaction) { delay = connection.transaction.notes.tarpit; } if (!delay) return next(); connection.loginfo(plugin, `tarpitting response for ${delay}s`); setTimeout(() => next(), delay * 1000); }
import React from 'react' import Link from 'react-router/lib/Link' import {pure} from 'recompose' import urls from 'utils/urls' const {home} = urls export const Header = pure(({loggedIn, logout, username}) => <nav className='navbar navbar-inverse'> <div className='container-fluid'> <div className='navbar-header'> <Link to={home} className='navbar-brand'>Project</Link> </div> <div className='collapse navbar-collapse'> <ul className='nav navbar-nav'> <li><Link to={home}>Test</Link></li> <li><Link to={home}>Test 2</Link></li> </ul> {loggedIn && <ul className='nav navbar-nav navbar-right'> <li> <a href='#'>{username}</a> </li> <li> <button onClick={logout} className='btn btn-default navbar-btn'>Logout</button> </li> </ul>} </div> </div> </nav> ) export default Header
/* imports common modules */ var electron = require('electron') var ipc = electron.ipcRenderer /* define window.chrome this is necessary because some websites (such as the Google Drive file viewer, see issue #378) check for a Chrome user agent, and then do things like if(chrome.<module>) {} so we need to define an empty chrome object to prevent errors */ window.chrome = {}
/* eslint no-console:0 */ require('../src/server/babel') require('../src/server/globals') const { json } = require('../src/service/api') json('status').then( res => console.info('API server is up and running', res), err => console.error('Failed to ping API server', err) )
var e=function(){this.table=new Uint16Array(16),this.trans=new Uint16Array(288)},t=function(t,r){this.sourceIndex=0,this.tag=0,this.bitCount=0,this.destLen=0,this.lengthTree=new e,this.distanceTree=new e,this.source=void 0,this.dest=void 0,this.source=t,this.dest=r},r=new e,n=new e,o=new Uint8Array(30),a=new Uint16Array(30),s=new Uint8Array(30),i=new Uint16Array(30),u=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),c=new e,f=new Uint8Array(320);function d(e,t,r,n){for(var o=0;o<r;++o)e[o]=0;for(var a=0;a<30-r;++a)e[a+r]=a/r|0;for(var s=0,i=n;s<30;++s)t[s]=i,i+=1<<e[s]}var b=new Uint16Array(16);function l(e,t,r,n){var o,a;for(o=0;o<16;++o)e.table[o]=0;for(o=0;o<n;++o)e.table[t[r+o]]++;for(e.table[0]=0,a=0,o=0;o<16;++o)b[o]=a,a+=e.table[o];for(o=0;o<n;++o)t[r+o]&&(e.trans[b[t[r+o]]++]=o)}function v(e){e.bitCount--||(e.tag=e.source[e.sourceIndex++],e.bitCount=7);var t=1&e.tag;return e.tag>>>=1,t}function h(e,t,r){if(!t)return r;for(;e.bitCount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitCount,e.bitCount+=8;var n=e.tag&65535>>>16-t;return e.tag>>>=t,e.bitCount-=t,n+r}function w(e,t){for(;e.bitCount<24;)e.tag|=e.source[e.sourceIndex++]<<e.bitCount,e.bitCount+=8;var r=0,n=0,o=0,a=e.tag;do{n=2*n+(1&a),a>>>=1,++o,r+=t.table[o],n-=t.table[o]}while(n>=0);return e.tag=a,e.bitCount-=o,t.trans[r+n]}function g(e,t,r){var n,o,a,s=h(e,5,257),i=h(e,5,1),d=h(e,4,4);for(n=0;n<19;++n)f[n]=0;for(n=0;n<d;++n){var b=h(e,3,0);f[u[n]]=b}for(l(c,f,0,19),o=0;o<s+i;){var v=w(e,c);switch(v){case 16:var g=f[o-1];for(a=h(e,2,3);a;--a)f[o++]=g;break;case 17:for(a=h(e,3,3);a;--a)f[o++]=0;break;case 18:for(a=h(e,7,11);a;--a)f[o++]=0;break;default:f[o++]=v}}l(t,f,0,s),l(r,f,s,i)}function C(e,t,r){for(var n=w(e,t);256!==n;){if(n<256)e.dest[e.destLen++]=n;else{var u=void 0,c=h(e,o[n-=257],a[n]),f=w(e,r),d=e.destLen-h(e,s[f],i[f]);for(u=d;u<d+c;++u)e.dest[e.destLen++]=e.dest[u]}n=w(e,t)}return 0}function x(e){for(var t;e.bitCount>8;)e.sourceIndex--,e.bitCount-=8;if((t=256*(t=e.source[e.sourceIndex+1])+e.source[e.sourceIndex])!==(65535&~(256*e.source[e.sourceIndex+3]+e.source[e.sourceIndex+2])))return-3;e.sourceIndex+=4;for(var r=t;r;--r)e.dest[e.destLen++]=e.source[e.sourceIndex++];return e.bitCount=0,0}function y(e,o){var a,s,i=new t(e,o);do{switch(a=v(i),h(i,2,0)){case 0:s=x(i);break;case 1:s=C(i,r,n)||0;break;case 2:g(i,i.lengthTree,i.distanceTree),s=C(i,i.lengthTree,i.distanceTree)||0;break;default:s=-3}if(0!==s)throw new Error("Data error")}while(!a);return i.destLen<i.dest.length?"function"==typeof i.dest.slice?i.dest.slice(0,i.destLen):i.dest.subarray(0,i.destLen):i.dest}!function(e,t){var r=0;for(r=0;r<7;++r)e.table[r]=0;for(e.table[7]=24,e.table[8]=152,e.table[9]=112,r=0;r<24;++r)e.trans[r]=256+r;for(r=0;r<144;++r)e.trans[24+r]=r;for(r=0;r<8;++r)e.trans[168+r]=280+r;for(r=0;r<112;++r)e.trans[176+r]=144+r;for(r=0;r<5;++r)t.table[r]=0;for(t.table[5]=32,r=0;r<32;++r)t.trans[r]=r}(r,n),d(o,a,4,3),d(s,i,2,1),o[28]=0,a[28]=258;export default y; //# sourceMappingURL=index.module.js.map
const http = require('http') http .createServer(function (req, res) { console.log(req.headers) res.writeHead(200, { 'Content-Type': 'text/plain' }) res.end( [ 'Hello World', process.env.FOO, process.env.HTTP_PROXY, 'x-forwarded-host: ' + req.headers['x-forwarded-host'], 'host: ' + req.headers.host, ].join(' ') ) }) .listen(process.env.PORT, '127.0.0.1') console.log('Server listening on port', process.env.PORT)
import React from "react" import { colors } from "../../utils/presets" import { WebpackIcon, ReactJSIcon, GraphQLIcon } from "../../assets/tech-logos" import Card from "../card" import CardHeadline from "../card-headline" import TechWithIcon from "../tech-with-icon" import FuturaParagraph from "../futura-paragraph" const HomepageFeatures = () => ( <div css={{ display: `flex`, flex: `0 1 auto`, flexWrap: `wrap`, borderBottom: `1px solid ${colors.purple[10]}`, }} > <Card> <CardHeadline>Modern web tech without the headache</CardHeadline> <FuturaParagraph> Enjoy the power of the latest web technologies –{` `} <TechWithIcon icon={ReactJSIcon}>React.js</TechWithIcon>,{` `} <TechWithIcon icon={WebpackIcon}>Webpack</TechWithIcon>,{` `} modern JavaScript and CSS and more — all set up and waiting for you to start building. </FuturaParagraph> </Card> <Card> <CardHeadline>Bring your own data</CardHeadline> <FuturaParagraph> Gatsby’s rich data plugin ecosystem lets you build sites with the data you want — from one or many sources: Pull data from headless CMSs, SaaS services, APIs, databases, your file system, and more directly into your pages using {` `} <TechWithIcon icon={GraphQLIcon}>GraphQL</TechWithIcon>. </FuturaParagraph> </Card> <Card> <CardHeadline>Scale to the entire internet</CardHeadline> <FuturaParagraph> Gatsby.js is Internet Scale. Forget complicated deploys with databases and servers and their expensive, time-consuming setup costs, maintenance, and scaling fears. Gatsby.js builds your site as “static” files which can be deployed easily on dozens of services. </FuturaParagraph> </Card> <Card> <CardHeadline>Future-proof your website</CardHeadline> <FuturaParagraph> Do not build a website with last decade’s tech. The future of the web is mobile, JavaScript and APIs—the {` `} <a href="https://jamstack.org/">JAMstack</a>. Every website is a web app and every web app is a website. Gatsby.js is the universal JavaScript framework you’ve been waiting for. </FuturaParagraph> </Card> <Card> <CardHeadline> <em css={{ color: colors.gatsby, fontStyle: `normal` }}>Static</em> {` `} Progressive Web Apps </CardHeadline> <FuturaParagraph> Gatsby.js is a static PWA (Progressive Web App) generator. You get code and data splitting out-of-the-box. Gatsby loads only the critical HTML, CSS, data, and JavaScript so your site loads as fast as possible. Once loaded, Gatsby prefetches resources for other pages so clicking around the site feels incredibly fast. </FuturaParagraph> </Card> <Card> <CardHeadline>Speed past the competition</CardHeadline> <FuturaParagraph> Gatsby.js builds the fastest possible website. Instead of waiting to generate pages when requested, pre-build pages and lift them into a global cloud of servers — ready to be delivered instantly to your users wherever they are. </FuturaParagraph> </Card> </div> ) export default HomepageFeatures
$(function () { $('.js-basic-example').DataTable({ responsive: true }); });
/** * Using Rails-like standard naming convention for endpoints. * GET /api/tags -> index * POST /api/tags -> create * GET /api/tags/:id -> show * PUT /api/tags/:id -> upsert * PATCH /api/tags/:id -> patch * DELETE /api/tags/:id -> destroy */ 'use strict'; //import jsonpatch from 'fast-json-patch'; import Tag from './tag.model'; import Question from '../question/question.model'; /* istanbul ignore next */ function respondWithResult(res, statusCode) { statusCode = statusCode || 200; return function(entity) { if(entity) { return res.status(statusCode).json(entity); } return null; }; } /* istanbul ignore next */ function patchUpdates(patches) { return function(entity) { try { jsonpatch.apply(entity, patches, /*validate*/ true); } catch(err) { return Promise.reject(err); } return entity.save(); }; } /* istanbul ignore next */ function removeEntity(res) { return function(entity) { if(entity) { return entity.remove() .then(() => { res.status(204).end(); }); } }; } /* istanbul ignore next */ function handleEntityNotFound(res) { return function(entity) { if(!entity) { res.status(404).end(); return null; } return entity; }; } /* istanbul ignore next */ function handleError(res, statusCode) { statusCode = statusCode || 500; return function(err) { res.status(statusCode).send(err); }; } /* istanbul ignore next */ // Gets a list of Tags export function index(req, res) { return Tag.find().exec() .then(respondWithResult(res)) .catch(handleError(res)); } /* istanbul ignore next */ // Gets a single Tag from the DB export function show(req, res) { console.log("Search by tag"); var query = req.params.id; console.log(query); Question.find({"tags.text": query}).sort({createdAt: -1}).limit(20).execAsync() .then(respondWithResult(res)) .catch(handleError(res)); } /* istanbul ignore next */ // Gets a single Tag from the DB export function findByName(req, res) { var query = req.params.query; Tag.find({"name": new RegExp(query, 'i')}).sort({createdAt: -1}).limit(20).execAsync() .then(respondWithResult(res)) .catch(handleError(res)); } /* istanbul ignore next */ // Creates a new Tag in the DB export function create(req, res) { return Tag.create(req.body) .then(respondWithResult(res, 201)) .catch(handleError(res)); } /* istanbul ignore next */ // Upserts the given Tag in the DB at the specified ID export function upsert(req, res) { if(req.body._id) { delete req.body._id; } return Tag.findOneAndUpdate({_id: req.params.id}, req.body, {new: true, upsert: true, setDefaultsOnInsert: true, runValidators: true}).exec() .then(respondWithResult(res)) .catch(handleError(res)); } /* istanbul ignore next */ // Updates an existing Tag in the DB export function patch(req, res) { if(req.body._id) { delete req.body._id; } return Tag.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(patchUpdates(req.body)) .then(respondWithResult(res)) .catch(handleError(res)); } /* istanbul ignore next */ // Deletes a Tag from the DB export function destroy(req, res) { return Tag.findById(req.params.id).exec() .then(handleEntityNotFound(res)) .then(removeEntity(res)) .catch(handleError(res)); } /* istanbul ignore next */ /** * Modify tag */ export function updateTag(req, res, next) { // db.users.update({"_id" : ObjectId("58e4b8c142984807893801a3")},{$set:{"role":"admin"}}) console.log("Update tag"); console.log("======"); console.log(req.params.id); console.log(req.params.name); Tag.update({"_id": req.params.id},{$set:{"name":req.params.name}}) .then(respondWithResult(res)) .catch(handleError(res)); //res.redirect(config.path +'/tagsIndex'); }
import React from 'react'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import Growler from './growler.jsx'; import * as growlerActionCreators from '../actions/growler.action'; const mapStateToProps = state => ({ growler: state.growler, }); const mapDispatchToProps = dispatch => bindActionCreators(growlerActionCreators, dispatch); @connect(mapStateToProps, mapDispatchToProps) class growlerContainer extends React.Component { getMessage() { const lang = this.props.currentLocale || "enUS"; let message = this.props.growler.text; if(this.props.messages && this.props.messages[lang]){ return this.props.messages[lang][message] || message; } return message; } render() { const message = this.getMessage(); this.props.hideTimeOutGrowler(this.props.growler, this.props.shownFor); return <Growler {...this.props} message={message} />; } } export default growlerContainer;
import React from 'react'; import Link from '@docusaurus/Link'; import { morfeo } from '@morfeo/react'; import { enableMorfeoDevTool } from '@morfeo/dev-tools'; import '@morfeo/preset-default'; import CookieConsent from 'react-cookie-consent'; enableMorfeoDevTool(); const buttonStyle = morfeo.resolve({ corner: 'm' }); function Root({ children }) { return ( <> {children} <CookieConsent buttonClasses="button button--secondary button--lg" buttonStyle={buttonStyle} > We use cookies to improve your experience on our site. To find out more, read our <Link to="/privacy">privacy policy</Link>. </CookieConsent> </> ); } export default Root;
# -*- coding: utf-8 -*- from __future__ import unicode_literals import atexit from .platform import platform __all__ = ['set_up', 'get_context'] _context = None def _tear_down(): global _context _context.tear_down() _context._vm.tear_down() # no-qa platform.tear_down() def set_up(): """ Set ups the V8 machinery:\ platform, VM and context. This function is not thread-safe,\ it must be called from a place\ where is guaranteed it will be\ called once and only once.\ Probably within the main-thread\ at import time. """ global _context if _context is not None: raise AssertionError( 'This function must only be called ' 'once in an application lifetime') platform.set_up() vm = platform.create_vm() vm.set_up() _context = vm.create_context() _context.set_up() atexit.register(_tear_down) def get_context(): """ Return a global V8 context. :py:func:`.set_up` must has been called :return: Global V8 context :rtype: :py:class:`.Context` """ global _context if _context is None: raise AssertionError( 'No context found. ' 'Did you call shortcuts.set_up()?') return _context
import ifElse from '../ifElse'; describe('utils/function/ifElse', () => { it('should call first function base on condition', () => { const cond = jest.fn(() => true); const onT = jest.fn(() => 8); const onF = jest.fn(); expect(ifElse(cond, onT, onF)(1, 2, 3)).toBe(8); expect(cond).toBeCalledWith(1, 2, 3); expect(onT).toBeCalledWith(1, 2, 3); expect(onF).not.toBeCalled(); }); it('should call second function base on condition', () => { const cond = jest.fn(() => false); const onT = jest.fn(() => 8); const onF = jest.fn(() => 2); expect(ifElse(cond, onT, onF)('test')).toBe(2); expect(cond).toBeCalledWith('test'); expect(onT).not.toBeCalled(); expect(onF).toBeCalledWith('test'); }); });
/**@preserve GeneXus Java 10_3_12-110051 on December 12, 2020 12:55:45.27 */ gx.evt.autoSkip = false; gx.define('hconsultaprocessoconv', false, function () { this.ServerClass = "hconsultaprocessoconv" ; this.PackageName = "" ; this.setObjectType("web"); this.setOnAjaxSessionTimeout("Warn"); this.hasEnterEvent = true; this.skipOnEnter = false; this.addKeyListener("6", "'GXM_FIRST'"); this.addKeyListener("7", "'GXM_PREVIOUS'"); this.addKeyListener("8", "'GXM_NEXT'"); this.addKeyListener("9", "'GXM_LAST'"); this.addKeyListener("5", "'PROCURAR'"); this.addKeyListener("5", "REFRESH"); this.addKeyListener("12", "CANCEL"); this.addKeyListener("1", "HELP"); this.SetStandaloneVars=function() { this.AV12EmpresaPadrao=gx.fn.getControlValue("vEMPRESAPADRAO") ; this.AV17PProcessoConvAno=gx.fn.getIntegerValue("vPPROCESSOCONVANO",'.') ; this.AV16PProcessoConvNumero=gx.fn.getIntegerValue("vPPROCESSOCONVNUMERO",'.') ; }; this.Valid_Convenioid=function() { try { if( gx.fn.currentGridRowImpl(41) ===0) { return true; } var gxballoon = gx.util.balloon.getNew("CONVENIOID", gx.fn.currentGridRowImpl(41)); this.AnyError = 0; this.StandaloneModal( ); this.StandaloneNotModal( ); } catch(e){} try { if (gxballoon == null) return true; return gxballoon.show(); } catch(e){} return true ; } this.e17ni2_client=function() { this.executeServerEvent("ENTER", true, arguments[0], false, false); }; this.e11ni2_client=function() { this.executeServerEvent("'GXM_FIRST'", true, null, false, false); }; this.e12ni2_client=function() { this.executeServerEvent("'GXM_PREVIOUS'", true, null, false, false); }; this.e13ni2_client=function() { this.executeServerEvent("'GXM_NEXT'", true, null, false, false); }; this.e14ni2_client=function() { this.executeServerEvent("'GXM_LAST'", true, null, false, false); }; this.e15ni2_client=function() { this.executeServerEvent("'PROCURAR'", false, null, false, false); }; this.e20ni2_client=function() { this.executeServerEvent("'ATUALIZAPAGINA'", true, arguments[0], false, false); }; this.e21ni1_client=function() { this.executeServerEvent("CANCEL", true, null, false, false); }; this.GXValidFnc = []; var GXValidFnc = this.GXValidFnc ; this.GXCtrlIds=[2,5,8,11,13,16,18,20,23,25,28,30,33,35,36,42,43,44,45,46,47,48,49,50,51,57,60,62,64,66,68,69,70,71,72,73,74]; this.GXLastCtrlId =74; this.GridContainer = new gx.grid.grid(this, 2,"WbpLvl2",41,"Grid","Grid","GridContainer",this.CmpContext,this.IsMasterPage,"hconsultaprocessoconv",[],false,1,true,true,0,false,false,false,"",0,"px","Novo registro",true,false,false,null,null,false,"",false,[1,1,1,1]); var GridContainer = this.GridContainer; GridContainer.addSingleLineEdit(3373,42,"PROCESSOCONVANO","","","ProcessoConvAno","int",0,"px",4,4,"right",null,[],3373,"ProcessoConvAno",true,0,false,false,"Attribute",1,""); GridContainer.addSingleLineEdit(3374,43,"PROCESSOCONVNUMERO","","","ProcessoConvNumero","int",0,"px",8,8,"right",null,[],3374,"ProcessoConvNumero",true,0,false,false,"Attribute",1,""); GridContainer.addSingleLineEdit(3817,44,"PROCESSOCONVDATAINICIO","","","ProcessoConvDataInicio","date",0,"px",10,10,"right",null,[],3817,"ProcessoConvDataInicio",true,0,false,false,"Attribute",1,""); GridContainer.addComboBox(3815,45,"PROCESSOCONVSITUACAO","","ProcessoConvSituacao","char",null,0,true,false,0,"px",""); GridContainer.addSingleLineEdit("Finalidade",46,"vFINALIDADE","","","Finalidade","svchar",0,"px",65,65,"left",null,[],"Finalidade","Finalidade",true,0,false,false,"SemQuebraGrid",1,""); GridContainer.addSingleLineEdit(3819,47,"PROCESSOCONVFINALIDADE","Finalidade","","ProcessoConvFinalidade","svchar",0,"px",100,80,"left",null,[],3819,"ProcessoConvFinalidade",false,0,false,false,"Attribute",1,""); GridContainer.addSingleLineEdit(1681,48,"CONVENIOID","","","ConvenioId","int",0,"px",7,7,"right",null,[],1681,"ConvenioId",true,0,false,false,"Attribute",1,""); GridContainer.addSingleLineEdit(2082,49,"CONVENIODESCRICAO","","","ConvenioDescricao","svchar",0,"px",40,40,"left",null,[],2082,"ConvenioDescricao",false,0,false,false,"SemQuebraGrid",1,""); GridContainer.addSingleLineEdit("Conveniodescricaogrid",50,"vCONVENIODESCRICAOGRID","Descrição do Convênio","","ConvenioDescricaoGrid","svchar",0,"px",40,40,"left",null,[],"Conveniodescricaogrid","ConvenioDescricaoGrid",true,0,false,false,"SemQuebraGrid",1,""); GridContainer.addSingleLineEdit(3820,51,"PROCESSOCONVVALOR","","","ProcessoConvValor","decimal",0,"px",22,22,"right",null,[],3820,"ProcessoConvValor",true,2,false,false,"SemQuebraGrid",1,""); this.setGrid(GridContainer); GXValidFnc[2]={fld:"TABLEPRINCIPAL",grid:0}; GXValidFnc[5]={fld:"TABLE1",grid:0}; GXValidFnc[8]={fld:"TABLEFILTROS",grid:0}; GXValidFnc[11]={fld:"TEXTBLOCK4", format:0,grid:0}; GXValidFnc[13]={fld:"TABLERANGEPROCESSOS",grid:0}; GXValidFnc[16]={lvl:0,type:"int",len:4,dec:0,sign:false,pic:"ZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vPROCESSOCONVANO",gxz:"ZV18ProcessoConvAno",gxold:"OV18ProcessoConvAno",gxvar:"AV18ProcessoConvAno",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV18ProcessoConvAno=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV18ProcessoConvAno=gx.num.intval(Value)},v2c:function(){gx.fn.setControlValue("vPROCESSOCONVANO",gx.O.AV18ProcessoConvAno,0)},c2v:function(){gx.O.AV18ProcessoConvAno=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vPROCESSOCONVANO",'.')},nac:gx.falseFn}; GXValidFnc[18]={fld:"TEXTBLOCK5", format:0,grid:0}; GXValidFnc[20]={lvl:0,type:"int",len:8,dec:0,sign:false,pic:"ZZZZZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vPROCESSOCONVNUMERO",gxz:"ZV19ProcessoConvNumero",gxold:"OV19ProcessoConvNumero",gxvar:"AV19ProcessoConvNumero",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV19ProcessoConvNumero=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV19ProcessoConvNumero=gx.num.intval(Value)},v2c:function(){gx.fn.setControlValue("vPROCESSOCONVNUMERO",gx.O.AV19ProcessoConvNumero,0)},c2v:function(){gx.O.AV19ProcessoConvNumero=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vPROCESSOCONVNUMERO",'.')},nac:gx.falseFn}; GXValidFnc[23]={fld:"TEXTBLOCK1", format:0,grid:0}; GXValidFnc[25]={lvl:0,type:"svchar",len:100,dec:0,sign:false,ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vPROCESSOCONVFINALIDADE",gxz:"ZV20ProcessoConvFinalidade",gxold:"OV20ProcessoConvFinalidade",gxvar:"AV20ProcessoConvFinalidade",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV20ProcessoConvFinalidade=Value},v2z:function(Value){gx.O.ZV20ProcessoConvFinalidade=Value},v2c:function(){gx.fn.setControlValue("vPROCESSOCONVFINALIDADE",gx.O.AV20ProcessoConvFinalidade,0)},c2v:function(){gx.O.AV20ProcessoConvFinalidade=this.val()},val:function(){return gx.fn.getControlValue("vPROCESSOCONVFINALIDADE")},nac:gx.falseFn}; GXValidFnc[28]={fld:"TEXTBLOCK3", format:0,grid:0}; GXValidFnc[30]={lvl:0,type:"char",len:1,dec:0,sign:false,ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vSTPROCESSO",gxz:"ZV31StProcesso",gxold:"OV31StProcesso",gxvar:"AV31StProcesso",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"combo",v2v:function(Value){gx.O.AV31StProcesso=Value},v2z:function(Value){gx.O.ZV31StProcesso=Value},v2c:function(){gx.fn.setComboBoxValue("vSTPROCESSO",gx.O.AV31StProcesso)},c2v:function(){gx.O.AV31StProcesso=this.val()},val:function(){return gx.fn.getControlValue("vSTPROCESSO")},nac:gx.falseFn}; GXValidFnc[33]={fld:"TEXTBLOCK2", format:0,grid:0}; GXValidFnc[35]={lvl:0,type:"int",len:7,dec:0,sign:false,pic:"ZZZZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vCONVENIOID",gxz:"ZV21ConvenioId",gxold:"OV21ConvenioId",gxvar:"AV21ConvenioId",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV21ConvenioId=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV21ConvenioId=gx.num.intval(Value)},v2c:function(){gx.fn.setControlValue("vCONVENIOID",gx.O.AV21ConvenioId,0)},c2v:function(){gx.O.AV21ConvenioId=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vCONVENIOID",'.')},nac:gx.falseFn}; GXValidFnc[36]={lvl:0,type:"svchar",len:40,dec:0,sign:false,ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vCONVENIODESCRICAO",gxz:"ZV22ConvenioDescricao",gxold:"OV22ConvenioDescricao",gxvar:"AV22ConvenioDescricao",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV22ConvenioDescricao=Value},v2z:function(Value){gx.O.ZV22ConvenioDescricao=Value},v2c:function(){gx.fn.setControlValue("vCONVENIODESCRICAO",gx.O.AV22ConvenioDescricao,0)},c2v:function(){gx.O.AV22ConvenioDescricao=this.val()},val:function(){return gx.fn.getControlValue("vCONVENIODESCRICAO")},nac:gx.falseFn}; GXValidFnc[42]={lvl:2,type:"int",len:4,dec:0,sign:false,pic:"ZZZ9",ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVANO",gxz:"Z3373ProcessoConvAno",gxold:"O3373ProcessoConvAno",gxvar:"A3373ProcessoConvAno",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',v2v:function(Value){gx.O.A3373ProcessoConvAno=gx.num.intval(Value)},v2z:function(Value){gx.O.Z3373ProcessoConvAno=gx.num.intval(Value)},v2c:function(row){gx.fn.setGridControlValue("PROCESSOCONVANO",row || gx.fn.currentGridRowImpl(41),gx.O.A3373ProcessoConvAno,0)},c2v:function(){gx.O.A3373ProcessoConvAno=gx.num.intval(this.val())},val:function(row){return gx.fn.getGridIntegerValue("PROCESSOCONVANO",row || gx.fn.currentGridRowImpl(41),'.')},nac:gx.falseFn}; GXValidFnc[43]={lvl:2,type:"int",len:8,dec:0,sign:false,pic:"ZZZZZZZ9",ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVNUMERO",gxz:"Z3374ProcessoConvNumero",gxold:"O3374ProcessoConvNumero",gxvar:"A3374ProcessoConvNumero",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',v2v:function(Value){gx.O.A3374ProcessoConvNumero=gx.num.intval(Value)},v2z:function(Value){gx.O.Z3374ProcessoConvNumero=gx.num.intval(Value)},v2c:function(row){gx.fn.setGridControlValue("PROCESSOCONVNUMERO",row || gx.fn.currentGridRowImpl(41),gx.O.A3374ProcessoConvNumero,0)},c2v:function(){gx.O.A3374ProcessoConvNumero=gx.num.intval(this.val())},val:function(row){return gx.fn.getGridIntegerValue("PROCESSOCONVNUMERO",row || gx.fn.currentGridRowImpl(41),'.')},nac:gx.falseFn}; GXValidFnc[44]={lvl:2,type:"date",len:10,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVDATAINICIO",gxz:"Z3817ProcessoConvDataInicio",gxold:"O3817ProcessoConvDataInicio",gxvar:"A3817ProcessoConvDataInicio",dp:{f:0,st:false,wn:false,mf:false,pic:"99/99/9999",dec:0},ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',v2v:function(Value){gx.O.A3817ProcessoConvDataInicio=gx.fn.toDatetimeValue(Value)},v2z:function(Value){gx.O.Z3817ProcessoConvDataInicio=gx.fn.toDatetimeValue(Value)},v2c:function(row){gx.fn.setGridControlValue("PROCESSOCONVDATAINICIO",row || gx.fn.currentGridRowImpl(41),gx.O.A3817ProcessoConvDataInicio,0);if (typeof(this.dom_hdl) == 'function') this.dom_hdl.call(gx.O);},c2v:function(){gx.O.A3817ProcessoConvDataInicio=gx.fn.toDatetimeValue(this.val())},val:function(row){return gx.fn.getGridDateTimeValue("PROCESSOCONVDATAINICIO",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[45]={lvl:2,type:"char",len:1,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVSITUACAO",gxz:"Z3815ProcessoConvSituacao",gxold:"O3815ProcessoConvSituacao",gxvar:"A3815ProcessoConvSituacao",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"combo",inputType:'text',v2v:function(Value){gx.O.A3815ProcessoConvSituacao=Value},v2z:function(Value){gx.O.Z3815ProcessoConvSituacao=Value},v2c:function(row){gx.fn.setGridComboBoxValue("PROCESSOCONVSITUACAO",row || gx.fn.currentGridRowImpl(41),gx.O.A3815ProcessoConvSituacao)},c2v:function(){gx.O.A3815ProcessoConvSituacao=this.val()},val:function(row){return gx.fn.getGridControlValue("PROCESSOCONVSITUACAO",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[46]={lvl:2,type:"svchar",len:65,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"vFINALIDADE",gxz:"ZV23Finalidade",gxold:"OV23Finalidade",gxvar:"AV23Finalidade",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',autoCorrect:"1",v2v:function(Value){gx.O.AV23Finalidade=Value},v2z:function(Value){gx.O.ZV23Finalidade=Value},v2c:function(row){gx.fn.setGridControlValue("vFINALIDADE",row || gx.fn.currentGridRowImpl(41),gx.O.AV23Finalidade,0)},c2v:function(){gx.O.AV23Finalidade=this.val()},val:function(row){return gx.fn.getGridControlValue("vFINALIDADE",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[47]={lvl:2,type:"svchar",len:100,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVFINALIDADE",gxz:"Z3819ProcessoConvFinalidade",gxold:"O3819ProcessoConvFinalidade",gxvar:"A3819ProcessoConvFinalidade",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',autoCorrect:"1",v2v:function(Value){gx.O.A3819ProcessoConvFinalidade=Value},v2z:function(Value){gx.O.Z3819ProcessoConvFinalidade=Value},v2c:function(row){gx.fn.setGridControlValue("PROCESSOCONVFINALIDADE",row || gx.fn.currentGridRowImpl(41),gx.O.A3819ProcessoConvFinalidade,0)},c2v:function(){gx.O.A3819ProcessoConvFinalidade=this.val()},val:function(row){return gx.fn.getGridControlValue("PROCESSOCONVFINALIDADE",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[48]={lvl:2,type:"int",len:7,dec:0,sign:false,pic:"ZZZZZZ9",ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:this.Valid_Convenioid,isvalid:null,rgrid:[],fld:"CONVENIOID",gxz:"Z1681ConvenioId",gxold:"O1681ConvenioId",gxvar:"A1681ConvenioId",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',v2v:function(Value){gx.O.A1681ConvenioId=gx.num.intval(Value)},v2z:function(Value){gx.O.Z1681ConvenioId=gx.num.intval(Value)},v2c:function(row){gx.fn.setGridControlValue("CONVENIOID",row || gx.fn.currentGridRowImpl(41),gx.O.A1681ConvenioId,0)},c2v:function(){gx.O.A1681ConvenioId=gx.num.intval(this.val())},val:function(row){return gx.fn.getGridIntegerValue("CONVENIOID",row || gx.fn.currentGridRowImpl(41),'.')},nac:gx.falseFn}; GXValidFnc[49]={lvl:2,type:"svchar",len:40,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"CONVENIODESCRICAO",gxz:"Z2082ConvenioDescricao",gxold:"O2082ConvenioDescricao",gxvar:"A2082ConvenioDescricao",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',autoCorrect:"1",v2v:function(Value){gx.O.A2082ConvenioDescricao=Value},v2z:function(Value){gx.O.Z2082ConvenioDescricao=Value},v2c:function(row){gx.fn.setGridControlValue("CONVENIODESCRICAO",row || gx.fn.currentGridRowImpl(41),gx.O.A2082ConvenioDescricao,0);if (typeof(this.dom_hdl) == 'function') this.dom_hdl.call(gx.O);},c2v:function(){gx.O.A2082ConvenioDescricao=this.val()},val:function(row){return gx.fn.getGridControlValue("CONVENIODESCRICAO",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[50]={lvl:2,type:"svchar",len:40,dec:0,sign:false,ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"vCONVENIODESCRICAOGRID",gxz:"ZV30ConvenioDescricaoGrid",gxold:"OV30ConvenioDescricaoGrid",gxvar:"AV30ConvenioDescricaoGrid",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',autoCorrect:"1",v2v:function(Value){gx.O.AV30ConvenioDescricaoGrid=Value},v2z:function(Value){gx.O.ZV30ConvenioDescricaoGrid=Value},v2c:function(row){gx.fn.setGridControlValue("vCONVENIODESCRICAOGRID",row || gx.fn.currentGridRowImpl(41),gx.O.AV30ConvenioDescricaoGrid,0)},c2v:function(){gx.O.AV30ConvenioDescricaoGrid=this.val()},val:function(row){return gx.fn.getGridControlValue("vCONVENIODESCRICAOGRID",row || gx.fn.currentGridRowImpl(41))},nac:gx.falseFn}; GXValidFnc[51]={lvl:2,type:"decimal",len:18,dec:2,sign:false,pic:"ZZZ,ZZZ,ZZZ,ZZZ,ZZ9.99",ro:1,isacc:0,grid:41,gxgrid:this.GridContainer,fnc:null,isvalid:null,rgrid:[],fld:"PROCESSOCONVVALOR",gxz:"Z3820ProcessoConvValor",gxold:"O3820ProcessoConvValor",gxvar:"A3820ProcessoConvValor",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",inputType:'text',v2v:function(Value){gx.O.A3820ProcessoConvValor=gx.fn.toDecimalValue(Value,',','.')},v2z:function(Value){gx.O.Z3820ProcessoConvValor=gx.fn.toDecimalValue(Value,'.',',')},v2c:function(row){gx.fn.setGridDecimalValue("PROCESSOCONVVALOR",row || gx.fn.currentGridRowImpl(41),gx.O.A3820ProcessoConvValor,2,',');if (typeof(this.dom_hdl) == 'function') this.dom_hdl.call(gx.O);},c2v:function(){gx.O.A3820ProcessoConvValor=this.val()},val:function(row){return gx.fn.getGridDecimalValue("PROCESSOCONVVALOR",row || gx.fn.currentGridRowImpl(41),'.',',')},nac:gx.falseFn}; GXValidFnc[57]={fld:"TABLENAV",grid:0}; GXValidFnc[60]={fld:"BTNPRIMEIRO",grid:0}; GXValidFnc[62]={fld:"BTNANTERIOR",grid:0}; GXValidFnc[64]={fld:"BTNPROXIMO",grid:0}; GXValidFnc[66]={fld:"BTNULTIMO",grid:0}; GXValidFnc[68]={fld:"BTNFECHAR",grid:0}; GXValidFnc[69]={fld:"JS", format:2,grid:0}; GXValidFnc[70]={lvl:0,type:"int",len:4,dec:0,sign:false,pic:"ZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vPAGINA",gxz:"ZV28Pagina",gxold:"OV28Pagina",gxvar:"AV28Pagina",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"combo",v2v:function(Value){gx.O.AV28Pagina=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV28Pagina=gx.num.intval(Value)},v2c:function(){gx.fn.setComboBoxValue("vPAGINA",gx.O.AV28Pagina)},c2v:function(){gx.O.AV28Pagina=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vPAGINA",'.')},nac:gx.falseFn}; GXValidFnc[71]={lvl:0,type:"int",len:4,dec:0,sign:false,pic:"ZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vPAGINAAUX",gxz:"ZV29PaginaAux",gxold:"OV29PaginaAux",gxvar:"AV29PaginaAux",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV29PaginaAux=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV29PaginaAux=gx.num.intval(Value)},v2c:function(){gx.fn.setControlValue("vPAGINAAUX",gx.O.AV29PaginaAux,0)},c2v:function(){gx.O.AV29PaginaAux=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vPAGINAAUX",'.')},nac:gx.falseFn}; GXValidFnc[72]={lvl:0,type:"char",len:10,dec:0,sign:false,pic:"@!",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[],fld:"vCONVENIOEMPRESAID",gxz:"ZV26ConvenioEmpresaId",gxold:"OV26ConvenioEmpresaId",gxvar:"AV26ConvenioEmpresaId",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV26ConvenioEmpresaId=Value},v2z:function(Value){gx.O.ZV26ConvenioEmpresaId=Value},v2c:function(){gx.fn.setControlValue("vCONVENIOEMPRESAID",gx.O.AV26ConvenioEmpresaId,0)},c2v:function(){gx.O.AV26ConvenioEmpresaId=this.val()},val:function(){return gx.fn.getControlValue("vCONVENIOEMPRESAID")},nac:gx.falseFn}; GXValidFnc[73]={lvl:0,type:"int",len:4,dec:0,sign:false,pic:"ZZZ9",ro:0,grid:0,gxgrid:null,fnc:null,isvalid:null,rgrid:[this.GridContainer],fld:"vORDEREDBY",gxz:"ZV5Orderedby",gxold:"OV5Orderedby",gxvar:"AV5Orderedby",ucs:[],op:[],ip:[],nacdep:[],ctrltype:"edit",v2v:function(Value){gx.O.AV5Orderedby=gx.num.intval(Value)},v2z:function(Value){gx.O.ZV5Orderedby=gx.num.intval(Value)},v2c:function(){gx.fn.setControlValue("vORDEREDBY",gx.O.AV5Orderedby,0)},c2v:function(){gx.O.AV5Orderedby=gx.num.intval(this.val())},val:function(){return gx.fn.getIntegerValue("vORDEREDBY",'.')},nac:gx.falseFn}; GXValidFnc[74]={fld:"PROMPT_CONVENIOID",grid:0}; this.AV18ProcessoConvAno = 0 ; this.ZV18ProcessoConvAno = 0 ; this.OV18ProcessoConvAno = 0 ; this.AV19ProcessoConvNumero = 0 ; this.ZV19ProcessoConvNumero = 0 ; this.OV19ProcessoConvNumero = 0 ; this.AV20ProcessoConvFinalidade = "" ; this.ZV20ProcessoConvFinalidade = "" ; this.OV20ProcessoConvFinalidade = "" ; this.AV31StProcesso = "" ; this.ZV31StProcesso = "" ; this.OV31StProcesso = "" ; this.AV21ConvenioId = 0 ; this.ZV21ConvenioId = 0 ; this.OV21ConvenioId = 0 ; this.AV22ConvenioDescricao = "" ; this.ZV22ConvenioDescricao = "" ; this.OV22ConvenioDescricao = "" ; this.Z3373ProcessoConvAno = 0 ; this.O3373ProcessoConvAno = 0 ; this.Z3374ProcessoConvNumero = 0 ; this.O3374ProcessoConvNumero = 0 ; this.Z3817ProcessoConvDataInicio = gx.date.nullDate() ; this.O3817ProcessoConvDataInicio = gx.date.nullDate() ; this.Z3815ProcessoConvSituacao = "" ; this.O3815ProcessoConvSituacao = "" ; this.ZV23Finalidade = "" ; this.OV23Finalidade = "" ; this.Z3819ProcessoConvFinalidade = "" ; this.O3819ProcessoConvFinalidade = "" ; this.Z1681ConvenioId = 0 ; this.O1681ConvenioId = 0 ; this.Z2082ConvenioDescricao = "" ; this.O2082ConvenioDescricao = "" ; this.ZV30ConvenioDescricaoGrid = "" ; this.OV30ConvenioDescricaoGrid = "" ; this.Z3820ProcessoConvValor = 0 ; this.O3820ProcessoConvValor = 0 ; this.AV28Pagina = 0 ; this.ZV28Pagina = 0 ; this.OV28Pagina = 0 ; this.AV29PaginaAux = 0 ; this.ZV29PaginaAux = 0 ; this.OV29PaginaAux = 0 ; this.AV26ConvenioEmpresaId = "" ; this.ZV26ConvenioEmpresaId = "" ; this.OV26ConvenioEmpresaId = "" ; this.AV5Orderedby = 0 ; this.ZV5Orderedby = 0 ; this.OV5Orderedby = 0 ; this.AV18ProcessoConvAno = 0 ; this.AV19ProcessoConvNumero = 0 ; this.AV20ProcessoConvFinalidade = "" ; this.AV31StProcesso = "" ; this.AV21ConvenioId = 0 ; this.AV22ConvenioDescricao = "" ; this.AV28Pagina = 0 ; this.AV29PaginaAux = 0 ; this.AV26ConvenioEmpresaId = "" ; this.AV5Orderedby = 0 ; this.AV17PProcessoConvAno = 0 ; this.AV16PProcessoConvNumero = 0 ; this.A3372ProcessoConvEmpresaId = "" ; this.A1680ConvenioEmpresaId = "" ; this.A3373ProcessoConvAno = 0 ; this.A3374ProcessoConvNumero = 0 ; this.A3817ProcessoConvDataInicio = gx.date.nullDate() ; this.A3815ProcessoConvSituacao = "" ; this.AV23Finalidade = "" ; this.A3819ProcessoConvFinalidade = "" ; this.A1681ConvenioId = 0 ; this.A2082ConvenioDescricao = "" ; this.AV30ConvenioDescricaoGrid = "" ; this.A3820ProcessoConvValor = 0 ; this.AV12EmpresaPadrao = "" ; this.Events = {"e17ni2_client": ["ENTER", true] ,"e11ni2_client": ["'GXM_FIRST'", true] ,"e12ni2_client": ["'GXM_PREVIOUS'", true] ,"e13ni2_client": ["'GXM_NEXT'", true] ,"e14ni2_client": ["'GXM_LAST'", true] ,"e15ni2_client": ["'PROCURAR'", true] ,"e20ni2_client": ["'ATUALIZAPAGINA'", true] ,"e21ni1_client": ["CANCEL", true]}; this.EvtParms["REFRESH"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'},{av:'AV5Orderedby',fld:'vORDEREDBY'}],[{ctrl:'PROCESSOCONVANO',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("PROCESSOCONVANO","Title")',ctrl:'PROCESSOCONVANO',prop:'Title'},{av:'AV7Imagem',fld:'vIMAGEM'},{ctrl:'PROCESSOCONVNUMERO',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("PROCESSOCONVNUMERO","Title")',ctrl:'PROCESSOCONVNUMERO',prop:'Title'},{ctrl:'PROCESSOCONVDATAINICIO',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("PROCESSOCONVDATAINICIO","Title")',ctrl:'PROCESSOCONVDATAINICIO',prop:'Title'},{ctrl:'PROCESSOCONVSITUACAO'},{ctrl:'vFINALIDADE',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("vFINALIDADE","Title")',ctrl:'vFINALIDADE',prop:'Title'},{ctrl:'CONVENIOID',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("CONVENIOID","Title")',ctrl:'CONVENIOID',prop:'Title'},{ctrl:'CONVENIODESCRICAO',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("CONVENIODESCRICAO","Title")',ctrl:'CONVENIODESCRICAO',prop:'Title'},{ctrl:'PROCESSOCONVVALOR',prop:'Titleformat'},{av:'gx.fn.getCtrlProperty("PROCESSOCONVVALOR","Title")',ctrl:'PROCESSOCONVVALOR',prop:'Title'},{av:'AV29PaginaAux',fld:'vPAGINAAUX'},{av:'AV28Pagina',fld:'vPAGINA'},{av:'AV27NumPagina',fld:'vNUMPAGINA'},{av:'gx.fn.getCtrlProperty("BTNANTERIOR","Enabled")',ctrl:'BTNANTERIOR',prop:'Enabled'},{av:'gx.fn.getCtrlProperty("BTNPROXIMO","Enabled")',ctrl:'BTNPROXIMO',prop:'Enabled'},{av:'gx.fn.getCtrlProperty("BTNPRIMEIRO","Enabled")',ctrl:'BTNPRIMEIRO',prop:'Enabled'},{av:'gx.fn.getCtrlProperty("BTNULTIMO","Enabled")',ctrl:'BTNULTIMO',prop:'Enabled'}]]; this.EvtParms["ENTER"] = [[{av:'A3373ProcessoConvAno',fld:'PROCESSOCONVANO'},{av:'A3374ProcessoConvNumero',fld:'PROCESSOCONVNUMERO'}],[{av:'AV17PProcessoConvAno',fld:'vPPROCESSOCONVANO'},{av:'AV16PProcessoConvNumero',fld:'vPPROCESSOCONVNUMERO'}]]; this.EvtParms["'GXM_FIRST'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'}],[{av:'AV28Pagina',fld:'vPAGINA'}]]; this.EvtParms["'GXM_PREVIOUS'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'},{av:'AV28Pagina',fld:'vPAGINA'}],[{av:'AV28Pagina',fld:'vPAGINA'}]]; this.EvtParms["'GXM_NEXT'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'},{av:'AV28Pagina',fld:'vPAGINA'},{av:'AV29PaginaAux',fld:'vPAGINAAUX'}],[{av:'AV28Pagina',fld:'vPAGINA'}]]; this.EvtParms["'GXM_LAST'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'},{av:'AV29PaginaAux',fld:'vPAGINAAUX'}],[{av:'AV28Pagina',fld:'vPAGINA'}]]; this.EvtParms["'PROCURAR'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'},{av:'AV9EmpresaLogadaId',fld:'vEMPRESALOGADAID'},{av:'AV39Pgmname',fld:'vPGMNAME'}],[{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV32OpcoesTxtTela',fld:'vOPCOESTXTTELA'}]]; this.EvtParms["LOAD"] = [[{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'}],[{av:'AV23Finalidade',fld:'vFINALIDADE'},{av:'gx.fn.getCtrlProperty("vFINALIDADE","Tooltiptext")',ctrl:'vFINALIDADE',prop:'Tooltiptext'},{av:'AV30ConvenioDescricaoGrid',fld:'vCONVENIODESCRICAOGRID'}]]; this.EvtParms["'ATUALIZAPAGINA'"] = [[{av:'GRID_nFirstRecordOnPage'},{av:'GRID_nEOF'},{av:'subGrid_Rows'},{av:'AV18ProcessoConvAno',fld:'vPROCESSOCONVANO'},{av:'AV19ProcessoConvNumero',fld:'vPROCESSOCONVNUMERO'},{av:'AV20ProcessoConvFinalidade',fld:'vPROCESSOCONVFINALIDADE'},{av:'AV31StProcesso',fld:'vSTPROCESSO'},{av:'AV21ConvenioId',fld:'vCONVENIOID'},{av:'AV5Orderedby',fld:'vORDEREDBY'},{av:'AV12EmpresaPadrao',fld:'vEMPRESAPADRAO'},{av:'A3819ProcessoConvFinalidade',fld:'PROCESSOCONVFINALIDADE'},{av:'A2082ConvenioDescricao',fld:'CONVENIODESCRICAO'}],[]]; this.setPrompt("PROMPT_CONVENIOID", [35]); this.setVCMap("AV12EmpresaPadrao", "vEMPRESAPADRAO", 0, "char"); this.setVCMap("AV17PProcessoConvAno", "vPPROCESSOCONVANO", 0, "int"); this.setVCMap("AV16PProcessoConvNumero", "vPPROCESSOCONVNUMERO", 0, "int"); this.setVCMap("AV12EmpresaPadrao", "vEMPRESAPADRAO", 0, "char"); GridContainer.addRefreshingVar(this.GXValidFnc[16]); GridContainer.addRefreshingVar(this.GXValidFnc[20]); GridContainer.addRefreshingVar(this.GXValidFnc[25]); GridContainer.addRefreshingVar(this.GXValidFnc[30]); GridContainer.addRefreshingVar(this.GXValidFnc[35]); GridContainer.addRefreshingVar(this.GXValidFnc[73]); GridContainer.addRefreshingVar({rfrVar:"AV12EmpresaPadrao"}); GridContainer.addRefreshingVar({rfrVar:"A3819ProcessoConvFinalidade", rfrProp:"Value", gxAttId:"3819"}); GridContainer.addRefreshingVar({rfrVar:"A2082ConvenioDescricao", rfrProp:"Value", gxAttId:"2082"}); this.InitStandaloneVars( ); }); gx.setParentObj(new hconsultaprocessoconv());
/* * # Semantic UI - 1.8.0 * https://github.com/Semantic-Org/Semantic-UI * http://www.semantic-ui.com/ * * Copyright 2014 Contributors * Released under the MIT license * http://opensource.org/licenses/MIT * */ !function(e,n,t,i){"use strict";e.fn.accordion=function(t){{var o,a=e(this),s=(new Date).getTime(),r=[],c=arguments[0],l="string"==typeof c,u=[].slice.call(arguments,1);n.requestAnimationFrame||n.mozRequestAnimationFrame||n.webkitRequestAnimationFrame||n.msRequestAnimationFrame||function(e){setTimeout(e,0)}}return a.each(function(){var d,f,m=e.isPlainObject(t)?e.extend(!0,{},e.fn.accordion.settings,t):e.extend({},e.fn.accordion.settings),p=m.className,g=m.namespace,b=m.selector,h=m.error,v="."+g,y="module-"+g,C=a.selector||"",O=e(this),x=O.find(b.title),F=O.find(b.content),T=this,A=O.data(y);f={initialize:function(){f.debug("Initializing accordion with bound events",O),O.on("click"+v,b.title,f.event.click),f.observeChanges(),f.instantiate()},instantiate:function(){A=f,O.data(y,f)},destroy:function(){f.debug("Destroying previous accordion for",O),O.removeData(y),x.off(v)},refresh:function(){x=O.find(b.title),F=O.find(b.content)},observeChanges:function(){"MutationObserver"in n&&(d=new MutationObserver(function(){f.debug("DOM tree modified, updating selector cache"),f.refresh()}),d.observe(T,{childList:!0,subtree:!0}),f.debug("Setting up mutation observer",d))},event:{click:function(){f.toggle.call(this)}},toggle:function(n){var t=n!==i?"number"==typeof n?x.eq(n):e(n):e(this),o=t.next(F),a=o.is(":visible");f.debug("Toggling visibility of content",t),a?m.collapsible?f.close.call(t):f.debug("Cannot close accordion content collapsing is disabled"):f.open.call(t)},open:function(n){var t=n!==i?"number"==typeof n?x.eq(n):e(n):e(this),o=t.next(F),a=o.is(":animated"),s=o.hasClass(p.active);a||s||(f.debug("Opening accordion content",t),m.exclusive&&f.closeOthers.call(t),t.addClass(p.active),m.animateChildren&&(e.fn.transition!==i&&O.transition("is supported")?o.children().transition({animation:"fade in",useFailSafe:!0,debug:m.debug,verbose:m.verbose,duration:m.duration}):o.children().stop().animate({opacity:1},m.duration,f.resetOpacity)),o.stop().slideDown(m.duration,m.easing,function(){o.addClass(p.active),f.reset.display.call(this),m.onOpen.call(this),m.onChange.call(this)}))},close:function(n){var t=n!==i?"number"==typeof n?x.eq(n):e(n):e(this),o=t.next(F),a=o.hasClass(p.active);a&&(f.debug("Closing accordion content",o),t.removeClass(p.active),o.removeClass(p.active).show(),m.animateChildren&&(e.fn.transition!==i&&O.transition("is supported")?o.children().transition({animation:"fade out",useFailSafe:!0,debug:m.debug,verbose:m.verbose,duration:m.duration}):o.children().stop().animate({opacity:0},m.duration,f.resetOpacity)),o.stop().slideUp(m.duration,m.easing,function(){f.reset.display.call(this),m.onClose.call(this),m.onChange.call(this)}))},closeOthers:function(n){var t,o,a,s=n!==i?x.eq(n):e(this),r=s.parents(b.content).prev(b.title),c=s.closest(b.accordion),l=b.title+"."+p.active+":visible",u=b.content+"."+p.active+":visible";m.closeNested?(t=c.find(l).not(r),a=t.next(F)):(t=c.find(l).not(r),o=c.find(u).find(l).not(r),t=t.not(o),a=t.next(F)),t.length>0&&(f.debug("Exclusive enabled, closing other content",t),t.removeClass(p.active),m.animateChildren&&(e.fn.transition!==i&&O.transition("is supported")?a.children().transition({animation:"fade out",useFailSafe:!0,debug:m.debug,verbose:m.verbose,duration:m.duration}):a.children().stop().animate({opacity:0},m.duration,f.resetOpacity)),a.stop().slideUp(m.duration,m.easing,function(){e(this).removeClass(p.active),f.reset.display.call(this)}))},reset:{display:function(){f.verbose("Removing inline display from element",this),e(this).css("display",""),""===e(this).attr("style")&&e(this).attr("style","").removeAttr("style")},opacity:function(){f.verbose("Removing inline opacity from element",this),e(this).css("opacity",""),""===e(this).attr("style")&&e(this).attr("style","").removeAttr("style")}},setting:function(n,t){if(f.debug("Changing setting",n,t),e.isPlainObject(n))e.extend(!0,m,n);else{if(t===i)return m[n];m[n]=t}},internal:function(n,t){return f.debug("Changing internal",n,t),t===i?f[n]:void(e.isPlainObject(n)?e.extend(!0,f,n):f[n]=t)},debug:function(){m.debug&&(m.performance?f.performance.log(arguments):(f.debug=Function.prototype.bind.call(console.info,console,m.name+":"),f.debug.apply(console,arguments)))},verbose:function(){m.verbose&&m.debug&&(m.performance?f.performance.log(arguments):(f.verbose=Function.prototype.bind.call(console.info,console,m.name+":"),f.verbose.apply(console,arguments)))},error:function(){f.error=Function.prototype.bind.call(console.error,console,m.name+":"),f.error.apply(console,arguments)},performance:{log:function(e){var n,t,i;m.performance&&(n=(new Date).getTime(),i=s||n,t=n-i,s=n,r.push({Name:e[0],Arguments:[].slice.call(e,1)||"",Element:T,"Execution Time":t})),clearTimeout(f.performance.timer),f.performance.timer=setTimeout(f.performance.display,100)},display:function(){var n=m.name+":",t=0;s=!1,clearTimeout(f.performance.timer),e.each(r,function(e,n){t+=n["Execution Time"]}),n+=" "+t+"ms",C&&(n+=" '"+C+"'"),(console.group!==i||console.table!==i)&&r.length>0&&(console.groupCollapsed(n),console.table?console.table(r):e.each(r,function(e,n){console.log(n.Name+": "+n["Execution Time"]+"ms")}),console.groupEnd()),r=[]}},invoke:function(n,t,a){var s,r,c,l=A;return t=t||u,a=T||a,"string"==typeof n&&l!==i&&(n=n.split(/[\. ]/),s=n.length-1,e.each(n,function(t,o){var a=t!=s?o+n[t+1].charAt(0).toUpperCase()+n[t+1].slice(1):n;if(e.isPlainObject(l[a])&&t!=s)l=l[a];else{if(l[a]!==i)return r=l[a],!1;if(!e.isPlainObject(l[o])||t==s)return l[o]!==i?(r=l[o],!1):(f.error(h.method,n),!1);l=l[o]}})),e.isFunction(r)?c=r.apply(a,t):r!==i&&(c=r),e.isArray(o)?o.push(c):o!==i?o=[o,c]:c!==i&&(o=c),r}},l?(A===i&&f.initialize(),f.invoke(c)):(A!==i&&f.destroy(),f.initialize())}),o!==i?o:this},e.fn.accordion.settings={name:"Accordion",namespace:"accordion",debug:!1,verbose:!0,performance:!0,exclusive:!0,collapsible:!0,closeNested:!1,animateChildren:!0,duration:500,easing:"easeOutQuint",onOpen:function(){},onClose:function(){},onChange:function(){},error:{method:"The method you called is not defined"},className:{active:"active"},selector:{accordion:".accordion",title:".title",content:".content"}},e.extend(e.easing,{easeOutQuint:function(e,n,t,i,o){return i*((n=n/o-1)*n*n*n*n+1)+t}})}(jQuery,window,document);
(this.webpackJsonpdashboard=this.webpackJsonpdashboard||[]).push([[85],{557:function(e,t,o){"use strict";function r(e){e.languages.mel={comment:/\/\/.*/,code:{pattern:/`(?:\\.|[^\\`\r\n])*`/,greedy:!0,alias:"italic",inside:{delimiter:{pattern:/^`|`$/,alias:"punctuation"}}},string:{pattern:/"(?:\\.|[^\\"\r\n])*"/,greedy:!0},variable:/\$\w+/,number:/\b0x[\da-fA-F]+\b|\b\d+\.?\d*|\B\.\d+/,flag:{pattern:/-[^\d\W]\w*/,alias:"operator"},keyword:/\b(?:break|case|continue|default|do|else|float|for|global|if|in|int|matrix|proc|return|string|switch|vector|while)\b/,function:/\w+(?=\()|\b(?:about|abs|addAttr|addAttributeEditorNodeHelp|addDynamic|addNewShelfTab|addPP|addPanelCategory|addPrefixToName|advanceToNextDrivenKey|affectedNet|affects|aimConstraint|air|alias|aliasAttr|align|alignCtx|alignCurve|alignSurface|allViewFit|ambientLight|angle|angleBetween|animCone|animCurveEditor|animDisplay|animView|annotate|appendStringArray|applicationName|applyAttrPreset|applyTake|arcLenDimContext|arcLengthDimension|arclen|arrayMapper|art3dPaintCtx|artAttrCtx|artAttrPaintVertexCtx|artAttrSkinPaintCtx|artAttrTool|artBuildPaintMenu|artFluidAttrCtx|artPuttyCtx|artSelectCtx|artSetPaintCtx|artUserPaintCtx|assignCommand|assignInputDevice|assignViewportFactories|attachCurve|attachDeviceAttr|attachSurface|attrColorSliderGrp|attrCompatibility|attrControlGrp|attrEnumOptionMenu|attrEnumOptionMenuGrp|attrFieldGrp|attrFieldSliderGrp|attrNavigationControlGrp|attrPresetEditWin|attributeExists|attributeInfo|attributeMenu|attributeQuery|autoKeyframe|autoPlace|bakeClip|bakeFluidShading|bakePartialHistory|bakeResults|bakeSimulation|basename|basenameEx|batchRender|bessel|bevel|bevelPlus|binMembership|bindSkin|blend2|blendShape|blendShapeEditor|blendShapePanel|blendTwoAttr|blindDataType|boneLattice|boundary|boxDollyCtx|boxZoomCtx|bufferCurve|buildBookmarkMenu|buildKeyframeMenu|button|buttonManip|CBG|cacheFile|cacheFileCombine|cacheFileMerge|cacheFileTrack|camera|cameraView|canCreateManip|canvas|capitalizeString|catch|catchQuiet|ceil|changeSubdivComponentDisplayLevel|changeSubdivRegion|channelBox|character|characterMap|characterOutlineEditor|characterize|chdir|checkBox|checkBoxGrp|checkDefaultRenderGlobals|choice|circle|circularFillet|clamp|clear|clearCache|clip|clipEditor|clipEditorCurrentTimeCtx|clipSchedule|clipSchedulerOutliner|clipTrimBefore|closeCurve|closeSurface|cluster|cmdFileOutput|cmdScrollFieldExecuter|cmdScrollFieldReporter|cmdShell|coarsenSubdivSelectionList|collision|color|colorAtPoint|colorEditor|colorIndex|colorIndexSliderGrp|colorSliderButtonGrp|colorSliderGrp|columnLayout|commandEcho|commandLine|commandPort|compactHairSystem|componentEditor|compositingInterop|computePolysetVolume|condition|cone|confirmDialog|connectAttr|connectControl|connectDynamic|connectJoint|connectionInfo|constrain|constrainValue|constructionHistory|container|containsMultibyte|contextInfo|control|convertFromOldLayers|convertIffToPsd|convertLightmap|convertSolidTx|convertTessellation|convertUnit|copyArray|copyFlexor|copyKey|copySkinWeights|cos|cpButton|cpCache|cpClothSet|cpCollision|cpConstraint|cpConvClothToMesh|cpForces|cpGetSolverAttr|cpPanel|cpProperty|cpRigidCollisionFilter|cpSeam|cpSetEdit|cpSetSolverAttr|cpSolver|cpSolverTypes|cpTool|cpUpdateClothUVs|createDisplayLayer|createDrawCtx|createEditor|createLayeredPsdFile|createMotionField|createNewShelf|createNode|createRenderLayer|createSubdivRegion|cross|crossProduct|ctxAbort|ctxCompletion|ctxEditMode|ctxTraverse|currentCtx|currentTime|currentTimeCtx|currentUnit|curve|curveAddPtCtx|curveCVCtx|curveEPCtx|curveEditorCtx|curveIntersect|curveMoveEPCtx|curveOnSurface|curveSketchCtx|cutKey|cycleCheck|cylinder|dagPose|date|defaultLightListCheckBox|defaultNavigation|defineDataServer|defineVirtualDevice|deformer|deg_to_rad|delete|deleteAttr|deleteShadingGroupsAndMaterials|deleteShelfTab|deleteUI|deleteUnusedBrushes|delrandstr|detachCurve|detachDeviceAttr|detachSurface|deviceEditor|devicePanel|dgInfo|dgdirty|dgeval|dgtimer|dimWhen|directKeyCtx|directionalLight|dirmap|dirname|disable|disconnectAttr|disconnectJoint|diskCache|displacementToPoly|displayAffected|displayColor|displayCull|displayLevelOfDetail|displayPref|displayRGBColor|displaySmoothness|displayStats|displayString|displaySurface|distanceDimContext|distanceDimension|doBlur|dolly|dollyCtx|dopeSheetEditor|dot|dotProduct|doubleProfileBirailSurface|drag|dragAttrContext|draggerContext|dropoffLocator|duplicate|duplicateCurve|duplicateSurface|dynCache|dynControl|dynExport|dynExpression|dynGlobals|dynPaintEditor|dynParticleCtx|dynPref|dynRelEdPanel|dynRelEditor|dynamicLoad|editAttrLimits|editDisplayLayerGlobals|editDisplayLayerMembers|editRenderLayerAdjustment|editRenderLayerGlobals|editRenderLayerMembers|editor|editorTemplate|effector|emit|emitter|enableDevice|encodeString|endString|endsWith|env|equivalent|equivalentTol|erf|error|eval|evalDeferred|evalEcho|event|exactWorldBoundingBox|exclusiveLightCheckBox|exec|executeForEachObject|exists|exp|expression|expressionEditorListen|extendCurve|extendSurface|extrude|fcheck|fclose|feof|fflush|fgetline|fgetword|file|fileBrowserDialog|fileDialog|fileExtension|fileInfo|filetest|filletCurve|filter|filterCurve|filterExpand|filterStudioImport|findAllIntersections|findAnimCurves|findKeyframe|findMenuItem|findRelatedSkinCluster|finder|firstParentOf|fitBspline|flexor|floatEq|floatField|floatFieldGrp|floatScrollBar|floatSlider|floatSlider2|floatSliderButtonGrp|floatSliderGrp|floor|flow|fluidCacheInfo|fluidEmitter|fluidVoxelInfo|flushUndo|fmod|fontDialog|fopen|formLayout|format|fprint|frameLayout|fread|freeFormFillet|frewind|fromNativePath|fwrite|gamma|gauss|geometryConstraint|getApplicationVersionAsFloat|getAttr|getClassification|getDefaultBrush|getFileList|getFluidAttr|getInputDeviceRange|getMayaPanelTypes|getModifiers|getPanel|getParticleAttr|getPluginResource|getenv|getpid|glRender|glRenderEditor|globalStitch|gmatch|goal|gotoBindPose|grabColor|gradientControl|gradientControlNoAttr|graphDollyCtx|graphSelectContext|graphTrackCtx|gravity|grid|gridLayout|group|groupObjectsByName|HfAddAttractorToAS|HfAssignAS|HfBuildEqualMap|HfBuildFurFiles|HfBuildFurImages|HfCancelAFR|HfConnectASToHF|HfCreateAttractor|HfDeleteAS|HfEditAS|HfPerformCreateAS|HfRemoveAttractorFromAS|HfSelectAttached|HfSelectAttractors|HfUnAssignAS|hardenPointCurve|hardware|hardwareRenderPanel|headsUpDisplay|headsUpMessage|help|helpLine|hermite|hide|hilite|hitTest|hotBox|hotkey|hotkeyCheck|hsv_to_rgb|hudButton|hudSlider|hudSliderButton|hwReflectionMap|hwRender|hwRenderLoad|hyperGraph|hyperPanel|hyperShade|hypot|iconTextButton|iconTextCheckBox|iconTextRadioButton|iconTextRadioCollection|iconTextScrollList|iconTextStaticLabel|ikHandle|ikHandleCtx|ikHandleDisplayScale|ikSolver|ikSplineHandleCtx|ikSystem|ikSystemInfo|ikfkDisplayMethod|illustratorCurves|image|imfPlugins|inheritTransform|insertJoint|insertJointCtx|insertKeyCtx|insertKnotCurve|insertKnotSurface|instance|instanceable|instancer|intField|intFieldGrp|intScrollBar|intSlider|intSliderGrp|interToUI|internalVar|intersect|iprEngine|isAnimCurve|isConnected|isDirty|isParentOf|isSameObject|isTrue|isValidObjectName|isValidString|isValidUiName|isolateSelect|itemFilter|itemFilterAttr|itemFilterRender|itemFilterType|joint|jointCluster|jointCtx|jointDisplayScale|jointLattice|keyTangent|keyframe|keyframeOutliner|keyframeRegionCurrentTimeCtx|keyframeRegionDirectKeyCtx|keyframeRegionDollyCtx|keyframeRegionInsertKeyCtx|keyframeRegionMoveKeyCtx|keyframeRegionScaleKeyCtx|keyframeRegionSelectKeyCtx|keyframeRegionSetKeyCtx|keyframeRegionTrackCtx|keyframeStats|lassoContext|lattice|latticeDeformKeyCtx|launch|launchImageEditor|layerButton|layeredShaderPort|layeredTexturePort|layout|layoutDialog|lightList|lightListEditor|lightListPanel|lightlink|lineIntersection|linearPrecision|linstep|listAnimatable|listAttr|listCameras|listConnections|listDeviceAttachments|listHistory|listInputDeviceAxes|listInputDeviceButtons|listInputDevices|listMenuAnnotation|listNodeTypes|listPanelCategories|listRelatives|listSets|listTransforms|listUnselected|listerEditor|loadFluid|loadNewShelf|loadPlugin|loadPluginLanguageResources|loadPrefObjects|localizedPanelLabel|lockNode|loft|log|longNameOf|lookThru|ls|lsThroughFilter|lsType|lsUI|Mayatomr|mag|makeIdentity|makeLive|makePaintable|makeRoll|makeSingleSurface|makeTubeOn|makebot|manipMoveContext|manipMoveLimitsCtx|manipOptions|manipRotateContext|manipRotateLimitsCtx|manipScaleContext|manipScaleLimitsCtx|marker|match|max|memory|menu|menuBarLayout|menuEditor|menuItem|menuItemToShelf|menuSet|menuSetPref|messageLine|min|minimizeApp|mirrorJoint|modelCurrentTimeCtx|modelEditor|modelPanel|mouse|movIn|movOut|move|moveIKtoFK|moveKeyCtx|moveVertexAlongDirection|multiProfileBirailSurface|mute|nParticle|nameCommand|nameField|namespace|namespaceInfo|newPanelItems|newton|nodeCast|nodeIconButton|nodeOutliner|nodePreset|nodeType|noise|nonLinear|normalConstraint|normalize|nurbsBoolean|nurbsCopyUVSet|nurbsCube|nurbsEditUV|nurbsPlane|nurbsSelect|nurbsSquare|nurbsToPoly|nurbsToPolygonsPref|nurbsToSubdiv|nurbsToSubdivPref|nurbsUVSet|nurbsViewDirectionVector|objExists|objectCenter|objectLayer|objectType|objectTypeUI|obsoleteProc|oceanNurbsPreviewPlane|offsetCurve|offsetCurveOnSurface|offsetSurface|openGLExtension|openMayaPref|optionMenu|optionMenuGrp|optionVar|orbit|orbitCtx|orientConstraint|outlinerEditor|outlinerPanel|overrideModifier|paintEffectsDisplay|pairBlend|palettePort|paneLayout|panel|panelConfiguration|panelHistory|paramDimContext|paramDimension|paramLocator|parent|parentConstraint|particle|particleExists|particleInstancer|particleRenderInfo|partition|pasteKey|pathAnimation|pause|pclose|percent|performanceOptions|pfxstrokes|pickWalk|picture|pixelMove|planarSrf|plane|play|playbackOptions|playblast|plugAttr|plugNode|pluginInfo|pluginResourceUtil|pointConstraint|pointCurveConstraint|pointLight|pointMatrixMult|pointOnCurve|pointOnSurface|pointPosition|poleVectorConstraint|polyAppend|polyAppendFacetCtx|polyAppendVertex|polyAutoProjection|polyAverageNormal|polyAverageVertex|polyBevel|polyBlendColor|polyBlindData|polyBoolOp|polyBridgeEdge|polyCacheMonitor|polyCheck|polyChipOff|polyClipboard|polyCloseBorder|polyCollapseEdge|polyCollapseFacet|polyColorBlindData|polyColorDel|polyColorPerVertex|polyColorSet|polyCompare|polyCone|polyCopyUV|polyCrease|polyCreaseCtx|polyCreateFacet|polyCreateFacetCtx|polyCube|polyCut|polyCutCtx|polyCylinder|polyCylindricalProjection|polyDelEdge|polyDelFacet|polyDelVertex|polyDuplicateAndConnect|polyDuplicateEdge|polyEditUV|polyEditUVShell|polyEvaluate|polyExtrudeEdge|polyExtrudeFacet|polyExtrudeVertex|polyFlipEdge|polyFlipUV|polyForceUV|polyGeoSampler|polyHelix|polyInfo|polyInstallAction|polyLayoutUV|polyListComponentConversion|polyMapCut|polyMapDel|polyMapSew|polyMapSewMove|polyMergeEdge|polyMergeEdgeCtx|polyMergeFacet|polyMergeFacetCtx|polyMergeUV|polyMergeVertex|polyMirrorFace|polyMoveEdge|polyMoveFacet|polyMoveFacetUV|polyMoveUV|polyMoveVertex|polyNormal|polyNormalPerVertex|polyNormalizeUV|polyOptUvs|polyOptions|polyOutput|polyPipe|polyPlanarProjection|polyPlane|polyPlatonicSolid|polyPoke|polyPrimitive|polyPrism|polyProjection|polyPyramid|polyQuad|polyQueryBlindData|polyReduce|polySelect|polySelectConstraint|polySelectConstraintMonitor|polySelectCtx|polySelectEditCtx|polySeparate|polySetToFaceNormal|polySewEdge|polyShortestPathCtx|polySmooth|polySoftEdge|polySphere|polySphericalProjection|polySplit|polySplitCtx|polySplitEdge|polySplitRing|polySplitVertex|polyStraightenUVBorder|polySubdivideEdge|polySubdivideFacet|polyToSubdiv|polyTorus|polyTransfer|polyTriangulate|polyUVSet|polyUnite|polyWedgeFace|popen|popupMenu|pose|pow|preloadRefEd|print|progressBar|progressWindow|projFileViewer|projectCurve|projectTangent|projectionContext|projectionManip|promptDialog|propModCtx|propMove|psdChannelOutliner|psdEditTextureFile|psdExport|psdTextureFile|putenv|pwd|python|querySubdiv|quit|rad_to_deg|radial|radioButton|radioButtonGrp|radioCollection|radioMenuItemCollection|rampColorPort|rand|randomizeFollicles|randstate|rangeControl|readTake|rebuildCurve|rebuildSurface|recordAttr|recordDevice|redo|reference|referenceEdit|referenceQuery|refineSubdivSelectionList|refresh|refreshAE|registerPluginResource|rehash|reloadImage|removeJoint|removeMultiInstance|removePanelCategory|rename|renameAttr|renameSelectionList|renameUI|render|renderGlobalsNode|renderInfo|renderLayerButton|renderLayerParent|renderLayerPostProcess|renderLayerUnparent|renderManip|renderPartition|renderQualityNode|renderSettings|renderThumbnailUpdate|renderWindowEditor|renderWindowSelectContext|renderer|reorder|reorderDeformers|requires|reroot|resampleFluid|resetAE|resetPfxToPolyCamera|resetTool|resolutionNode|retarget|reverseCurve|reverseSurface|revolve|rgb_to_hsv|rigidBody|rigidSolver|roll|rollCtx|rootOf|rot|rotate|rotationInterpolation|roundConstantRadius|rowColumnLayout|rowLayout|runTimeCommand|runup|sampleImage|saveAllShelves|saveAttrPreset|saveFluid|saveImage|saveInitialState|saveMenu|savePrefObjects|savePrefs|saveShelf|saveToolSettings|scale|scaleBrushBrightness|scaleComponents|scaleConstraint|scaleKey|scaleKeyCtx|sceneEditor|sceneUIReplacement|scmh|scriptCtx|scriptEditorInfo|scriptJob|scriptNode|scriptTable|scriptToShelf|scriptedPanel|scriptedPanelType|scrollField|scrollLayout|sculpt|searchPathArray|seed|selLoadSettings|select|selectContext|selectCurveCV|selectKey|selectKeyCtx|selectKeyframeRegionCtx|selectMode|selectPref|selectPriority|selectType|selectedNodes|selectionConnection|separator|setAttr|setAttrEnumResource|setAttrMapping|setAttrNiceNameResource|setConstraintRestPosition|setDefaultShadingGroup|setDrivenKeyframe|setDynamic|setEditCtx|setEditor|setFluidAttr|setFocus|setInfinity|setInputDeviceMapping|setKeyCtx|setKeyPath|setKeyframe|setKeyframeBlendshapeTargetWts|setMenuMode|setNodeNiceNameResource|setNodeTypeFlag|setParent|setParticleAttr|setPfxToPolyCamera|setPluginResource|setProject|setStampDensity|setStartupMessage|setState|setToolTo|setUITemplate|setXformManip|sets|shadingConnection|shadingGeometryRelCtx|shadingLightRelCtx|shadingNetworkCompare|shadingNode|shapeCompare|shelfButton|shelfLayout|shelfTabLayout|shellField|shortNameOf|showHelp|showHidden|showManipCtx|showSelectionInTitle|showShadingGroupAttrEditor|showWindow|sign|simplify|sin|singleProfileBirailSurface|size|sizeBytes|skinCluster|skinPercent|smoothCurve|smoothTangentSurface|smoothstep|snap2to2|snapKey|snapMode|snapTogetherCtx|snapshot|soft|softMod|softModCtx|sort|sound|soundControl|source|spaceLocator|sphere|sphrand|spotLight|spotLightPreviewPort|spreadSheetEditor|spring|sqrt|squareSurface|srtContext|stackTrace|startString|startsWith|stitchAndExplodeShell|stitchSurface|stitchSurfacePoints|strcmp|stringArrayCatenate|stringArrayContains|stringArrayCount|stringArrayInsertAtIndex|stringArrayIntersector|stringArrayRemove|stringArrayRemoveAtIndex|stringArrayRemoveDuplicates|stringArrayRemoveExact|stringArrayToString|stringToStringArray|strip|stripPrefixFromName|stroke|subdAutoProjection|subdCleanTopology|subdCollapse|subdDuplicateAndConnect|subdEditUV|subdListComponentConversion|subdMapCut|subdMapSewMove|subdMatchTopology|subdMirror|subdToBlind|subdToPoly|subdTransferUVsToCache|subdiv|subdivCrease|subdivDisplaySmoothness|substitute|substituteAllString|substituteGeometry|substring|surface|surfaceSampler|surfaceShaderList|swatchDisplayPort|switchTable|symbolButton|symbolCheckBox|sysFile|system|tabLayout|tan|tangentConstraint|texLatticeDeformContext|texManipContext|texMoveContext|texMoveUVShellContext|texRotateContext|texScaleContext|texSelectContext|texSelectShortestPathCtx|texSmudgeUVContext|texWinToolCtx|text|textCurves|textField|textFieldButtonGrp|textFieldGrp|textManip|textScrollList|textToShelf|textureDisplacePlane|textureHairColor|texturePlacementContext|textureWindow|threadCount|threePointArcCtx|timeControl|timePort|timerX|toNativePath|toggle|toggleAxis|toggleWindowVisibility|tokenize|tokenizeList|tolerance|tolower|toolButton|toolCollection|toolDropped|toolHasOptions|toolPropertyWindow|torus|toupper|trace|track|trackCtx|transferAttributes|transformCompare|transformLimits|translator|trim|trunc|truncateFluidCache|truncateHairCache|tumble|tumbleCtx|turbulence|twoPointArcCtx|uiRes|uiTemplate|unassignInputDevice|undo|undoInfo|ungroup|uniform|unit|unloadPlugin|untangleUV|untitledFileName|untrim|upAxis|updateAE|userCtx|uvLink|uvSnapshot|validateShelfName|vectorize|view2dToolCtx|viewCamera|viewClipPlane|viewFit|viewHeadOn|viewLookAt|viewManip|viewPlace|viewSet|visor|volumeAxis|vortex|waitCursor|warning|webBrowser|webBrowserPrefs|whatIs|window|windowPref|wire|wireContext|workspace|wrinkle|wrinkleContext|writeTake|xbmLangPathList|xform)\b/,operator:[/\+[+=]?|-[-=]?|&&|\|\||[<>]=|[*\/!=]=?|[%^]/,{pattern:/(^|[^<])<(?!<)/,lookbehind:!0},{pattern:/(^|[^>])>(?!>)/,lookbehind:!0}],punctuation:/<<|>>|[.,:;?\[\](){}]/},e.languages.mel.code.inside.rest=e.languages.mel}e.exports=r,r.displayName="mel",r.aliases=[]}}]);
import { createBrowserHistory } from 'history'; import routeConstants from '@utils/routeConstants'; export const setbaseUrl = () => { let baseUrl = ''; const routes = Object.keys(routeConstants); const pathname = window.location.pathname; if (process.env.ENVIRONMENT_NAME === 'uat') { routes.forEach((routeKey) => { let route = routeConstants[routeKey].route; const pathnames = pathname.split('/'); const ids = []; let index = 0; pathnames.forEach((p) => { const num = parseInt(p, 10); if (!Number.isNaN(num)) { ids.push({ value: p, startIndex: index }); } index += p.length + 1; }); let idCounter = 0; while (ids.length && idCounter < ids.length && route.includes(':')) { const currentSegmentId = pathname.substring( ids[idCounter].startIndex, ids[idCounter].startIndex + ids[idCounter].value.length ); const indexOfColon = route.indexOf(':'); let indexOfSlash = route.length; for (let i = indexOfColon; i < route.length; i++) { if (route.charAt(i) === '/') { indexOfSlash = i; break; } } route = route.replace(route.substring(indexOfColon, indexOfSlash), currentSegmentId); idCounter++; } if (pathname.includes(route)) { if (pathname.substring(pathname.length - route.length, pathname.length) === route) { baseUrl = pathname.substring(0, pathname.length - route.length); } if (pathname.substring(pathname.length - route.length - 1, pathname.length) === `${route}/`) { baseUrl = pathname.substring(0, pathname.length - route.length - 1); } } }); } return baseUrl; }; const history = createBrowserHistory({ basename: setbaseUrl() }); export default history;
/* * Copyright 2014,2015 Open Networking Laboratory * * 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. */ /* ONOS GUI -- Util -- Theme Service - Unit Tests */ describe('factory: fw/util/theme.js', function() { var ts, $log, fs; beforeEach(module('onosUtil')); beforeEach(inject(function (ThemeService, _$log_, FnService) { ts = ThemeService; $log = _$log_; fs = FnService; ts.init(); })); it('should define ThemeService', function () { expect(ts).toBeDefined(); }); it('should define api functions', function () { expect(fs.areFunctions(ts, [ 'init', 'theme', 'toggleTheme', 'addListener', 'removeListener' ])).toBeTruthy(); }); function verifyBodyClass(yes, no) { function bodyHasClass(c) { return d3.select('body').classed(c); } expect(bodyHasClass(yes)).toBeTruthy(); expect(bodyHasClass(no)).toBeFalsy(); } it('should default to light theme', function () { expect(ts.theme()).toEqual('light'); }); it('should toggle to dark, then to light again', function () { // Note: re-work this once theme-change listeners are implemented spyOn($log, 'debug'); expect(ts.toggleTheme()).toEqual('dark'); expect(ts.theme()).toEqual('dark'); expect($log.debug).toHaveBeenCalledWith('Theme-Change-(toggle): dark'); verifyBodyClass('dark', 'light'); expect(ts.toggleTheme()).toEqual('light'); expect(ts.theme()).toEqual('light'); expect($log.debug).toHaveBeenCalledWith('Theme-Change-(toggle): light'); verifyBodyClass('light', 'dark'); }); it('should let us set the theme by name', function () { // Note: re-work this once theme-change listeners are implemented spyOn($log, 'debug'); expect(ts.theme()).toEqual('light'); ts.theme('dark'); expect(ts.theme()).toEqual('dark'); expect($log.debug).toHaveBeenCalledWith('Theme-Change-(set): dark'); verifyBodyClass('dark', 'light'); }); it('should ignore unknown theme names', function () { // Note: re-work this once theme-change listeners are implemented spyOn($log, 'debug'); expect(ts.theme()).toEqual('light'); verifyBodyClass('light', 'dark'); ts.theme('turquoise'); expect(ts.theme()).toEqual('light'); expect($log.debug).not.toHaveBeenCalled(); verifyBodyClass('light', 'dark'); }); // === Unit Tests for listeners it('should report lack of callback', function () { spyOn($log, 'error'); var list = ts.addListener(); expect($log.error).toHaveBeenCalledWith( 'ThemeService.addListener(): callback not a function' ); expect(list.error).toEqual('No callback defined'); }); it('should report non-functional callback', function () { spyOn($log, 'error'); var list = ts.addListener(['some array']); expect($log.error).toHaveBeenCalledWith( 'ThemeService.addListener(): callback not a function' ); expect(list.error).toEqual('No callback defined'); }); it('should invoke our callback with an event', function () { var event; function cb(ev) { event = ev; } expect(event).toBeUndefined(); ts.addListener(cb); ts.theme('dark'); expect(event).toEqual({ event: 'themeChange', value: 'dark' }); }); it('should invoke our callback at appropriate times', function () { var calls = [], phase, listener; function cb() { calls.push(phase); } expect(calls).toEqual([]); phase = 'pre'; ts.toggleTheme(); // -> dark phase = 'added'; listener = ts.addListener(cb); ts.toggleTheme(); // -> light phase = 'same'; ts.theme('light'); // (still light - no event) phase = 'diff'; ts.theme('dark'); // -> dark phase = 'post'; ts.removeListener(listener); ts.toggleTheme(); // -> light expect(calls).toEqual(['added', 'diff']); }); });
# -*- coding: utf-8 -*- from scout.commands import cli def test_update_diseases(mock_app): """Tests the CLI that updates disease terms in database""" runner = mock_app.test_cli_runner() assert runner # Test CLI base, no arguments provided result = runner.invoke(cli, ["update", "diseases"]) assert ( "WARNING Please provide a omim api key to load the omim gene panel" in result.output ) # command raises error because no valid key is provided assert result.exit_code != 0 # Test CLI base, provide non valid API key result = runner.invoke(cli, ["update", "diseases", "--api-key", "not_a_valid_key"]) assert result.exit_code != 0 assert ( "Seems like url https://data.omim.org/downloads/not_a_valid_key/genemap2.txt does not exist" in result.output )
"use strict"; var __assign = (this && this.__assign) || function () { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); var mithril_1 = __importDefault(require("mithril")); var EmployeeGroupLine = { view: function (_a) { var attrs = _a.attrs; return mithril_1.default("svg", __assign({ "xmlns": "http://www.w3.org/2000/svg", "width": 36, "height": 36, "viewBox": "0 0 36 36" }, attrs), mithril_1.default("title", {}, "employee_group_line"), mithril_1.default("g", { "id": "e1709d41-49e9-409f-9912-e2615f9236f6", "data-name": "Layer 3" }, mithril_1.default("path", { "d": "M18.42,16.31a5.7,5.7,0,1,1,5.76-5.7A5.74,5.74,0,0,1,18.42,16.31Zm0-9.4a3.7,3.7,0,1,0,3.76,3.7A3.74,3.74,0,0,0,18.42,6.91Z" }), mithril_1.default("path", { "d": "M18.42,16.31a5.7,5.7,0,1,1,5.76-5.7A5.74,5.74,0,0,1,18.42,16.31Zm0-9.4a3.7,3.7,0,1,0,3.76,3.7A3.74,3.74,0,0,0,18.42,6.91Z" }), mithril_1.default("path", { "d": "M21.91,17.65a20.6,20.6,0,0,0-13,2A1.77,1.77,0,0,0,8,21.25v3.56a1,1,0,0,0,2,0V21.38a18.92,18.92,0,0,1,12-1.68Z" }), mithril_1.default("path", { "d": "M33,22H26.3V20.52a1,1,0,0,0-2,0V22H17a1,1,0,0,0-1,1V33a1,1,0,0,0,1,1H33a1,1,0,0,0,1-1V23A1,1,0,0,0,33,22ZM32,32H18V24h6.3v.41a1,1,0,0,0,2,0V24H32Z" }), mithril_1.default("rect", { "x": 21.81, "y": 27.42, "width": 5.96, "height": 1.4 }), mithril_1.default("path", { "d": "M10.84,12.24a18,18,0,0,0-7.95,2A1.67,1.67,0,0,0,2,15.71v3.1a1,1,0,0,0,2,0v-2.9a16,16,0,0,1,7.58-1.67A7.28,7.28,0,0,1,10.84,12.24Z" }), mithril_1.default("path", { "d": "M33.11,14.23a17.8,17.8,0,0,0-7.12-2,7.46,7.46,0,0,1-.73,2A15.89,15.89,0,0,1,32,15.91v2.9a1,1,0,1,0,2,0v-3.1A1.67,1.67,0,0,0,33.11,14.23Z" }), mithril_1.default("path", { "d": "M10.66,10.61c0-.23,0-.45,0-.67a3.07,3.07,0,0,1,.54-6.11,3.15,3.15,0,0,1,2.2.89,8.16,8.16,0,0,1,1.7-1.08,5.13,5.13,0,0,0-9,3.27,5.1,5.1,0,0,0,4.7,5A7.42,7.42,0,0,1,10.66,10.61Z" }), mithril_1.default("path", { "d": "M24.77,1.83a5.17,5.17,0,0,0-3.69,1.55,7.87,7.87,0,0,1,1.9,1,3.14,3.14,0,0,1,4.93,2.52,3.09,3.09,0,0,1-1.79,2.77,7.14,7.14,0,0,1,.06.93,7.88,7.88,0,0,1-.1,1.2,5.1,5.1,0,0,0,3.83-4.9A5.12,5.12,0,0,0,24.77,1.83Z" }))); } }; exports.default = EmployeeGroupLine;
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["rrule"] = factory(); else root["rrule"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (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 = 1); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return isPresent; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return isNumber; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return isArray; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "j", function() { return range; }); /* unused harmony export clone */ /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "k", function() { return repeat; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "m", function() { return toArray; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "h", function() { return padStart; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "l", function() { return split; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "i", function() { return pymod; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return divmod; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return empty; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "g", function() { return notEmpty; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return includes; }); // ============================================================================= // Helper functions // ============================================================================= var isPresent = function (value) { return value !== null && value !== undefined; }; var isNumber = function (value) { return typeof value === 'number'; }; var isArray = Array.isArray; /** * Simplified version of python's range() */ var range = function (start, end) { if (end === void 0) { end = start; } if (arguments.length === 1) { end = start; start = 0; } var rang = []; for (var i = start; i < end; i++) rang.push(i); return rang; }; var clone = function (array) { return [].concat(array); }; var repeat = function (value, times) { var i = 0; var array = []; if (isArray(value)) { for (; i < times; i++) array[i] = [].concat(value); } else { for (; i < times; i++) array[i] = value; } return array; }; var toArray = function (item) { if (isArray(item)) { return item; } return [item]; }; function padStart(item, targetLength, padString) { if (padString === void 0) { padString = ' '; } var str = String(item); targetLength = targetLength >> 0; if (str.length > targetLength) { return String(str); } targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += repeat(padString, targetLength / padString.length); } return padString.slice(0, targetLength) + String(str); } /** * Python like split */ var split = function (str, sep, num) { var splits = str.split(sep); return num ? splits.slice(0, num).concat([splits.slice(num).join(sep)]) : splits; }; /** * closure/goog/math/math.js:modulo * Copyright 2006 The Closure Library Authors. * The % operator in JavaScript returns the remainder of a / b, but differs from * some other languages in that the result will have the same sign as the * dividend. For example, -1 % 8 == -1, whereas in some other languages * (such as Python) the result would be 7. This function emulates the more * correct modulo behavior, which is useful for certain applications such as * calculating an offset index in a circular list. * * @param {number} a The dividend. * @param {number} b The divisor. * @return {number} a % b where the result is between 0 and b (either 0 <= x < b * or b < x <= 0, depending on the sign of b). */ var pymod = function (a, b) { var r = a % b; // If r and b differ in sign, add b to wrap the result to the correct sign. return r * b < 0 ? r + b : r; }; /** * @see: <http://docs.python.org/library/functions.html#divmod> */ var divmod = function (a, b) { return { div: Math.floor(a / b), mod: pymod(a, b) }; }; var empty = function (obj) { return !isPresent(obj) || obj.length === 0; }; /** * Python-like boolean * @return {Boolean} value of an object/primitive, taking into account * the fact that in Python an empty list's/tuple's * boolean value is False, whereas in JS it's true */ var notEmpty = function (obj) { return !empty(obj); }; /** * Return true if a value is in an array */ var includes = function (arr, val) { return notEmpty(arr) && arr.indexOf(val) !== -1; }; /***/ }), /* 1 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: ./src/helpers.ts var helpers = __webpack_require__(0); // CONCATENATED MODULE: ./src/dateutil.ts /** * General date-related utilities. * Also handles several incompatibilities between JavaScript and Python * */ var dateutil_dateutil; (function (dateutil) { dateutil.MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; /** * Number of milliseconds of one day */ dateutil.ONE_DAY = 1000 * 60 * 60 * 24; /** * @see: <http://docs.python.org/library/datetime.html#datetime.MAXYEAR> */ dateutil.MAXYEAR = 9999; /** * Python uses 1-Jan-1 as the base for calculating ordinals but we don't * want to confuse the JS engine with milliseconds > Number.MAX_NUMBER, * therefore we use 1-Jan-1970 instead */ dateutil.ORDINAL_BASE = new Date(Date.UTC(1970, 0, 1)); /** * Python: MO-SU: 0 - 6 * JS: SU-SAT 0 - 6 */ dateutil.PY_WEEKDAYS = [6, 0, 1, 2, 3, 4, 5]; /** * py_date.timetuple()[7] */ dateutil.getYearDay = function (date) { var dateNoTime = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()); return (Math.ceil((dateNoTime.valueOf() - new Date(date.getUTCFullYear(), 0, 1).valueOf()) / dateutil.ONE_DAY) + 1); }; dateutil.isLeapYear = function (year) { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; }; dateutil.isDate = function (value) { return value instanceof Date; }; dateutil.isValidDate = function (value) { return dateutil.isDate(value) && !isNaN(value.getTime()); }; /** * @return {Number} the date's timezone offset in ms */ dateutil.tzOffset = function (date) { return date.getTimezoneOffset() * 60 * 1000; }; /** * @see: <http://www.mcfedries.com/JavaScript/DaysBetween.asp> */ dateutil.daysBetween = function (date1, date2) { // The number of milliseconds in one day // Convert both dates to milliseconds var date1ms = date1.getTime() - dateutil.tzOffset(date1); var date2ms = date2.getTime() - dateutil.tzOffset(date2); // Calculate the difference in milliseconds var differencems = date1ms - date2ms; // Convert back to days and return return Math.round(differencems / dateutil.ONE_DAY); }; /** * @see: <http://docs.python.org/library/datetime.html#datetime.date.toordinal> */ dateutil.toOrdinal = function (date) { return dateutil.daysBetween(date, dateutil.ORDINAL_BASE); }; /** * @see - <http://docs.python.org/library/datetime.html#datetime.date.fromordinal> */ dateutil.fromOrdinal = function (ordinal) { return new Date(dateutil.ORDINAL_BASE.getTime() + ordinal * dateutil.ONE_DAY); }; dateutil.getMonthDays = function (date) { var month = date.getUTCMonth(); return month === 1 && dateutil.isLeapYear(date.getUTCFullYear()) ? 29 : dateutil.MONTH_DAYS[month]; }; /** * @return {Number} python-like weekday */ dateutil.getWeekday = function (date) { return dateutil.PY_WEEKDAYS[date.getUTCDay()]; }; /** * @see: <http://docs.python.org/library/calendar.html#calendar.monthrange> */ dateutil.monthRange = function (year, month) { var date = new Date(Date.UTC(year, month, 1)); return [dateutil.getWeekday(date), dateutil.getMonthDays(date)]; }; /** * @see: <http://docs.python.org/library/datetime.html#datetime.datetime.combine> */ dateutil.combine = function (date, time) { time = time || date; return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), time.getHours(), time.getMinutes(), time.getSeconds(), time.getMilliseconds())); }; dateutil.clone = function (date) { var dolly = new Date(date.getTime()); return dolly; }; dateutil.cloneDates = function (dates) { var clones = []; for (var i = 0; i < dates.length; i++) { clones.push(dateutil.clone(dates[i])); } return clones; }; /** * Sorts an array of Date or dateutil.Time objects */ dateutil.sort = function (dates) { dates.sort(function (a, b) { return a.getTime() - b.getTime(); }); }; dateutil.timeToUntilString = function (time, utc) { if (utc === void 0) { utc = true; } var date = new Date(time); return [ Object(helpers["h" /* padStart */])(date.getUTCFullYear().toString(), 4, '0'), Object(helpers["h" /* padStart */])(date.getUTCMonth() + 1, 2, '0'), Object(helpers["h" /* padStart */])(date.getUTCDate(), 2, '0'), 'T', Object(helpers["h" /* padStart */])(date.getUTCHours(), 2, '0'), Object(helpers["h" /* padStart */])(date.getUTCMinutes(), 2, '0'), Object(helpers["h" /* padStart */])(date.getUTCSeconds(), 2, '0'), utc ? 'Z' : '' ].join(''); }; dateutil.untilStringToDate = function (until) { var re = /^(\d{4})(\d{2})(\d{2})(T(\d{2})(\d{2})(\d{2})Z?)?$/; var bits = re.exec(until); if (!bits) throw new Error("Invalid UNTIL value: " + until); return new Date(Date.UTC(parseInt(bits[1], 10), parseInt(bits[2], 10) - 1, parseInt(bits[3], 10), parseInt(bits[5], 10) || 0, parseInt(bits[6], 10) || 0, parseInt(bits[7], 10) || 0)); }; })(dateutil_dateutil || (dateutil_dateutil = {})); /* harmony default export */ var src_dateutil = (dateutil_dateutil); // CONCATENATED MODULE: ./src/iterresult.ts /** * This class helps us to emulate python's generators, sorta. */ var IterResult = /** @class */ (function () { function IterResult(method, args) { this.minDate = null; this.maxDate = null; this._result = []; this.total = 0; this.method = method; this.args = args; if (method === 'between') { this.maxDate = args.inc ? args.before : new Date(args.before.getTime() - 1); this.minDate = args.inc ? args.after : new Date(args.after.getTime() + 1); } else if (method === 'before') { this.maxDate = args.inc ? args.dt : new Date(args.dt.getTime() - 1); } else if (method === 'after') { this.minDate = args.inc ? args.dt : new Date(args.dt.getTime() + 1); } } /** * Possibly adds a date into the result. * * @param {Date} date - the date isn't necessarly added to the result * list (if it is too late/too early) * @return {Boolean} true if it makes sense to continue the iteration * false if we're done. */ IterResult.prototype.accept = function (date) { ++this.total; var tooEarly = this.minDate && date < this.minDate; var tooLate = this.maxDate && date > this.maxDate; if (this.method === 'between') { if (tooEarly) return true; if (tooLate) return false; } else if (this.method === 'before') { if (tooLate) return false; } else if (this.method === 'after') { if (tooEarly) return true; this.add(date); return false; } return this.add(date); }; /** * * @param {Date} date that is part of the result. * @return {Boolean} whether we are interested in more values. */ IterResult.prototype.add = function (date) { this._result.push(date); return true; }; /** * 'before' and 'after' return only one date, whereas 'all' * and 'between' an array. * @return {Date,Array?} */ IterResult.prototype.getValue = function () { var res = this._result; switch (this.method) { case 'all': case 'between': return res; case 'before': case 'after': default: return (res.length ? res[res.length - 1] : null); } }; IterResult.prototype.clone = function () { return new IterResult(this.method, this.args); }; return IterResult; }()); /* harmony default export */ var iterresult = (IterResult); // CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js /*! ***************************************************************************** Copyright (c) Microsoft Corporation. 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 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { 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 extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; } return __assign.apply(this, arguments); } function __rest(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]]; return t; } function __decorate(decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; } function __param(paramIndex, decorator) { return function (target, key) { decorator(target, key, paramIndex); } } function __metadata(metadataKey, metadataValue) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } function __exportStar(m, exports) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } function __await(v) { return this instanceof __await ? (this.v = v, this) : new __await(v); } function __asyncGenerator(thisArg, _arguments, generator) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var g = generator.apply(thisArg, _arguments || []), i, q = []; return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } function fulfill(value) { resume("next", value); } function reject(value) { resume("throw", value); } function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } } function __asyncDelegator(o) { var i, p; return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } } function __asyncValues(o) { if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); var m = o[Symbol.asyncIterator], i; return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } } function __makeTemplateObject(cooked, raw) { if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } return cooked; }; function __importStar(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; result.default = mod; return result; } function __importDefault(mod) { return (mod && mod.__esModule) ? mod : { default: mod }; } // CONCATENATED MODULE: ./src/callbackiterresult.ts /** * IterResult subclass that calls a callback function on each add, * and stops iterating when the callback returns false. */ var callbackiterresult_CallbackIterResult = /** @class */ (function (_super) { __extends(CallbackIterResult, _super); function CallbackIterResult(method, args, iterator) { var _this = _super.call(this, method, args) || this; _this.iterator = iterator; return _this; } CallbackIterResult.prototype.add = function (date) { if (this.iterator(date, this._result.length)) { this._result.push(date); return true; } return false; }; return CallbackIterResult; }(iterresult)); /* harmony default export */ var callbackiterresult = (callbackiterresult_CallbackIterResult); // CONCATENATED MODULE: ./src/types.ts var Frequency; (function (Frequency) { Frequency[Frequency["YEARLY"] = 0] = "YEARLY"; Frequency[Frequency["MONTHLY"] = 1] = "MONTHLY"; Frequency[Frequency["WEEKLY"] = 2] = "WEEKLY"; Frequency[Frequency["DAILY"] = 3] = "DAILY"; Frequency[Frequency["HOURLY"] = 4] = "HOURLY"; Frequency[Frequency["MINUTELY"] = 5] = "MINUTELY"; Frequency[Frequency["SECONDLY"] = 6] = "SECONDLY"; })(Frequency || (Frequency = {})); function freqIsDailyOrGreater(freq) { return freq < Frequency.HOURLY; } // CONCATENATED MODULE: ./src/weekday.ts // ============================================================================= // Weekday // ============================================================================= var WDAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU']; var Weekday = /** @class */ (function () { function Weekday(weekday, n) { if (n === 0) throw new Error("Can't create weekday with n == 0"); this.weekday = weekday; this.n = n; } // __call__ - Cannot call the object directly, do it through // e.g. RRule.TH.nth(-1) instead, Weekday.prototype.nth = function (n) { return this.n === n ? this : new Weekday(this.weekday, n); }; // __eq__ Weekday.prototype.equals = function (other) { return this.weekday === other.weekday && this.n === other.n; }; // __repr__ Weekday.prototype.toString = function () { var s = WDAYS[this.weekday]; if (this.n) s = (this.n > 0 ? '+' : '') + String(this.n) + s; return s; }; Weekday.prototype.getJsWeekday = function () { return this.weekday === 6 ? 0 : this.weekday + 1; }; return Weekday; }()); // CONCATENATED MODULE: ./src/datetime.ts var Time = /** @class */ (function () { function Time(hour, minute, second, millisecond) { this.hour = hour; this.minute = minute; this.second = second; this.millisecond = millisecond || 0; } Time.prototype.getHours = function () { return this.hour; }; Time.prototype.getMinutes = function () { return this.minute; }; Time.prototype.getSeconds = function () { return this.second; }; Time.prototype.getMilliseconds = function () { return this.millisecond; }; Time.prototype.getTime = function () { return ((this.hour * 60 * 60 + this.minute * 60 + this.second) * 1000 + this.millisecond); }; return Time; }()); var datetime_DateTime = /** @class */ (function (_super) { __extends(DateTime, _super); function DateTime(year, month, day, hour, minute, second, millisecond) { var _this = _super.call(this, hour, minute, second, millisecond) || this; _this.year = year; _this.month = month; _this.day = day; return _this; } DateTime.fromDate = function (date) { return new this(date.getUTCFullYear(), date.getUTCMonth() + 1, date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds(), date.valueOf() % 1000); }; DateTime.prototype.getWeekday = function () { return dateutil_dateutil.getWeekday(new Date(this.getTime())); }; DateTime.prototype.getTime = function () { return new Date(Date.UTC(this.year, this.month - 1, this.day, this.hour, this.minute, this.second, this.millisecond)).getTime(); }; DateTime.prototype.getDay = function () { return this.day; }; DateTime.prototype.getMonth = function () { return this.month; }; DateTime.prototype.getYear = function () { return this.year; }; DateTime.prototype.addYears = function (years) { this.year += years; }; DateTime.prototype.addMonths = function (months) { this.month += months; if (this.month > 12) { var yearDiv = Math.floor(this.month / 12); var monthMod = Object(helpers["i" /* pymod */])(this.month, 12); this.month = monthMod; this.year += yearDiv; if (this.month === 0) { this.month = 12; --this.year; } } }; DateTime.prototype.addWeekly = function (days, wkst) { if (wkst > this.getWeekday()) { this.day += -(this.getWeekday() + 1 + (6 - wkst)) + days * 7; } else { this.day += -(this.getWeekday() - wkst) + days * 7; } this.fixDay(); }; DateTime.prototype.addDaily = function (days) { this.day += days; this.fixDay(); }; DateTime.prototype.addHours = function (hours, filtered, byhour) { if (filtered) { // Jump to one iteration before next day this.hour += Math.floor((23 - this.hour) / hours) * hours; } while (true) { this.hour += hours; var _a = Object(helpers["a" /* divmod */])(this.hour, 24), dayDiv = _a.div, hourMod = _a.mod; if (dayDiv) { this.hour = hourMod; this.addDaily(dayDiv); } if (Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour)) break; } }; DateTime.prototype.addMinutes = function (minutes, filtered, byhour, byminute) { if (filtered) { // Jump to one iteration before next day this.minute += Math.floor((1439 - (this.hour * 60 + this.minute)) / minutes) * minutes; } while (true) { this.minute += minutes; var _a = Object(helpers["a" /* divmod */])(this.minute, 60), hourDiv = _a.div, minuteMod = _a.mod; if (hourDiv) { this.minute = minuteMod; this.addHours(hourDiv, false, byhour); } if ((Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour)) && (Object(helpers["b" /* empty */])(byminute) || Object(helpers["c" /* includes */])(byminute, this.minute))) { break; } } }; DateTime.prototype.addSeconds = function (seconds, filtered, byhour, byminute, bysecond) { if (filtered) { // Jump to one iteration before next day this.second += Math.floor((86399 - (this.hour * 3600 + this.minute * 60 + this.second)) / seconds) * seconds; } while (true) { this.second += seconds; var _a = Object(helpers["a" /* divmod */])(this.second, 60), minuteDiv = _a.div, secondMod = _a.mod; if (minuteDiv) { this.second = secondMod; this.addMinutes(minuteDiv, false, byhour, byminute); } if ((Object(helpers["b" /* empty */])(byhour) || Object(helpers["c" /* includes */])(byhour, this.hour)) && (Object(helpers["b" /* empty */])(byminute) || Object(helpers["c" /* includes */])(byminute, this.minute)) && (Object(helpers["b" /* empty */])(bysecond) || Object(helpers["c" /* includes */])(bysecond, this.second))) { break; } } }; DateTime.prototype.fixDay = function () { if (this.day <= 28) { return; } var daysinmonth = dateutil_dateutil.monthRange(this.year, this.month - 1)[1]; if (this.day <= daysinmonth) { return; } while (this.day > daysinmonth) { this.day -= daysinmonth; ++this.month; if (this.month === 13) { this.month = 1; ++this.year; if (this.year > dateutil_dateutil.MAXYEAR) { return; } } daysinmonth = dateutil_dateutil.monthRange(this.year, this.month - 1)[1]; } }; DateTime.prototype.add = function (options, filtered) { var freq = options.freq, interval = options.interval, wkst = options.wkst, byhour = options.byhour, byminute = options.byminute, bysecond = options.bysecond; switch (freq) { case Frequency.YEARLY: return this.addYears(interval); case Frequency.MONTHLY: return this.addMonths(interval); case Frequency.WEEKLY: return this.addWeekly(interval, wkst); case Frequency.DAILY: return this.addDaily(interval); case Frequency.HOURLY: return this.addHours(interval, filtered, byhour); case Frequency.MINUTELY: return this.addMinutes(interval, filtered, byhour, byminute); case Frequency.SECONDLY: return this.addSeconds(interval, filtered, byhour, byminute, bysecond); } }; return DateTime; }(Time)); // CONCATENATED MODULE: ./src/parseoptions.ts function initializeOptions(options) { var invalid = []; var keys = Object.keys(options); var initializedOptions = {}; // Shallow copy for options and origOptions and check for invalid keys.forEach(function (key) { var value = options[key]; initializedOptions[key] = value; if (!Object(helpers["c" /* includes */])(rrule_defaultKeys, key)) invalid.push(key); if (src_dateutil.isDate(value) && !src_dateutil.isValidDate(value)) invalid.push(key); }); if (invalid.length) { throw new Error('Invalid options: ' + invalid.join(', ')); } return initializedOptions; } function parseOptions(options) { var opts = initializeOptions(options); var keys = Object.keys(options); // Merge in default options rrule_defaultKeys.forEach(function (key) { if (!Object(helpers["c" /* includes */])(keys, key) || !Object(helpers["f" /* isPresent */])(opts[key])) opts[key] = DEFAULT_OPTIONS[key]; }); if (Object(helpers["f" /* isPresent */])(opts.byeaster)) opts.freq = src_rrule.YEARLY; if (!(Object(helpers["f" /* isPresent */])(opts.freq) && src_rrule.FREQUENCIES[opts.freq])) { throw new Error("Invalid frequency: " + opts.freq + " " + options.freq); } if (!opts.dtstart) opts.dtstart = new Date(new Date().setMilliseconds(0)); if (!Object(helpers["f" /* isPresent */])(opts.wkst)) { opts.wkst = src_rrule.MO.weekday; } else if (Object(helpers["e" /* isNumber */])(opts.wkst)) { // cool, just keep it like that } else { opts.wkst = opts.wkst.weekday; } if (Object(helpers["f" /* isPresent */])(opts.bysetpos)) { if (Object(helpers["e" /* isNumber */])(opts.bysetpos)) opts.bysetpos = [opts.bysetpos]; for (var i = 0; i < opts.bysetpos.length; i++) { var v = opts.bysetpos[i]; if (v === 0 || !(v >= -366 && v <= 366)) { throw new Error('bysetpos must be between 1 and 366,' + ' or between -366 and -1'); } } } if (!(Boolean(opts.byweekno) || Object(helpers["g" /* notEmpty */])(opts.byweekno) || Object(helpers["g" /* notEmpty */])(opts.byyearday) || Boolean(opts.bymonthday) || Object(helpers["g" /* notEmpty */])(opts.bymonthday) || Object(helpers["f" /* isPresent */])(opts.byweekday) || Object(helpers["f" /* isPresent */])(opts.byeaster))) { switch (opts.freq) { case src_rrule.YEARLY: if (!opts.bymonth) opts.bymonth = opts.dtstart.getUTCMonth() + 1; opts.bymonthday = opts.dtstart.getUTCDate(); break; case src_rrule.MONTHLY: opts.bymonthday = opts.dtstart.getUTCDate(); break; case src_rrule.WEEKLY: opts.byweekday = [src_dateutil.getWeekday(opts.dtstart)]; break; } } // bymonth if (Object(helpers["f" /* isPresent */])(opts.bymonth) && !Object(helpers["d" /* isArray */])(opts.bymonth)) { opts.bymonth = [opts.bymonth]; } // byyearday if (Object(helpers["f" /* isPresent */])(opts.byyearday) && !Object(helpers["d" /* isArray */])(opts.byyearday) && Object(helpers["e" /* isNumber */])(opts.byyearday)) { opts.byyearday = [opts.byyearday]; } // bymonthday if (!Object(helpers["f" /* isPresent */])(opts.bymonthday)) { opts.bymonthday = []; opts.bynmonthday = []; } else if (Object(helpers["d" /* isArray */])(opts.bymonthday)) { var bymonthday = []; var bynmonthday = []; for (var i = 0; i < opts.bymonthday.length; i++) { var v = opts.bymonthday[i]; if (v > 0) { bymonthday.push(v); } else if (v < 0) { bynmonthday.push(v); } } opts.bymonthday = bymonthday; opts.bynmonthday = bynmonthday; } else if (opts.bymonthday < 0) { opts.bynmonthday = [opts.bymonthday]; opts.bymonthday = []; } else { opts.bynmonthday = []; opts.bymonthday = [opts.bymonthday]; } // byweekno if (Object(helpers["f" /* isPresent */])(opts.byweekno) && !Object(helpers["d" /* isArray */])(opts.byweekno)) { opts.byweekno = [opts.byweekno]; } // byweekday / bynweekday if (!Object(helpers["f" /* isPresent */])(opts.byweekday)) { opts.bynweekday = null; } else if (Object(helpers["e" /* isNumber */])(opts.byweekday)) { opts.byweekday = [opts.byweekday]; opts.bynweekday = null; } else if (opts.byweekday instanceof Weekday) { if (!opts.byweekday.n || opts.freq > src_rrule.MONTHLY) { opts.byweekday = [opts.byweekday.weekday]; opts.bynweekday = null; } else { opts.bynweekday = [[opts.byweekday.weekday, opts.byweekday.n]]; opts.byweekday = null; } } else { var byweekday = []; var bynweekday = []; for (var i = 0; i < opts.byweekday.length; i++) { var wday = opts.byweekday[i]; if (Object(helpers["e" /* isNumber */])(wday)) { byweekday.push(wday); continue; } var wd = wday; if (!wd.n || opts.freq > src_rrule.MONTHLY) { byweekday.push(wd.weekday); } else { bynweekday.push([wd.weekday, wd.n]); } } opts.byweekday = Object(helpers["g" /* notEmpty */])(byweekday) ? byweekday : null; opts.bynweekday = Object(helpers["g" /* notEmpty */])(bynweekday) ? bynweekday : null; } // byhour if (!Object(helpers["f" /* isPresent */])(opts.byhour)) { opts.byhour = opts.freq < src_rrule.HOURLY ? [opts.dtstart.getUTCHours()] : null; } else if (Object(helpers["e" /* isNumber */])(opts.byhour)) { opts.byhour = [opts.byhour]; } // byminute if (!Object(helpers["f" /* isPresent */])(opts.byminute)) { opts.byminute = opts.freq < src_rrule.MINUTELY ? [opts.dtstart.getUTCMinutes()] : null; } else if (Object(helpers["e" /* isNumber */])(opts.byminute)) { opts.byminute = [opts.byminute]; } // bysecond if (!Object(helpers["f" /* isPresent */])(opts.bysecond)) { opts.bysecond = opts.freq < src_rrule.SECONDLY ? [opts.dtstart.getUTCSeconds()] : null; } else if (Object(helpers["e" /* isNumber */])(opts.bysecond)) { opts.bysecond = [opts.bysecond]; } return { parsedOptions: opts }; } function buildTimeset(opts) { var millisecondModulo = opts.dtstart.getTime() % 1000; if (!freqIsDailyOrGreater(opts.freq)) { return []; } var timeset = []; opts.byhour.forEach(function (hour) { opts.byminute.forEach(function (minute) { opts.bysecond.forEach(function (second) { timeset.push(new Time(hour, minute, second, millisecondModulo)); }); }); }); return timeset; } // CONCATENATED MODULE: ./src/parsestring.ts function parseString(rfcString) { var options = rfcString.split('\n').map(parseLine).filter(function (x) { return x !== null; }); return __assign({}, options[0], options[1]); } function parseDtstart(line) { var options = {}; var dtstartWithZone = /DTSTART(?:;TZID=([^:=]+?))?(?::|=)([^;\s]+)/i.exec(line); if (!dtstartWithZone) { return options; } var _ = dtstartWithZone[0], tzid = dtstartWithZone[1], dtstart = dtstartWithZone[2]; if (tzid) { options.tzid = tzid; } options.dtstart = src_dateutil.untilStringToDate(dtstart); return options; } function parseLine(rfcString) { rfcString = rfcString.replace(/^\s+|\s+$/, ''); if (!rfcString.length) return null; var header = /^([A-Z]+?)[:;]/.exec(rfcString.toUpperCase()); if (!header) { return parseRrule(rfcString); } var _ = header[0], key = header[1]; switch (key.toUpperCase()) { case 'RRULE': case 'EXRULE': return parseRrule(rfcString); case 'DTSTART': return parseDtstart(rfcString); default: throw new Error("Unsupported RFC prop " + key + " in " + rfcString); } } function parseRrule(line) { var strippedLine = line.replace(/^RRULE:/i, ''); var options = parseDtstart(strippedLine); var attrs = line.replace(/^(?:RRULE|EXRULE):/i, '').split(';'); attrs.forEach(function (attr) { var _a = attr.split('='), key = _a[0], value = _a[1]; switch (key.toUpperCase()) { case 'FREQ': options.freq = Frequency[value.toUpperCase()]; break; case 'WKST': options.wkst = Days[value.toUpperCase()]; break; case 'COUNT': case 'INTERVAL': case 'BYSETPOS': case 'BYMONTH': case 'BYMONTHDAY': case 'BYYEARDAY': case 'BYWEEKNO': case 'BYHOUR': case 'BYMINUTE': case 'BYSECOND': var num = parseNumber(value); var optionKey = key.toLowerCase(); // @ts-ignore options[optionKey] = num; break; case 'BYWEEKDAY': case 'BYDAY': options.byweekday = parseWeekday(value); break; case 'DTSTART': case 'TZID': // for backwards compatibility var dtstart = parseDtstart(line); options.tzid = dtstart.tzid; options.dtstart = dtstart.dtstart; break; case 'UNTIL': options.until = src_dateutil.untilStringToDate(value); break; case 'BYEASTER': options.byeaster = Number(value); break; default: throw new Error("Unknown RRULE property '" + key + "'"); } }); return options; } function parseNumber(value) { if (value.indexOf(',') !== -1) { var values = value.split(','); return values.map(parseIndividualNumber); } return parseIndividualNumber(value); } function parseIndividualNumber(value) { if (/^[+-]?\d+$/.test(value)) { return Number(value); } return value; } function parseWeekday(value) { var days = value.split(','); return days.map(function (day) { if (day.length === 2) { // MO, TU, ... return Days[day]; // wday instanceof Weekday } // -1MO, +3FR, 1SO, 13TU ... var parts = day.match(/^([+-]?\d{1,2})([A-Z]{2})$/); var n = Number(parts[1]); var wdaypart = parts[2]; var wday = Days[wdaypart].weekday; return new Weekday(wday, n); }); } // EXTERNAL MODULE: ./node_modules/luxon/build/cjs-browser/luxon.js var luxon = __webpack_require__(2); // CONCATENATED MODULE: ./src/datewithzone.ts var datewithzone_DateWithZone = /** @class */ (function () { function DateWithZone(date, tzid) { this.date = date; this.tzid = tzid; } Object.defineProperty(DateWithZone.prototype, "isUTC", { get: function () { return !this.tzid || this.tzid.toUpperCase() === 'UTC'; }, enumerable: true, configurable: true }); DateWithZone.prototype.toString = function () { var datestr = src_dateutil.timeToUntilString(this.date.getTime(), this.isUTC); if (!this.isUTC) { return ";TZID=" + this.tzid + ":" + datestr; } return ":" + datestr; }; DateWithZone.prototype.getTime = function () { return this.date.getTime(); }; DateWithZone.prototype.rezonedDate = function () { if (this.isUTC) { return this.date; } try { var datetime = luxon["DateTime"] .fromJSDate(this.date); var rezoned = datetime.setZone(this.tzid, { keepLocalTime: true }); return rezoned.toJSDate(); } catch (e) { if (e instanceof TypeError) { console.error('Using TZID without Luxon available is unsupported. Returned times are in UTC, not the requested time zone'); } return this.date; } }; return DateWithZone; }()); // CONCATENATED MODULE: ./src/optionstostring.ts function optionsToString(options) { var rrule = []; var dtstart = ''; var keys = Object.keys(options); var defaultKeys = Object.keys(DEFAULT_OPTIONS); for (var i = 0; i < keys.length; i++) { if (keys[i] === 'tzid') continue; if (!Object(helpers["c" /* includes */])(defaultKeys, keys[i])) continue; var key = keys[i].toUpperCase(); var value = options[keys[i]]; var outValue = ''; if (!Object(helpers["f" /* isPresent */])(value) || (Object(helpers["d" /* isArray */])(value) && !value.length)) continue; switch (key) { case 'FREQ': outValue = src_rrule.FREQUENCIES[options.freq]; break; case 'WKST': if (Object(helpers["e" /* isNumber */])(value)) { outValue = new Weekday(value).toString(); } else { outValue = value.toString(); } break; case 'BYWEEKDAY': /* NOTE: BYWEEKDAY is a special case. RRule() deconstructs the rule.options.byweekday array into an array of Weekday arguments. On the other hand, rule.origOptions is an array of Weekdays. We need to handle both cases here. It might be worth change RRule to keep the Weekdays. Also, BYWEEKDAY (used by RRule) vs. BYDAY (RFC) */ key = 'BYDAY'; outValue = Object(helpers["m" /* toArray */])(value).map(function (wday) { if (wday instanceof Weekday) { return wday; } if (Object(helpers["d" /* isArray */])(wday)) { return new Weekday(wday[0], wday[1]); } return new Weekday(wday); }).toString(); break; case 'DTSTART': dtstart = buildDtstart(value, options.tzid); break; case 'UNTIL': outValue = src_dateutil.timeToUntilString(value, !options.tzid); break; default: if (Object(helpers["d" /* isArray */])(value)) { var strValues = []; for (var j = 0; j < value.length; j++) { strValues[j] = String(value[j]); } outValue = strValues.toString(); } else { outValue = String(value); } } if (outValue) { rrule.push([key, outValue]); } } var rules = rrule.map(function (_a) { var key = _a[0], value = _a[1]; return key + "=" + value.toString(); }).join(';'); var ruleString = ''; if (rules !== '') { ruleString = "RRULE:" + rules; } return [dtstart, ruleString].filter(function (x) { return !!x; }).join('\n'); } function buildDtstart(dtstart, tzid) { if (!dtstart) { return ''; } return 'DTSTART' + new datewithzone_DateWithZone(new Date(dtstart), tzid).toString(); } // CONCATENATED MODULE: ./src/cache.ts var cache_Cache = /** @class */ (function () { function Cache() { this.all = false; this.before = []; this.after = []; this.between = []; } /** * @param {String} what - all/before/after/between * @param {Array,Date} value - an array of dates, one date, or null * @param {Object?} args - _iter arguments */ Cache.prototype._cacheAdd = function (what, value, args) { if (value) { value = value instanceof Date ? src_dateutil.clone(value) : src_dateutil.cloneDates(value); } if (what === 'all') { this.all = value; } else { args._value = value; this[what].push(args); } }; /** * @return false - not in the cache * null - cached, but zero occurrences (before/after) * Date - cached (before/after) * [] - cached, but zero occurrences (all/between) * [Date1, DateN] - cached (all/between) */ Cache.prototype._cacheGet = function (what, args) { var cached = false; var argsKeys = args ? Object.keys(args) : []; var findCacheDiff = function (item) { for (var i = 0; i < argsKeys.length; i++) { var key = argsKeys[i]; if (String(args[key]) !== String(item[key])) { return true; } } return false; }; var cachedObject = this[what]; if (what === 'all') { cached = this.all; } else if (Object(helpers["d" /* isArray */])(cachedObject)) { // Let's see whether we've already called the // 'what' method with the same 'args' for (var i = 0; i < cachedObject.length; i++) { var item = cachedObject[i]; if (argsKeys.length && findCacheDiff(item)) continue; cached = item._value; break; } } if (!cached && this.all) { // Not in the cache, but we already know all the occurrences, // so we can find the correct dates from the cached ones. var iterResult = new iterresult(what, args); for (var i = 0; i < this.all.length; i++) { if (!iterResult.accept(this.all[i])) break; } cached = iterResult.getValue(); this._cacheAdd(what, cached, args); } return Object(helpers["d" /* isArray */])(cached) ? src_dateutil.cloneDates(cached) : cached instanceof Date ? src_dateutil.clone(cached) : cached; }; return Cache; }()); // CONCATENATED MODULE: ./src/masks.ts // ============================================================================= // Date masks // ============================================================================= // Every mask is 7 days longer to handle cross-year weekly periods. var M365MASK = Object(helpers["k" /* repeat */])(1, 31).concat(Object(helpers["k" /* repeat */])(2, 28), Object(helpers["k" /* repeat */])(3, 31), Object(helpers["k" /* repeat */])(4, 30), Object(helpers["k" /* repeat */])(5, 31), Object(helpers["k" /* repeat */])(6, 30), Object(helpers["k" /* repeat */])(7, 31), Object(helpers["k" /* repeat */])(8, 31), Object(helpers["k" /* repeat */])(9, 30), Object(helpers["k" /* repeat */])(10, 31), Object(helpers["k" /* repeat */])(11, 30), Object(helpers["k" /* repeat */])(12, 31), Object(helpers["k" /* repeat */])(1, 7)); var M366MASK = Object(helpers["k" /* repeat */])(1, 31).concat(Object(helpers["k" /* repeat */])(2, 29), Object(helpers["k" /* repeat */])(3, 31), Object(helpers["k" /* repeat */])(4, 30), Object(helpers["k" /* repeat */])(5, 31), Object(helpers["k" /* repeat */])(6, 30), Object(helpers["k" /* repeat */])(7, 31), Object(helpers["k" /* repeat */])(8, 31), Object(helpers["k" /* repeat */])(9, 30), Object(helpers["k" /* repeat */])(10, 31), Object(helpers["k" /* repeat */])(11, 30), Object(helpers["k" /* repeat */])(12, 31), Object(helpers["k" /* repeat */])(1, 7)); var M28 = Object(helpers["j" /* range */])(1, 29); var M29 = Object(helpers["j" /* range */])(1, 30); var M30 = Object(helpers["j" /* range */])(1, 31); var M31 = Object(helpers["j" /* range */])(1, 32); var MDAY366MASK = M31.concat(M29, M31, M30, M31, M30, M31, M31, M30, M31, M30, M31, M31.slice(0, 7)); var MDAY365MASK = M31.concat(M28, M31, M30, M31, M30, M31, M31, M30, M31, M30, M31, M31.slice(0, 7)); var NM28 = Object(helpers["j" /* range */])(-28, 0); var NM29 = Object(helpers["j" /* range */])(-29, 0); var NM30 = Object(helpers["j" /* range */])(-30, 0); var NM31 = Object(helpers["j" /* range */])(-31, 0); var NMDAY366MASK = NM31.concat(NM29, NM31, NM30, NM31, NM30, NM31, NM31, NM30, NM31, NM30, NM31, NM31.slice(0, 7)); var NMDAY365MASK = NM31.concat(NM28, NM31, NM30, NM31, NM30, NM31, NM31, NM30, NM31, NM30, NM31, NM31.slice(0, 7)); var M366RANGE = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366]; var M365RANGE = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365]; var WDAYMASK = (function () { var wdaymask = []; for (var i = 0; i < 55; i++) wdaymask = wdaymask.concat(Object(helpers["j" /* range */])(7)); return wdaymask; })(); // CONCATENATED MODULE: ./src/iterinfo/yearinfo.ts function rebuildYear(year, options) { var firstyday = new Date(Date.UTC(year, 0, 1)); var yearlen = src_dateutil.isLeapYear(year) ? 366 : 365; var nextyearlen = src_dateutil.isLeapYear(year + 1) ? 366 : 365; var yearordinal = src_dateutil.toOrdinal(firstyday); var yearweekday = src_dateutil.getWeekday(firstyday); var result = __assign({ yearlen: yearlen, nextyearlen: nextyearlen, yearordinal: yearordinal, yearweekday: yearweekday }, baseYearMasks(year), { wnomask: null }); if (Object(helpers["b" /* empty */])(options.byweekno)) { return result; } result.wnomask = Object(helpers["k" /* repeat */])(0, yearlen + 7); var firstwkst; var wyearlen; var no1wkst = firstwkst = Object(helpers["i" /* pymod */])(7 - yearweekday + options.wkst, 7); if (no1wkst >= 4) { no1wkst = 0; // Number of days in the year, plus the days we got // from last year. wyearlen = result.yearlen + Object(helpers["i" /* pymod */])(yearweekday - options.wkst, 7); } else { // Number of days in the year, minus the days we // left in last year. wyearlen = yearlen - no1wkst; } var div = Math.floor(wyearlen / 7); var mod = Object(helpers["i" /* pymod */])(wyearlen, 7); var numweeks = Math.floor(div + mod / 4); for (var j = 0; j < options.byweekno.length; j++) { var n = options.byweekno[j]; if (n < 0) { n += numweeks + 1; } if (!(n > 0 && n <= numweeks)) { continue; } var i = void 0; if (n > 1) { i = no1wkst + (n - 1) * 7; if (no1wkst !== firstwkst) { i -= 7 - firstwkst; } } else { i = no1wkst; } for (var k = 0; k < 7; k++) { result.wnomask[i] = 1; i++; if (result.wdaymask[i] === options.wkst) break; } } if (Object(helpers["c" /* includes */])(options.byweekno, 1)) { // Check week number 1 of next year as well // orig-TODO : Check -numweeks for next year. var i = no1wkst + numweeks * 7; if (no1wkst !== firstwkst) i -= 7 - firstwkst; if (i < yearlen) { // If week starts in next year, we // don't care about it. for (var j = 0; j < 7; j++) { result.wnomask[i] = 1; i += 1; if (result.wdaymask[i] === options.wkst) break; } } } if (no1wkst) { // Check last week number of last year as // well. If no1wkst is 0, either the year // started on week start, or week number 1 // got days from last year, so there are no // days from last year's last week number in // this year. var lnumweeks = void 0; if (!Object(helpers["c" /* includes */])(options.byweekno, -1)) { var lyearweekday = src_dateutil.getWeekday(new Date(Date.UTC(year - 1, 0, 1))); var lno1wkst = Object(helpers["i" /* pymod */])(7 - lyearweekday.valueOf() + options.wkst, 7); var lyearlen = src_dateutil.isLeapYear(year - 1) ? 366 : 365; var weekst = void 0; if (lno1wkst >= 4) { lno1wkst = 0; weekst = lyearlen + Object(helpers["i" /* pymod */])(lyearweekday - options.wkst, 7); } else { weekst = yearlen - no1wkst; } lnumweeks = Math.floor(52 + Object(helpers["i" /* pymod */])(weekst, 7) / 4); } else { lnumweeks = -1; } if (Object(helpers["c" /* includes */])(options.byweekno, lnumweeks)) { for (var i = 0; i < no1wkst; i++) result.wnomask[i] = 1; } } return result; } function baseYearMasks(year) { var yearlen = src_dateutil.isLeapYear(year) ? 366 : 365; var firstyday = new Date(Date.UTC(year, 0, 1)); var wday = src_dateutil.getWeekday(firstyday); if (yearlen === 365) { return { mmask: M365MASK, mdaymask: MDAY365MASK, nmdaymask: NMDAY365MASK, wdaymask: WDAYMASK.slice(wday), mrange: M365RANGE }; } return { mmask: M366MASK, mdaymask: MDAY366MASK, nmdaymask: NMDAY366MASK, wdaymask: WDAYMASK.slice(wday), mrange: M366RANGE }; } // CONCATENATED MODULE: ./src/iterinfo/monthinfo.ts function rebuildMonth(year, month, yearlen, mrange, wdaymask, options) { var result = { lastyear: year, lastmonth: month, nwdaymask: [] }; var ranges = []; if (options.freq === src_rrule.YEARLY) { if (Object(helpers["b" /* empty */])(options.bymonth)) { ranges = [[0, yearlen]]; } else { for (var j = 0; j < options.bymonth.length; j++) { month = options.bymonth[j]; ranges.push(mrange.slice(month - 1, month + 1)); } } } else if (options.freq === src_rrule.MONTHLY) { ranges = [mrange.slice(month - 1, month + 1)]; } if (Object(helpers["b" /* empty */])(ranges)) { return result; } // Weekly frequency won't get here, so we may not // care about cross-year weekly periods. result.nwdaymask = Object(helpers["k" /* repeat */])(0, yearlen); for (var j = 0; j < ranges.length; j++) { var rang = ranges[j]; var first = rang[0]; var last = rang[1] - 1; for (var k = 0; k < options.bynweekday.length; k++) { var i = void 0; var _a = options.bynweekday[k], wday = _a[0], n = _a[1]; if (n < 0) { i = last + (n + 1) * 7; i -= Object(helpers["i" /* pymod */])(wdaymask[i] - wday, 7); } else { i = first + (n - 1) * 7; i += Object(helpers["i" /* pymod */])(7 - wdaymask[i] + wday, 7); } if (first <= i && i <= last) result.nwdaymask[i] = 1; } } return result; } // CONCATENATED MODULE: ./src/iterinfo/easter.ts function easter(y, offset) { if (offset === void 0) { offset = 0; } var a = y % 19; var b = Math.floor(y / 100); var c = y % 100; var d = Math.floor(b / 4); var e = b % 4; var f = Math.floor((b + 8) / 25); var g = Math.floor((b - f + 1) / 3); var h = Math.floor(19 * a + b - d - g + 15) % 30; var i = Math.floor(c / 4); var k = c % 4; var l = Math.floor(32 + 2 * e + 2 * i - h - k) % 7; var m = Math.floor((a + 11 * h + 22 * l) / 451); var month = Math.floor((h + l - 7 * m + 114) / 31); var day = ((h + l - 7 * m + 114) % 31) + 1; var date = Date.UTC(y, month - 1, day + offset); var yearStart = Date.UTC(y, 0, 1); return [Math.ceil((date - yearStart) / (1000 * 60 * 60 * 24))]; } // CONCATENATED MODULE: ./src/iterinfo/index.ts // ============================================================================= // Iterinfo // ============================================================================= var iterinfo_Iterinfo = /** @class */ (function () { function Iterinfo(options) { this.options = options; } Iterinfo.prototype.rebuild = function (year, month) { var options = this.options; if (year !== this.lastyear) { this.yearinfo = rebuildYear(year, options); } if (Object(helpers["g" /* notEmpty */])(options.bynweekday) && (month !== this.lastmonth || year !== this.lastyear)) { var _a = this.yearinfo, yearlen = _a.yearlen, mrange = _a.mrange, wdaymask = _a.wdaymask; this.monthinfo = rebuildMonth(year, month, yearlen, mrange, wdaymask, options); } if (Object(helpers["f" /* isPresent */])(options.byeaster)) { this.eastermask = easter(year, options.byeaster); } }; Object.defineProperty(Iterinfo.prototype, "lastyear", { get: function () { return this.monthinfo ? this.monthinfo.lastyear : null; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "lastmonth", { get: function () { return this.monthinfo ? this.monthinfo.lastmonth : null; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "yearlen", { get: function () { return this.yearinfo.yearlen; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "yearordinal", { get: function () { return this.yearinfo.yearordinal; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "mrange", { get: function () { return this.yearinfo.mrange; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "wdaymask", { get: function () { return this.yearinfo.wdaymask; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "mmask", { get: function () { return this.yearinfo.mmask; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "wnomask", { get: function () { return this.yearinfo.wnomask; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "nwdaymask", { get: function () { return this.monthinfo ? this.monthinfo.nwdaymask : []; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "nextyearlen", { get: function () { return this.yearinfo.nextyearlen; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "mdaymask", { get: function () { return this.yearinfo.mdaymask; }, enumerable: true, configurable: true }); Object.defineProperty(Iterinfo.prototype, "nmdaymask", { get: function () { return this.yearinfo.nmdaymask; }, enumerable: true, configurable: true }); Iterinfo.prototype.ydayset = function () { return [Object(helpers["j" /* range */])(this.yearlen), 0, this.yearlen]; }; Iterinfo.prototype.mdayset = function (_, month, __) { var start = this.mrange[month - 1]; var end = this.mrange[month]; var set = Object(helpers["k" /* repeat */])(null, this.yearlen); for (var i = start; i < end; i++) set[i] = i; return [set, start, end]; }; Iterinfo.prototype.wdayset = function (year, month, day) { // We need to handle cross-year weeks here. var set = Object(helpers["k" /* repeat */])(null, this.yearlen + 7); var i = src_dateutil.toOrdinal(new Date(Date.UTC(year, month - 1, day))) - this.yearordinal; var start = i; for (var j = 0; j < 7; j++) { set[i] = i; ++i; if (this.wdaymask[i] === this.options.wkst) break; } return [set, start, i]; }; Iterinfo.prototype.ddayset = function (year, month, day) { var set = Object(helpers["k" /* repeat */])(null, this.yearlen); var i = src_dateutil.toOrdinal(new Date(Date.UTC(year, month - 1, day))) - this.yearordinal; set[i] = i; return [set, i, i + 1]; }; Iterinfo.prototype.htimeset = function (hour, _, second, millisecond) { var _this = this; var set = []; this.options.byminute.forEach(function (minute) { set = set.concat(_this.mtimeset(hour, minute, second, millisecond)); }); src_dateutil.sort(set); return set; }; Iterinfo.prototype.mtimeset = function (hour, minute, _, millisecond) { var set = this.options.bysecond.map(function (second) { return new Time(hour, minute, second, millisecond); }); src_dateutil.sort(set); return set; }; Iterinfo.prototype.stimeset = function (hour, minute, second, millisecond) { return [new Time(hour, minute, second, millisecond)]; }; Iterinfo.prototype.getdayset = function (freq) { switch (freq) { case Frequency.YEARLY: return this.ydayset.bind(this); case Frequency.MONTHLY: return this.mdayset.bind(this); case Frequency.WEEKLY: return this.wdayset.bind(this); case Frequency.DAILY: return this.ddayset.bind(this); default: return this.ddayset.bind(this); } }; Iterinfo.prototype.gettimeset = function (freq) { switch (freq) { case Frequency.HOURLY: return this.htimeset.bind(this); case Frequency.MINUTELY: return this.mtimeset.bind(this); case Frequency.SECONDLY: return this.stimeset.bind(this); } }; return Iterinfo; }()); /* harmony default export */ var iterinfo = (iterinfo_Iterinfo); // CONCATENATED MODULE: ./src/iter/poslist.ts function buildPoslist(bysetpos, timeset, start, end, ii, dayset) { var poslist = []; for (var j = 0; j < bysetpos.length; j++) { var daypos = void 0; var timepos = void 0; var pos = bysetpos[j]; if (pos < 0) { daypos = Math.floor(pos / timeset.length); timepos = Object(helpers["i" /* pymod */])(pos, timeset.length); } else { daypos = Math.floor((pos - 1) / timeset.length); timepos = Object(helpers["i" /* pymod */])(pos - 1, timeset.length); } var tmp = []; for (var k = start; k < end; k++) { var val = dayset[k]; if (!Object(helpers["f" /* isPresent */])(val)) continue; tmp.push(val); } var i = void 0; if (daypos < 0) { i = tmp.slice(daypos)[0]; } else { i = tmp[daypos]; } var time = timeset[timepos]; var date = src_dateutil.fromOrdinal(ii.yearordinal + i); var res = src_dateutil.combine(date, time); // XXX: can this ever be in the array? // - compare the actual date instead? if (!Object(helpers["c" /* includes */])(poslist, res)) poslist.push(res); } src_dateutil.sort(poslist); return poslist; } // CONCATENATED MODULE: ./src/iter/index.ts function iter(iterResult, options) { var dtstart = options.dtstart, freq = options.freq, interval = options.interval, until = options.until, bysetpos = options.bysetpos; var count = options.count; if (count === 0 || interval === 0) { return emitResult(iterResult); } var counterDate = datetime_DateTime.fromDate(dtstart); var ii = new iterinfo(options); ii.rebuild(counterDate.year, counterDate.month); var timeset = makeTimeset(ii, counterDate, options); while (true) { var _a = ii.getdayset(freq)(counterDate.year, counterDate.month, counterDate.day), dayset = _a[0], start = _a[1], end = _a[2]; var filtered = removeFilteredDays(dayset, start, end, ii, options); if (Object(helpers["g" /* notEmpty */])(bysetpos)) { var poslist = buildPoslist(bysetpos, timeset, start, end, ii, dayset); for (var j = 0; j < poslist.length; j++) { var res = poslist[j]; if (until && res > until) { return emitResult(iterResult); } if (res >= dtstart) { var rezonedDate = rezoneIfNeeded(res, options); if (!iterResult.accept(rezonedDate)) { return emitResult(iterResult); } if (count) { --count; if (!count) { return emitResult(iterResult); } } } } } else { for (var j = start; j < end; j++) { var currentDay = dayset[j]; if (!Object(helpers["f" /* isPresent */])(currentDay)) { continue; } var date = src_dateutil.fromOrdinal(ii.yearordinal + currentDay); for (var k = 0; k < timeset.length; k++) { var time = timeset[k]; var res = src_dateutil.combine(date, time); if (until && res > until) { return emitResult(iterResult); } if (res >= dtstart) { var rezonedDate = rezoneIfNeeded(res, options); if (!iterResult.accept(rezonedDate)) { return emitResult(iterResult); } if (count) { --count; if (!count) { return emitResult(iterResult); } } } } } } if (options.interval === 0) { return emitResult(iterResult); } // Handle frequency and interval counterDate.add(options, filtered); if (counterDate.year > src_dateutil.MAXYEAR) { return emitResult(iterResult); } if (!freqIsDailyOrGreater(freq)) { timeset = ii.gettimeset(freq)(counterDate.hour, counterDate.minute, counterDate.second, 0); } ii.rebuild(counterDate.year, counterDate.month); } } function isFiltered(ii, currentDay, options) { var bymonth = options.bymonth, byweekno = options.byweekno, byweekday = options.byweekday, byeaster = options.byeaster, bymonthday = options.bymonthday, bynmonthday = options.bynmonthday, byyearday = options.byyearday; return ((Object(helpers["g" /* notEmpty */])(bymonth) && !Object(helpers["c" /* includes */])(bymonth, ii.mmask[currentDay])) || (Object(helpers["g" /* notEmpty */])(byweekno) && !ii.wnomask[currentDay]) || (Object(helpers["g" /* notEmpty */])(byweekday) && !Object(helpers["c" /* includes */])(byweekday, ii.wdaymask[currentDay])) || (Object(helpers["g" /* notEmpty */])(ii.nwdaymask) && !ii.nwdaymask[currentDay]) || (byeaster !== null && !Object(helpers["c" /* includes */])(ii.eastermask, currentDay)) || ((Object(helpers["g" /* notEmpty */])(bymonthday) || Object(helpers["g" /* notEmpty */])(bynmonthday)) && !Object(helpers["c" /* includes */])(bymonthday, ii.mdaymask[currentDay]) && !Object(helpers["c" /* includes */])(bynmonthday, ii.nmdaymask[currentDay])) || (Object(helpers["g" /* notEmpty */])(byyearday) && ((currentDay < ii.yearlen && !Object(helpers["c" /* includes */])(byyearday, currentDay + 1) && !Object(helpers["c" /* includes */])(byyearday, -ii.yearlen + currentDay)) || (currentDay >= ii.yearlen && !Object(helpers["c" /* includes */])(byyearday, currentDay + 1 - ii.yearlen) && !Object(helpers["c" /* includes */])(byyearday, -ii.nextyearlen + currentDay - ii.yearlen))))); } function rezoneIfNeeded(date, options) { return new datewithzone_DateWithZone(date, options.tzid).rezonedDate(); } function emitResult(iterResult) { return iterResult.getValue(); } function removeFilteredDays(dayset, start, end, ii, options) { var filtered = false; for (var dayCounter = start; dayCounter < end; dayCounter++) { var currentDay = dayset[dayCounter]; filtered = isFiltered(ii, currentDay, options); if (filtered) dayset[currentDay] = null; } return filtered; } function makeTimeset(ii, counterDate, options) { var freq = options.freq, byhour = options.byhour, byminute = options.byminute, bysecond = options.bysecond; if (freqIsDailyOrGreater(freq)) { return buildTimeset(options); } if ((freq >= src_rrule.HOURLY && Object(helpers["g" /* notEmpty */])(byhour) && !Object(helpers["c" /* includes */])(byhour, counterDate.hour)) || (freq >= src_rrule.MINUTELY && Object(helpers["g" /* notEmpty */])(byminute) && !Object(helpers["c" /* includes */])(byminute, counterDate.minute)) || (freq >= src_rrule.SECONDLY && Object(helpers["g" /* notEmpty */])(bysecond) && !Object(helpers["c" /* includes */])(bysecond, counterDate.second))) { return []; } return ii.gettimeset(freq)(counterDate.hour, counterDate.minute, counterDate.second, counterDate.millisecond); } // CONCATENATED MODULE: ./src/rrule.ts var getnlp = function () { // Lazy, runtime import to avoid circular refs. if (!getnlp._nlp) { getnlp._nlp = __webpack_require__(8); } return getnlp._nlp; }; // ============================================================================= // RRule // ============================================================================= var Days = { MO: new Weekday(0), TU: new Weekday(1), WE: new Weekday(2), TH: new Weekday(3), FR: new Weekday(4), SA: new Weekday(5), SU: new Weekday(6) }; var DEFAULT_OPTIONS = { freq: Frequency.YEARLY, dtstart: null, interval: 1, wkst: Days.MO, count: null, until: null, tzid: null, bysetpos: null, bymonth: null, bymonthday: null, bynmonthday: null, byyearday: null, byweekno: null, byweekday: null, bynweekday: null, byhour: null, byminute: null, bysecond: null, byeaster: null }; var rrule_defaultKeys = Object.keys(DEFAULT_OPTIONS); /** * * @param {Options?} options - see <http://labix.org/python-dateutil/#head-cf004ee9a75592797e076752b2a889c10f445418> * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... * @constructor */ var rrule_RRule = /** @class */ (function () { function RRule(options, noCache) { if (options === void 0) { options = {}; } if (noCache === void 0) { noCache = false; } // RFC string this._cache = noCache ? null : new cache_Cache(); // used by toString() this.origOptions = initializeOptions(options); var parsedOptions = parseOptions(options).parsedOptions; this.options = parsedOptions; } RRule.parseText = function (text, language) { return getnlp().parseText(text, language); }; RRule.fromText = function (text, language) { return getnlp().fromText(text, language); }; RRule.fromString = function (str) { return new RRule(RRule.parseString(str) || undefined); }; RRule.prototype._iter = function (iterResult) { return iter(iterResult, this.options); }; RRule.prototype._cacheGet = function (what, args) { if (!this._cache) return false; return this._cache._cacheGet(what, args); }; RRule.prototype._cacheAdd = function (what, value, args) { if (!this._cache) return; return this._cache._cacheAdd(what, value, args); }; /** * @param {Function} iterator - optional function that will be called * on each date that is added. It can return false * to stop the iteration. * @return Array containing all recurrences. */ RRule.prototype.all = function (iterator) { if (iterator) { return this._iter(new callbackiterresult('all', {}, iterator)); } var result = this._cacheGet('all'); if (result === false) { result = this._iter(new iterresult('all', {})); this._cacheAdd('all', result); } return result; }; /** * Returns all the occurrences of the rrule between after and before. * The inc keyword defines what happens if after and/or before are * themselves occurrences. With inc == True, they will be included in the * list, if they are found in the recurrence set. * @return Array */ RRule.prototype.between = function (after, before, inc, iterator) { if (inc === void 0) { inc = false; } if (!src_dateutil.isValidDate(after) || !src_dateutil.isValidDate(before)) throw new Error('Invalid date passed in to RRule.between'); var args = { before: before, after: after, inc: inc }; if (iterator) { return this._iter(new callbackiterresult('between', args, iterator)); } var result = this._cacheGet('between', args); if (result === false) { result = this._iter(new iterresult('between', args)); this._cacheAdd('between', result, args); } return result; }; /** * Returns the last recurrence before the given datetime instance. * The inc keyword defines what happens if dt is an occurrence. * With inc == True, if dt itself is an occurrence, it will be returned. * @return Date or null */ RRule.prototype.before = function (dt, inc) { if (inc === void 0) { inc = false; } if (!src_dateutil.isValidDate(dt)) throw new Error('Invalid date passed in to RRule.before'); var args = { dt: dt, inc: inc }; var result = this._cacheGet('before', args); if (result === false) { result = this._iter(new iterresult('before', args)); this._cacheAdd('before', result, args); } return result; }; /** * Returns the first recurrence after the given datetime instance. * The inc keyword defines what happens if dt is an occurrence. * With inc == True, if dt itself is an occurrence, it will be returned. * @return Date or null */ RRule.prototype.after = function (dt, inc) { if (inc === void 0) { inc = false; } if (!src_dateutil.isValidDate(dt)) throw new Error('Invalid date passed in to RRule.after'); var args = { dt: dt, inc: inc }; var result = this._cacheGet('after', args); if (result === false) { result = this._iter(new iterresult('after', args)); this._cacheAdd('after', result, args); } return result; }; /** * Returns the number of recurrences in this set. It will have go trough * the whole recurrence, if this hasn't been done before. */ RRule.prototype.count = function () { return this.all().length; }; /** * Converts the rrule into its string representation * @see <http://www.ietf.org/rfc/rfc2445.txt> * @return String */ RRule.prototype.toString = function () { return optionsToString(this.origOptions); }; /** * Will convert all rules described in nlp:ToText * to text. */ RRule.prototype.toText = function (gettext, language, dateFormatter) { return getnlp().toText(this, gettext, language, dateFormatter); }; RRule.prototype.isFullyConvertibleToText = function () { return getnlp().isFullyConvertible(this); }; /** * @return a RRule instance with the same freq and options * as this one (cache is not cloned) */ RRule.prototype.clone = function () { return new RRule(this.origOptions); }; // RRule class 'constants' RRule.FREQUENCIES = [ 'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY', 'HOURLY', 'MINUTELY', 'SECONDLY' ]; RRule.YEARLY = Frequency.YEARLY; RRule.MONTHLY = Frequency.MONTHLY; RRule.WEEKLY = Frequency.WEEKLY; RRule.DAILY = Frequency.DAILY; RRule.HOURLY = Frequency.HOURLY; RRule.MINUTELY = Frequency.MINUTELY; RRule.SECONDLY = Frequency.SECONDLY; RRule.MO = Days.MO; RRule.TU = Days.TU; RRule.WE = Days.WE; RRule.TH = Days.TH; RRule.FR = Days.FR; RRule.SA = Days.SA; RRule.SU = Days.SU; RRule.parseString = parseString; RRule.optionsToString = optionsToString; return RRule; }()); /* harmony default export */ var src_rrule = (rrule_RRule); // CONCATENATED MODULE: ./src/iterset.ts function iterSet(iterResult, _rrule, _exrule, _rdate, _exdate, tzid) { var _exdateHash = {}; var _accept = iterResult.accept; function evalExdate(after, before) { _exrule.forEach(function (rrule) { rrule.between(after, before, true).forEach(function (date) { _exdateHash[Number(date)] = true; }); }); } _exdate.forEach(function (date) { var zonedDate = new datewithzone_DateWithZone(date, tzid).rezonedDate(); _exdateHash[Number(zonedDate)] = true; }); iterResult.accept = function (date) { var dt = Number(date); if (!_exdateHash[dt]) { evalExdate(new Date(dt - 1), new Date(dt + 1)); if (!_exdateHash[dt]) { _exdateHash[dt] = true; return _accept.call(this, date); } } return true; }; if (iterResult.method === 'between') { evalExdate(iterResult.args.after, iterResult.args.before); iterResult.accept = function (date) { var dt = Number(date); if (!_exdateHash[dt]) { _exdateHash[dt] = true; return _accept.call(this, date); } return true; }; } for (var i = 0; i < _rdate.length; i++) { var zonedDate = new datewithzone_DateWithZone(_rdate[i], tzid).rezonedDate(); if (!iterResult.accept(new Date(zonedDate.getTime()))) break; } _rrule.forEach(function (rrule) { iter(iterResult, rrule.options); }); var res = iterResult._result; src_dateutil.sort(res); switch (iterResult.method) { case 'all': case 'between': return res; case 'before': return ((res.length && res[res.length - 1]) || null); case 'after': default: return ((res.length && res[0]) || null); } } // CONCATENATED MODULE: ./src/rrulestr.ts /** * RRuleStr * To parse a set of rrule strings */ var rrulestr_DEFAULT_OPTIONS = { dtstart: null, cache: false, unfold: false, forceset: false, compatible: false, tzid: null }; function parseInput(s, options) { var rrulevals = []; var rdatevals = []; var exrulevals = []; var exdatevals = []; var _a = parseDtstart(s), dtstart = _a.dtstart, tzid = _a.tzid; var lines = splitIntoLines(s, options.unfold); lines.forEach(function (line) { if (!line) return; var _a = breakDownLine(line), name = _a.name, parms = _a.parms, value = _a.value; switch (name.toUpperCase()) { case 'RRULE': if (parms.length) { throw new Error("unsupported RRULE parm: " + parms.join(',')); } rrulevals.push(parseString(line)); break; case 'RDATE': var _b = /RDATE(?:;TZID=([^:=]+))?/i.exec(line), _ = _b[0], rdateTzid = _b[1]; if (rdateTzid && !tzid) { tzid = rdateTzid; } rdatevals = rdatevals.concat(parseRDate(value, parms)); break; case 'EXRULE': if (parms.length) { throw new Error("unsupported EXRULE parm: " + parms.join(',')); } exrulevals.push(parseString(value)); break; case 'EXDATE': exdatevals = exdatevals.concat(parseRDate(value, parms)); break; case 'DTSTART': break; default: throw new Error('unsupported property: ' + name); } }); return { dtstart: dtstart, tzid: tzid, rrulevals: rrulevals, rdatevals: rdatevals, exrulevals: exrulevals, exdatevals: exdatevals }; } function buildRule(s, options) { var _a = parseInput(s, options), rrulevals = _a.rrulevals, rdatevals = _a.rdatevals, exrulevals = _a.exrulevals, exdatevals = _a.exdatevals, dtstart = _a.dtstart, tzid = _a.tzid; var noCache = options.cache === false; if (options.compatible) { options.forceset = true; options.unfold = true; } if (options.forceset || rrulevals.length > 1 || rdatevals.length || exrulevals.length || exdatevals.length) { var rset_1 = new rruleset(noCache); rset_1.dtstart(dtstart); rset_1.tzid(tzid || undefined); rrulevals.forEach(function (val) { rset_1.rrule(new src_rrule(groomRruleOptions(val, dtstart, tzid), noCache)); }); rdatevals.forEach(function (date) { rset_1.rdate(date); }); exrulevals.forEach(function (val) { rset_1.exrule(new src_rrule(groomRruleOptions(val, dtstart, tzid), noCache)); }); exdatevals.forEach(function (date) { rset_1.exdate(date); }); if (options.compatible && options.dtstart) rset_1.rdate(dtstart); return rset_1; } var val = rrulevals[0] || {}; return new src_rrule(groomRruleOptions(val, val.dtstart || options.dtstart || dtstart, val.tzid || options.tzid || tzid), noCache); } function rrulestr(s, options) { if (options === void 0) { options = {}; } return buildRule(s, rrulestr_initializeOptions(options)); } function groomRruleOptions(val, dtstart, tzid) { return __assign({}, val, { dtstart: dtstart, tzid: tzid }); } function rrulestr_initializeOptions(options) { var invalid = []; var keys = Object.keys(options); var defaultKeys = Object.keys(rrulestr_DEFAULT_OPTIONS); keys.forEach(function (key) { if (!Object(helpers["c" /* includes */])(defaultKeys, key)) invalid.push(key); }); if (invalid.length) { throw new Error('Invalid options: ' + invalid.join(', ')); } var initializedOptions = __assign({}, options); // Merge in default options defaultKeys.forEach(function (key) { if (!Object(helpers["c" /* includes */])(keys, key)) initializedOptions[key] = rrulestr_DEFAULT_OPTIONS[key]; }); return initializedOptions; } function extractName(line) { if (line.indexOf(':') === -1) { return { name: 'RRULE', value: line }; } var _a = Object(helpers["l" /* split */])(line, ':', 1), name = _a[0], value = _a[1]; return { name: name, value: value }; } function breakDownLine(line) { var _a = extractName(line), name = _a.name, value = _a.value; var parms = name.split(';'); if (!parms) throw new Error('empty property name'); return { name: parms[0].toUpperCase(), parms: parms.slice(1), value: value }; } function splitIntoLines(s, unfold) { if (unfold === void 0) { unfold = false; } s = s && s.trim(); if (!s) throw new Error('Invalid empty string'); // More info about 'unfold' option // Go head to http://www.ietf.org/rfc/rfc2445.txt if (!unfold) { return s.split(/\s/); } var lines = s.split('\n'); var i = 0; while (i < lines.length) { // TODO var line = (lines[i] = lines[i].replace(/\s+$/g, '')); if (!line) { lines.splice(i, 1); } else if (i > 0 && line[0] === ' ') { lines[i - 1] += line.slice(1); lines.splice(i, 1); } else { i += 1; } } return lines; } function validateDateParm(parms) { parms.forEach(function (parm) { if (!/(VALUE=DATE(-TIME)?)|(TZID=)/.test(parm)) { throw new Error('unsupported RDATE/EXDATE parm: ' + parm); } }); } function parseRDate(rdateval, parms) { validateDateParm(parms); return rdateval .split(',') .map(function (datestr) { return src_dateutil.untilStringToDate(datestr); }); } // CONCATENATED MODULE: ./src/rruleset.ts function createGetterSetter(fieldName) { var _this = this; return function (field) { if (field !== undefined) { _this["_" + fieldName] = field; } if (_this["_" + fieldName] !== undefined) { return _this["_" + fieldName]; } for (var i = 0; i < _this._rrule.length; i++) { var field_1 = _this._rrule[i].origOptions[fieldName]; if (field_1) { return field_1; } } }; } var rruleset_RRuleSet = /** @class */ (function (_super) { __extends(RRuleSet, _super); /** * * @param {Boolean?} noCache * The same stratagy as RRule on cache, default to false * @constructor */ function RRuleSet(noCache) { if (noCache === void 0) { noCache = false; } var _this = _super.call(this, {}, noCache) || this; _this.dtstart = createGetterSetter.apply(_this, ['dtstart']); _this.tzid = createGetterSetter.apply(_this, ['tzid']); _this._rrule = []; _this._rdate = []; _this._exrule = []; _this._exdate = []; return _this; } RRuleSet.prototype._iter = function (iterResult) { return iterSet(iterResult, this._rrule, this._exrule, this._rdate, this._exdate, this.tzid()); }; /** * Adds an RRule to the set * * @param {RRule} */ RRuleSet.prototype.rrule = function (rrule) { _addRule(rrule, this._rrule); }; /** * Adds an EXRULE to the set * * @param {RRule} */ RRuleSet.prototype.exrule = function (rrule) { _addRule(rrule, this._exrule); }; /** * Adds an RDate to the set * * @param {Date} */ RRuleSet.prototype.rdate = function (date) { _addDate(date, this._rdate); }; /** * Adds an EXDATE to the set * * @param {Date} */ RRuleSet.prototype.exdate = function (date) { _addDate(date, this._exdate); }; /** * Get list of included rrules in this recurrence set. * * @return List of rrules */ RRuleSet.prototype.rrules = function () { return this._rrule.map(function (e) { return rrulestr(e.toString()); }); }; /** * Get list of excluded rrules in this recurrence set. * * @return List of exrules */ RRuleSet.prototype.exrules = function () { return this._exrule.map(function (e) { return rrulestr(e.toString()); }); }; /** * Get list of included datetimes in this recurrence set. * * @return List of rdates */ RRuleSet.prototype.rdates = function () { return this._rdate.map(function (e) { return new Date(e.getTime()); }); }; /** * Get list of included datetimes in this recurrence set. * * @return List of exdates */ RRuleSet.prototype.exdates = function () { return this._exdate.map(function (e) { return new Date(e.getTime()); }); }; RRuleSet.prototype.valueOf = function () { var result = []; if (!this._rrule.length && this._dtstart) { result = result.concat(optionsToString({ dtstart: this._dtstart })); } this._rrule.forEach(function (rrule) { result = result.concat(rrule.toString().split('\n')); }); this._exrule.forEach(function (exrule) { result = result.concat(exrule.toString().split('\n') .map(function (line) { return line.replace(/^RRULE:/, 'EXRULE:'); }) .filter(function (line) { return !/^DTSTART/.test(line); })); }); if (this._rdate.length) { result.push(rdatesToString('RDATE', this._rdate, this.tzid())); } if (this._exdate.length) { result.push(rdatesToString('EXDATE', this._exdate, this.tzid())); } return result; }; /** * to generate recurrence field such as: * DTSTART:19970902T010000Z * RRULE:FREQ=YEARLY;COUNT=2;BYDAY=TU * RRULE:FREQ=YEARLY;COUNT=1;BYDAY=TH */ RRuleSet.prototype.toString = function () { return this.valueOf().join('\n'); }; /** * Create a new RRuleSet Object completely base on current instance */ RRuleSet.prototype.clone = function () { var rrs = new RRuleSet(!!this._cache); this._rrule.forEach(function (rule) { return rrs.rrule(rule.clone()); }); this._exrule.forEach(function (rule) { return rrs.exrule(rule.clone()); }); this._rdate.forEach(function (date) { return rrs.rdate(new Date(date.getTime())); }); this._exdate.forEach(function (date) { return rrs.exdate(new Date(date.getTime())); }); return rrs; }; return RRuleSet; }(src_rrule)); /* harmony default export */ var rruleset = (rruleset_RRuleSet); function _addRule(rrule, collection) { if (!(rrule instanceof src_rrule)) { throw new TypeError(String(rrule) + ' is not RRule instance'); } if (!Object(helpers["c" /* includes */])(collection.map(String), String(rrule))) { collection.push(rrule); } } function _addDate(date, collection) { if (!(date instanceof Date)) { throw new TypeError(String(date) + ' is not Date instance'); } if (!Object(helpers["c" /* includes */])(collection.map(Number), Number(date))) { collection.push(date); src_dateutil.sort(collection); } } function rdatesToString(param, rdates, tzid) { var isUTC = !tzid || tzid.toUpperCase() === 'UTC'; var header = isUTC ? param + ":" : param + ";TZID=" + tzid + ":"; var dateString = rdates .map(function (rdate) { return src_dateutil.timeToUntilString(rdate.valueOf(), isUTC); }) .join(','); return "" + header + dateString; } // CONCATENATED MODULE: ./src/index.ts /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Frequency", function() { return Frequency; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "Weekday", function() { return Weekday; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "RRule", function() { return src_rrule; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "RRuleSet", function() { return rruleset; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "rrulestr", function() { return rrulestr; }); /*! * rrule.js - Library for working with recurrence rules for calendar dates. * https://github.com/jakubroztocil/rrule * * Copyright 2010, Jakub Roztocil and Lars Schoning * Licenced under the BSD licence. * https://github.com/jakubroztocil/rrule/blob/master/LICENCE * * Based on: * python-dateutil - Extensions to the standard Python datetime module. * Copyright (c) 2003-2011 - Gustavo Niemeyer <gustavo@niemeyer.net> * Copyright (c) 2012 - Tomi Pieviläinen <tomi.pievilainen@iki.fi> * https://github.com/jakubroztocil/rrule/blob/master/LICENCE * */ // ============================================================================= // Export // ============================================================================= /* harmony default export */ var src = __webpack_exports__["default"] = (src_rrule); /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, '__esModule', { value: true }); /* This is just a junk drawer, containing anything used across multiple classes. Because Luxon is small(ish), this should stay small and we won't worry about splitting it up into, say, parsingUtil.js and basicUtil.js and so on. But they are divided up by feature area. */ /** * @private */ // TYPES function isUndefined(o) { return typeof o === 'undefined'; } function isNumber(o) { return typeof o === 'number'; } function isString(o) { return typeof o === 'string'; } function isDate(o) { return Object.prototype.toString.call(o) === '[object Date]'; } // CAPABILITIES function hasIntl() { return typeof Intl !== 'undefined' && Intl.DateTimeFormat; } function hasFormatToParts() { return !isUndefined(Intl.DateTimeFormat.prototype.formatToParts); } // OBJECTS AND ARRAYS function maybeArray(thing) { return Array.isArray(thing) ? thing : [thing]; } function bestBy(arr, by, compare) { if (arr.length === 0) { return undefined; } return arr.reduce(function (best, next) { var pair = [by(next), next]; if (!best) { return pair; } else if (compare.apply(null, [best[0], pair[0]]) === best[0]) { return best; } else { return pair; } }, null)[1]; } function pick(obj, keys) { return keys.reduce(function (a, k) { a[k] = obj[k]; return a; }, {}); } // NUMBERS AND STRINGS function numberBetween(thing, bottom, top) { return isNumber(thing) && thing >= bottom && thing <= top; } // x % n but takes the sign of n instead of x function floorMod(x, n) { return x - n * Math.floor(x / n); } function padStart(input) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; if (input.toString().length < n) { return ('0'.repeat(n) + input).slice(-n); } else { return input.toString(); } } function parseMillis(fraction) { if (isUndefined(fraction)) { return NaN; } else { var f = parseFloat('0.' + fraction) * 1000; return Math.floor(f); } } function roundTo(number, digits) { var factor = Math.pow(10, digits); return Math.round(number * factor) / factor; } // DATE BASICS function isLeapYear(year) { return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } function daysInMonth(year, month) { var modMonth = floorMod(month - 1, 12) + 1, modYear = year + (month - modMonth) / 12; if (modMonth === 2) { return isLeapYear(modYear) ? 29 : 28; } else { return [31, null, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][modMonth - 1]; } } function weeksInWeekYear(weekYear) { var p1 = (weekYear + Math.floor(weekYear / 4) - Math.floor(weekYear / 100) + Math.floor(weekYear / 400)) % 7, last = weekYear - 1, p2 = (last + Math.floor(last / 4) - Math.floor(last / 100) + Math.floor(last / 400)) % 7; return p1 === 4 || p2 === 3 ? 53 : 52; } function untruncateYear(year) { if (year > 99) { return year; } else return year > 60 ? 1900 + year : 2000 + year; } // PARSING function parseZoneInfo(ts, offsetFormat, locale) { var timeZone = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var date = new Date(ts), intlOpts = { hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' }; if (timeZone) { intlOpts.timeZone = timeZone; } var modified = Object.assign({ timeZoneName: offsetFormat }, intlOpts), intl = hasIntl(); if (intl && hasFormatToParts()) { var parsed = new Intl.DateTimeFormat(locale, modified).formatToParts(date).find(function (m) { return m.type.toLowerCase() === 'timezonename'; }); return parsed ? parsed.value : null; } else if (intl) { // this probably doesn't work for all locales var without = new Intl.DateTimeFormat(locale, intlOpts).format(date), included = new Intl.DateTimeFormat(locale, modified).format(date), diffed = included.substring(without.length), trimmed = diffed.replace(/^[, ]+/, ''); return trimmed; } else { return null; } } // signedOffset('-5', '30') -> -330 function signedOffset(offHourStr, offMinuteStr) { var offHour = parseInt(offHourStr, 10) || 0, offMin = parseInt(offMinuteStr, 10) || 0, offMinSigned = offHour < 0 ? -offMin : offMin; return offHour * 60 + offMinSigned; } // COERCION function normalizeObject(obj, normalizer) { var ignoreUnknown = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var normalized = {}; for (var u in obj) { if (obj.hasOwnProperty(u)) { var v = obj[u]; if (v !== null && !isUndefined(v) && !Number.isNaN(v)) { var mapped = normalizer(u, ignoreUnknown); if (mapped) { normalized[mapped] = v; } } } } return normalized; } function timeObject(obj) { return pick(obj, ['hour', 'minute', 'second', 'millisecond']); } var customInspectSymbol = function () { try { return __webpack_require__(3).inspect.custom; // eslint-disable-line global-require } catch (_err) { return Symbol('util.inspect.custom'); } }(); /** * @private */ var n = 'numeric'; var s = 'short'; var l = 'long'; var d2 = '2-digit'; var DATE_SHORT = { year: n, month: n, day: n }; var DATE_MED = { year: n, month: s, day: n }; var DATE_FULL = { year: n, month: l, day: n }; var DATE_HUGE = { year: n, month: l, day: n, weekday: l }; var TIME_SIMPLE = { hour: n, minute: d2 }; var TIME_WITH_SECONDS = { hour: n, minute: d2, second: d2 }; var TIME_WITH_SHORT_OFFSET = { hour: n, minute: d2, second: d2, timeZoneName: s }; var TIME_WITH_LONG_OFFSET = { hour: n, minute: d2, second: d2, timeZoneName: l }; var TIME_24_SIMPLE = { hour: n, minute: d2, hour12: false }; /** * {@link toLocaleString}; format like '09:30:23', always 24-hour. */ var TIME_24_WITH_SECONDS = { hour: n, minute: d2, second: d2, hour12: false }; /** * {@link toLocaleString}; format like '09:30:23 EDT', always 24-hour. */ var TIME_24_WITH_SHORT_OFFSET = { hour: n, minute: d2, second: d2, hour12: false, timeZoneName: s }; /** * {@link toLocaleString}; format like '09:30:23 Eastern Daylight Time', always 24-hour. */ var TIME_24_WITH_LONG_OFFSET = { hour: n, minute: d2, second: d2, hour12: false, timeZoneName: l }; /** * {@link toLocaleString}; format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. */ var DATETIME_SHORT = { year: n, month: n, day: n, hour: n, minute: d2 }; /** * {@link toLocaleString}; format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. */ var DATETIME_SHORT_WITH_SECONDS = { year: n, month: n, day: n, hour: n, minute: d2, second: d2 }; var DATETIME_MED = { year: n, month: s, day: n, hour: n, minute: d2 }; var DATETIME_MED_WITH_SECONDS = { year: n, month: s, day: n, hour: n, minute: d2, second: d2 }; var DATETIME_FULL = { year: n, month: l, day: n, hour: n, minute: d2, timeZoneName: s }; var DATETIME_FULL_WITH_SECONDS = { year: n, month: l, day: n, hour: n, minute: d2, second: d2, timeZoneName: s }; var DATETIME_HUGE = { year: n, month: l, day: n, weekday: l, hour: n, minute: d2, timeZoneName: l }; var DATETIME_HUGE_WITH_SECONDS = { year: n, month: l, day: n, weekday: l, hour: n, minute: d2, second: d2, timeZoneName: l }; function stringify(obj) { return JSON.stringify(obj, Object.keys(obj).sort()); } /** * @private */ var monthsLong = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var monthsShort = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; var monthsNarrow = ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D']; function months(length) { switch (length) { case 'narrow': return monthsNarrow; case 'short': return monthsShort; case 'long': return monthsLong; case 'numeric': return ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']; case '2-digit': return ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']; default: return null; } } var weekdaysLong = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; var weekdaysShort = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; var weekdaysNarrow = ['M', 'T', 'W', 'T', 'F', 'S', 'S']; function weekdays(length) { switch (length) { case 'narrow': return weekdaysNarrow; case 'short': return weekdaysShort; case 'long': return weekdaysLong; case 'numeric': return ['1', '2', '3', '4', '5', '6', '7']; default: return null; } } var meridiems = ['AM', 'PM']; var erasLong = ['Before Christ', 'Anno Domini']; var erasShort = ['BC', 'AD']; var erasNarrow = ['B', 'A']; function eras(length) { switch (length) { case 'narrow': return erasNarrow; case 'short': return erasShort; case 'long': return erasLong; default: return null; } } function meridiemForDateTime(dt) { return meridiems[dt.hour < 12 ? 0 : 1]; } function weekdayForDateTime(dt, length) { return weekdays(length)[dt.weekday - 1]; } function monthForDateTime(dt, length) { return months(length)[dt.month - 1]; } function eraForDateTime(dt, length) { return eras(length)[dt.year < 0 ? 0 : 1]; } function formatString(knownFormat) { // these all have the offsets removed because we don't have access to them // without all the intl stuff this is backfilling var filtered = pick(knownFormat, ['weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName', 'hour12']), key = stringify(filtered), dateTimeHuge = 'EEEE, LLLL d, yyyy, h:mm a'; switch (key) { case stringify(DATE_SHORT): return 'M/d/yyyy'; case stringify(DATE_MED): return 'LLL d, yyyy'; case stringify(DATE_FULL): return 'LLLL d, yyyy'; case stringify(DATE_HUGE): return 'EEEE, LLLL d, yyyy'; case stringify(TIME_SIMPLE): return 'h:mm a'; case stringify(TIME_WITH_SECONDS): return 'h:mm:ss a'; case stringify(TIME_WITH_SHORT_OFFSET): return 'h:mm a'; case stringify(TIME_WITH_LONG_OFFSET): return 'h:mm a'; case stringify(TIME_24_SIMPLE): return 'HH:mm'; case stringify(TIME_24_WITH_SECONDS): return 'HH:mm:ss'; case stringify(TIME_24_WITH_SHORT_OFFSET): return 'HH:mm'; case stringify(TIME_24_WITH_LONG_OFFSET): return 'HH:mm'; case stringify(DATETIME_SHORT): return 'M/d/yyyy, h:mm a'; case stringify(DATETIME_MED): return 'LLL d, yyyy, h:mm a'; case stringify(DATETIME_FULL): return 'LLLL d, yyyy, h:mm a'; case stringify(DATETIME_HUGE): return dateTimeHuge; case stringify(DATETIME_SHORT_WITH_SECONDS): return 'M/d/yyyy, h:mm:ss a'; case stringify(DATETIME_MED_WITH_SECONDS): return 'LLL d, yyyy, h:mm:ss a'; case stringify(DATETIME_FULL_WITH_SECONDS): return 'LLLL d, yyyy, h:mm:ss a'; case stringify(DATETIME_HUGE_WITH_SECONDS): return 'EEEE, LLLL d, yyyy, h:mm:ss a'; default: return dateTimeHuge; } } var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = 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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; // these aren't really private, but nor are they really useful to document /** * @private */ var LuxonError = function (_Error) { inherits(LuxonError, _Error); function LuxonError() { classCallCheck(this, LuxonError); return possibleConstructorReturn(this, _Error.apply(this, arguments)); } return LuxonError; }(Error); /** * @private */ var InvalidDateTimeError = function (_LuxonError) { inherits(InvalidDateTimeError, _LuxonError); function InvalidDateTimeError(reason) { classCallCheck(this, InvalidDateTimeError); return possibleConstructorReturn(this, _LuxonError.call(this, 'Invalid DateTime: ' + reason)); } return InvalidDateTimeError; }(LuxonError); /** * @private */ var InvalidIntervalError = function (_LuxonError2) { inherits(InvalidIntervalError, _LuxonError2); function InvalidIntervalError(reason) { classCallCheck(this, InvalidIntervalError); return possibleConstructorReturn(this, _LuxonError2.call(this, 'Invalid Interval: ' + reason)); } return InvalidIntervalError; }(LuxonError); /** * @private */ var InvalidDurationError = function (_LuxonError3) { inherits(InvalidDurationError, _LuxonError3); function InvalidDurationError(reason) { classCallCheck(this, InvalidDurationError); return possibleConstructorReturn(this, _LuxonError3.call(this, 'Invalid Duration: ' + reason)); } return InvalidDurationError; }(LuxonError); /** * @private */ var ConflictingSpecificationError = function (_LuxonError4) { inherits(ConflictingSpecificationError, _LuxonError4); function ConflictingSpecificationError() { classCallCheck(this, ConflictingSpecificationError); return possibleConstructorReturn(this, _LuxonError4.apply(this, arguments)); } return ConflictingSpecificationError; }(LuxonError); /** * @private */ var InvalidUnitError = function (_LuxonError5) { inherits(InvalidUnitError, _LuxonError5); function InvalidUnitError(unit) { classCallCheck(this, InvalidUnitError); return possibleConstructorReturn(this, _LuxonError5.call(this, 'Invalid unit ' + unit)); } return InvalidUnitError; }(LuxonError); /** * @private */ var InvalidArgumentError = function (_LuxonError6) { inherits(InvalidArgumentError, _LuxonError6); function InvalidArgumentError() { classCallCheck(this, InvalidArgumentError); return possibleConstructorReturn(this, _LuxonError6.apply(this, arguments)); } return InvalidArgumentError; }(LuxonError); /** * @private */ var ZoneIsAbstractError = function (_LuxonError7) { inherits(ZoneIsAbstractError, _LuxonError7); function ZoneIsAbstractError() { classCallCheck(this, ZoneIsAbstractError); return possibleConstructorReturn(this, _LuxonError7.call(this, 'Zone is an abstract class')); } return ZoneIsAbstractError; }(LuxonError); /* eslint no-unused-vars: "off" */ /** * @interface */ var Zone = function () { function Zone() { classCallCheck(this, Zone); } /** * Returns the offset's common name (such as EST) at the specified timestamp * @abstract * @param {number} ts - Epoch milliseconds for which to get the name * @param {Object} opts - Options to affect the format * @param {string} opts.format - What style of offset to return. Accepts 'long' or 'short'. * @param {string} opts.locale - What locale to return the offset name in. * @return {string} */ Zone.prototype.offsetName = function offsetName(ts, opts) { throw new ZoneIsAbstractError(); }; /** * Return the offset in minutes for this zone at the specified timestamp. * @abstract * @param {number} ts - Epoch milliseconds for which to compute the offset * @return {number} */ Zone.prototype.offset = function offset(ts) { throw new ZoneIsAbstractError(); }; /** * Return whether this Zone is equal to another zoner * @abstract * @param {Zone} otherZone - the zone to compare * @return {boolean} */ Zone.prototype.equals = function equals(otherZone) { throw new ZoneIsAbstractError(); }; /** * Return whether this Zone is valid. * @abstract * @type {boolean} */ createClass(Zone, [{ key: 'type', /** * The type of zone * @abstract * @type {string} */ get: function get$$1() { throw new ZoneIsAbstractError(); } /** * The name of this zone. * @abstract * @type {string} */ }, { key: 'name', get: function get$$1() { throw new ZoneIsAbstractError(); } /** * Returns whether the offset is known to be fixed for the whole year. * @abstract * @type {boolean} */ }, { key: 'universal', get: function get$$1() { throw new ZoneIsAbstractError(); } }, { key: 'isValid', get: function get$$1() { throw new ZoneIsAbstractError(); } }]); return Zone; }(); var singleton = null; var LocalZone = function (_Zone) { inherits(LocalZone, _Zone); function LocalZone() { classCallCheck(this, LocalZone); return possibleConstructorReturn(this, _Zone.apply(this, arguments)); } LocalZone.prototype.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale); }; LocalZone.prototype.offset = function offset(ts) { return -new Date(ts).getTimezoneOffset(); }; LocalZone.prototype.equals = function equals(otherZone) { return otherZone.type === 'local'; }; createClass(LocalZone, [{ key: 'type', get: function get$$1() { return 'local'; } }, { key: 'name', get: function get$$1() { if (hasIntl()) { return new Intl.DateTimeFormat().resolvedOptions().timeZone; } else return 'local'; } }, { key: 'universal', get: function get$$1() { return false; } }, { key: 'isValid', get: function get$$1() { return true; } }], [{ key: 'instance', get: function get$$1() { if (singleton === null) { singleton = new LocalZone(); } return singleton; } }]); return LocalZone; }(Zone); var dtfCache = {}; function makeDTF(zone) { if (!dtfCache[zone]) { dtfCache[zone] = new Intl.DateTimeFormat('en-US', { hour12: false, timeZone: zone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit' }); } return dtfCache[zone]; } var typeToPos = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 }; function hackyOffset(dtf, date) { var formatted = dtf.format(date).replace(/\u200E/g, ''), parsed = /(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(formatted), fMonth = parsed[1], fDay = parsed[2], fYear = parsed[3], fHour = parsed[4], fMinute = parsed[5], fSecond = parsed[6]; return [fYear, fMonth, fDay, fHour, fMinute, fSecond]; } function partsOffset(dtf, date) { var formatted = dtf.formatToParts(date), filled = []; for (var i = 0; i < formatted.length; i++) { var _formatted$i = formatted[i], type = _formatted$i.type, value = _formatted$i.value, pos = typeToPos[type]; if (!isUndefined(pos)) { filled[pos] = parseInt(value, 10); } } return filled; } var IANAZone = function (_Zone) { inherits(IANAZone, _Zone); IANAZone.isValidSpecifier = function isValidSpecifier(s) { return s && s.match(/^[a-z_+-]{1,256}\/[a-z_+-]{1,256}(\/[a-z_+-]{1,256})?$/i); }; IANAZone.isValidZone = function isValidZone(zone) { try { new Intl.DateTimeFormat('en-US', { timeZone: zone }).format(); return true; } catch (e) { return false; } }; // Etc/GMT+8 -> 480 IANAZone.parseGMTOffset = function parseGMTOffset(specifier) { if (specifier) { var match = specifier.match(/^Etc\/GMT([+-]\d{1,2})$/i); if (match) { return 60 * parseInt(match[1]); } } return null; }; function IANAZone(name) { classCallCheck(this, IANAZone); var _this = possibleConstructorReturn(this, _Zone.call(this)); _this.zoneName = name; _this.valid = IANAZone.isValidZone(name); return _this; } IANAZone.prototype.offsetName = function offsetName(ts, _ref) { var format = _ref.format, locale = _ref.locale; return parseZoneInfo(ts, format, locale, this.zoneName); }; IANAZone.prototype.offset = function offset(ts) { var date = new Date(ts), dtf = makeDTF(this.zoneName), _ref2 = dtf.formatToParts ? partsOffset(dtf, date) : hackyOffset(dtf, date), fYear = _ref2[0], fMonth = _ref2[1], fDay = _ref2[2], fHour = _ref2[3], fMinute = _ref2[4], fSecond = _ref2[5], asUTC = Date.UTC(fYear, fMonth - 1, fDay, fHour, fMinute, fSecond); var asTS = date.valueOf(); asTS -= asTS % 1000; return (asUTC - asTS) / (60 * 1000); }; IANAZone.prototype.equals = function equals(otherZone) { return otherZone.type === 'iana' && otherZone.zoneName === this.zoneName; }; createClass(IANAZone, [{ key: 'type', get: function get$$1() { return 'iana'; } }, { key: 'name', get: function get$$1() { return this.zoneName; } }, { key: 'universal', get: function get$$1() { return false; } }, { key: 'isValid', get: function get$$1() { return this.valid; } }]); return IANAZone; }(Zone); var singleton$1 = null; function hoursMinutesOffset(z) { var hours = Math.trunc(z.fixed / 60), minutes = Math.abs(z.fixed % 60), sign = hours > 0 ? '+' : '-', base = sign + Math.abs(hours); return minutes > 0 ? base + ':' + padStart(minutes, 2) : base; } var FixedOffsetZone = function (_Zone) { inherits(FixedOffsetZone, _Zone); FixedOffsetZone.instance = function instance(offset) { return offset === 0 ? FixedOffsetZone.utcInstance : new FixedOffsetZone(offset); }; FixedOffsetZone.parseSpecifier = function parseSpecifier(s) { if (s) { var r = s.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i); if (r) { return new FixedOffsetZone(signedOffset(r[1], r[2])); } } return null; }; createClass(FixedOffsetZone, null, [{ key: 'utcInstance', get: function get$$1() { if (singleton$1 === null) { singleton$1 = new FixedOffsetZone(0); } return singleton$1; } }]); function FixedOffsetZone(offset) { classCallCheck(this, FixedOffsetZone); var _this = possibleConstructorReturn(this, _Zone.call(this)); _this.fixed = offset; return _this; } FixedOffsetZone.prototype.offsetName = function offsetName() { return this.name; }; FixedOffsetZone.prototype.offset = function offset() { return this.fixed; }; FixedOffsetZone.prototype.equals = function equals(otherZone) { return otherZone.type === 'fixed' && otherZone.fixed === this.fixed; }; createClass(FixedOffsetZone, [{ key: 'type', get: function get$$1() { return 'fixed'; } }, { key: 'name', get: function get$$1() { return this.fixed === 0 ? 'UTC' : 'UTC' + hoursMinutesOffset(this); } }, { key: 'universal', get: function get$$1() { return true; } }, { key: 'isValid', get: function get$$1() { return true; } }]); return FixedOffsetZone; }(Zone); var singleton$2 = null; var InvalidZone = function (_Zone) { inherits(InvalidZone, _Zone); function InvalidZone() { classCallCheck(this, InvalidZone); return possibleConstructorReturn(this, _Zone.apply(this, arguments)); } InvalidZone.prototype.offsetName = function offsetName() { return null; }; InvalidZone.prototype.offset = function offset() { return NaN; }; InvalidZone.prototype.equals = function equals() { return false; }; createClass(InvalidZone, [{ key: 'type', get: function get$$1() { return 'invalid'; } }, { key: 'name', get: function get$$1() { return null; } }, { key: 'universal', get: function get$$1() { return false; } }, { key: 'isValid', get: function get$$1() { return false; } }], [{ key: 'instance', get: function get$$1() { if (singleton$2 === null) { singleton$2 = new InvalidZone(); } return singleton$2; } }]); return InvalidZone; }(Zone); /** * @private */ function normalizeZone(input, defaultZone) { var offset = void 0; if (isUndefined(input) || input === null) { return defaultZone; } else if (input instanceof Zone) { return input; } else if (isString(input)) { var lowered = input.toLowerCase(); if (lowered === 'local') return LocalZone.instance;else if (lowered === 'utc' || lowered === 'gmt') return FixedOffsetZone.utcInstance;else if ((offset = IANAZone.parseGMTOffset(input)) != null) { // handle Etc/GMT-4, which V8 chokes on return FixedOffsetZone.instance(offset); } else if (IANAZone.isValidSpecifier(lowered)) return new IANAZone(input);else return FixedOffsetZone.parseSpecifier(lowered) || InvalidZone.instance; } else if (isNumber(input)) { return FixedOffsetZone.instance(input); } else if ((typeof input === 'undefined' ? 'undefined' : _typeof(input)) === 'object' && input.offset) { // This is dumb, but the instanceof check above doesn't seem to really work // so we're duck checking it return input; } else { return InvalidZone.instance; } } var now = function now() { return Date.now(); }; var defaultZone = null; var defaultLocale = null; var defaultNumberingSystem = null; var defaultOutputCalendar = null; var throwOnInvalid = false; /** * Settings contains static getters and setters that control Luxon's overall behavior. Luxon is a simple library with few options, but the ones it does have live here. */ var Settings = function () { function Settings() { classCallCheck(this, Settings); } /** * Reset Luxon's global caches. Should only be necessary in testing scenarios. * @return {void} */ Settings.resetCaches = function resetCaches() { Locale.resetCache(); }; createClass(Settings, null, [{ key: 'now', /** * Get the callback for returning the current timestamp. * @type {function} */ get: function get$$1() { return now; } /** * Set the callback for returning the current timestamp. * @type {function} */ , set: function set$$1(n) { now = n; } /** * Get the default time zone to create DateTimes in. * @type {string} */ }, { key: 'defaultZoneName', get: function get$$1() { return (defaultZone || LocalZone.instance).name; } /** * Set the default time zone to create DateTimes in. Does not affect existing instances. * @type {string} */ , set: function set$$1(z) { if (!z) { defaultZone = null; } else { defaultZone = normalizeZone(z); } } /** * Get the default time zone object to create DateTimes in. Does not affect existing instances. * @type {Zone} */ }, { key: 'defaultZone', get: function get$$1() { return defaultZone || LocalZone.instance; } /** * Get the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: 'defaultLocale', get: function get$$1() { return defaultLocale; } /** * Set the default locale to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set$$1(locale) { defaultLocale = locale; } /** * Get the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: 'defaultNumberingSystem', get: function get$$1() { return defaultNumberingSystem; } /** * Set the default numbering system to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set$$1(numberingSystem) { defaultNumberingSystem = numberingSystem; } /** * Get the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ }, { key: 'defaultOutputCalendar', get: function get$$1() { return defaultOutputCalendar; } /** * Set the default output calendar to create DateTimes with. Does not affect existing instances. * @type {string} */ , set: function set$$1(outputCalendar) { defaultOutputCalendar = outputCalendar; } /** * Get whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ }, { key: 'throwOnInvalid', get: function get$$1() { return throwOnInvalid; } /** * Set whether Luxon will throw when it encounters invalid DateTimes, Durations, or Intervals * @type {boolean} */ , set: function set$$1(t) { throwOnInvalid = t; } }]); return Settings; }(); function stringifyTokens(splits, tokenToString) { var s = ''; for (var _iterator = splits, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var token = _ref; if (token.literal) { s += token.val; } else { s += tokenToString(token.val); } } return s; } var tokenToObject = { D: DATE_SHORT, DD: DATE_MED, DDD: DATE_FULL, DDDD: DATE_HUGE, t: TIME_SIMPLE, tt: TIME_WITH_SECONDS, ttt: TIME_WITH_SHORT_OFFSET, tttt: TIME_WITH_LONG_OFFSET, T: TIME_24_SIMPLE, TT: TIME_24_WITH_SECONDS, TTT: TIME_24_WITH_SHORT_OFFSET, TTTT: TIME_24_WITH_LONG_OFFSET, f: DATETIME_SHORT, ff: DATETIME_MED, fff: DATETIME_FULL, ffff: DATETIME_HUGE, F: DATETIME_SHORT_WITH_SECONDS, FF: DATETIME_MED_WITH_SECONDS, FFF: DATETIME_FULL_WITH_SECONDS, FFFF: DATETIME_HUGE_WITH_SECONDS }; /** * @private */ var Formatter = function () { Formatter.create = function create(locale) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var formatOpts = Object.assign({}, { round: true }, opts); return new Formatter(locale, formatOpts); }; Formatter.parseFormat = function parseFormat(fmt) { var current = null, currentFull = '', bracketed = false; var splits = []; for (var i = 0; i < fmt.length; i++) { var c = fmt.charAt(i); if (c === "'") { if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } current = null; currentFull = ''; bracketed = !bracketed; } else if (bracketed) { currentFull += c; } else if (c === current) { currentFull += c; } else { if (currentFull.length > 0) { splits.push({ literal: false, val: currentFull }); } currentFull = c; current = c; } } if (currentFull.length > 0) { splits.push({ literal: bracketed, val: currentFull }); } return splits; }; function Formatter(locale, formatOpts) { classCallCheck(this, Formatter); this.opts = formatOpts; this.loc = locale; this.systemLoc = null; } Formatter.prototype.formatWithSystemDefault = function formatWithSystemDefault(dt, opts) { if (this.systemLoc === null) { this.systemLoc = this.loc.redefaultToSystem(); } var df = this.systemLoc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); }; Formatter.prototype.formatDateTime = function formatDateTime(dt) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.format(); }; Formatter.prototype.formatDateTimeParts = function formatDateTimeParts(dt) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.formatToParts(); }; Formatter.prototype.resolvedOptions = function resolvedOptions(dt) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var df = this.loc.dtFormatter(dt, Object.assign({}, this.opts, opts)); return df.resolvedOptions(); }; Formatter.prototype.num = function num(n) { var p = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; // we get some perf out of doing this here, annoyingly if (this.opts.forceSimple) { return padStart(n, p); } var opts = Object.assign({}, this.opts); if (p > 0) { opts.padTo = p; } return this.loc.numberFormatter(opts).format(n); }; Formatter.prototype.formatDateTimeFromString = function formatDateTimeFromString(dt, fmt) { var _this = this; var knownEnglish = this.loc.listingMode() === 'en'; var string = function string(opts, extract) { return _this.loc.extract(dt, opts, extract); }, formatOffset = function formatOffset(opts) { if (dt.isOffsetFixed && dt.offset === 0 && opts.allowZ) { return 'Z'; } var hours = Math.trunc(dt.offset / 60), minutes = Math.abs(dt.offset % 60), sign = hours >= 0 ? '+' : '-', base = '' + sign + Math.abs(hours); switch (opts.format) { case 'short': return '' + sign + _this.num(Math.abs(hours), 2) + ':' + _this.num(minutes, 2); case 'narrow': return minutes > 0 ? base + ':' + minutes : base; case 'techie': return '' + sign + _this.num(Math.abs(hours), 2) + _this.num(minutes, 2); default: throw new RangeError('Value format ' + opts.format + ' is out of range for property format'); } }, meridiem = function meridiem() { return knownEnglish ? meridiemForDateTime(dt) : string({ hour: 'numeric', hour12: true }, 'dayperiod'); }, month = function month(length, standalone) { return knownEnglish ? monthForDateTime(dt, length) : string(standalone ? { month: length } : { month: length, day: 'numeric' }, 'month'); }, weekday = function weekday(length, standalone) { return knownEnglish ? weekdayForDateTime(dt, length) : string(standalone ? { weekday: length } : { weekday: length, month: 'long', day: 'numeric' }, 'weekday'); }, maybeMacro = function maybeMacro(token) { var macro = tokenToObject[token]; if (macro) { return _this.formatWithSystemDefault(dt, macro); } else { return token; } }, era = function era(length) { return knownEnglish ? eraForDateTime(dt, length) : string({ era: length }, 'era'); }, tokenToString = function tokenToString(token) { var outputCal = _this.loc.outputCalendar; // Where possible: http://cldr.unicode.org/translation/date-time#TOC-Stand-Alone-vs.-Format-Styles switch (token) { // ms case 'S': return _this.num(dt.millisecond); case 'u': // falls through case 'SSS': return _this.num(dt.millisecond, 3); // seconds case 's': return _this.num(dt.second); case 'ss': return _this.num(dt.second, 2); // minutes case 'm': return _this.num(dt.minute); case 'mm': return _this.num(dt.minute, 2); // hours case 'h': return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12); case 'hh': return _this.num(dt.hour % 12 === 0 ? 12 : dt.hour % 12, 2); case 'H': return _this.num(dt.hour); case 'HH': return _this.num(dt.hour, 2); // offset case 'Z': // like +6 return formatOffset({ format: 'narrow', allowZ: _this.opts.allowZ }); case 'ZZ': // like +06:00 return formatOffset({ format: 'short', allowZ: _this.opts.allowZ }); case 'ZZZ': // like +0600 return formatOffset({ format: 'techie', allowZ: false }); case 'ZZZZ': // like EST return dt.offsetNameShort; case 'ZZZZZ': // like Eastern Standard Time return dt.offsetNameLong; // zone case 'z': // like America/New_York return dt.zoneName; // meridiems case 'a': return meridiem(); // dates case 'd': return outputCal ? string({ day: 'numeric' }, 'day') : _this.num(dt.day); case 'dd': return outputCal ? string({ day: '2-digit' }, 'day') : _this.num(dt.day, 2); // weekdays - standalone case 'c': // like 1 return _this.num(dt.weekday); case 'ccc': // like 'Tues' return weekday('short', true); case 'cccc': // like 'Tuesday' return weekday('long', true); case 'ccccc': // like 'T' return weekday('narrow', true); // weekdays - format case 'E': // like 1 return _this.num(dt.weekday); case 'EEE': // like 'Tues' return weekday('short', false); case 'EEEE': // like 'Tuesday' return weekday('long', false); case 'EEEEE': // like 'T' return weekday('narrow', false); // months - standalone case 'L': // like 1 return outputCal ? string({ month: 'numeric', day: 'numeric' }, 'month') : _this.num(dt.month); case 'LL': // like 01, doesn't seem to work return outputCal ? string({ month: '2-digit', day: 'numeric' }, 'month') : _this.num(dt.month, 2); case 'LLL': // like Jan return month('short', true); case 'LLLL': // like January return month('long', true); case 'LLLLL': // like J return month('narrow', true); // months - format case 'M': // like 1 return outputCal ? string({ month: 'numeric' }, 'month') : _this.num(dt.month); case 'MM': // like 01 return outputCal ? string({ month: '2-digit' }, 'month') : _this.num(dt.month, 2); case 'MMM': // like Jan return month('short', false); case 'MMMM': // like January return month('long', false); case 'MMMMM': // like J return month('narrow', false); // years case 'y': // like 2014 return outputCal ? string({ year: 'numeric' }, 'year') : _this.num(dt.year); case 'yy': // like 14 return outputCal ? string({ year: '2-digit' }, 'year') : _this.num(dt.year.toString().slice(-2), 2); case 'yyyy': // like 0012 return outputCal ? string({ year: 'numeric' }, 'year') : _this.num(dt.year, 4); case 'yyyyyy': // like 000012 return outputCal ? string({ year: 'numeric' }, 'year') : _this.num(dt.year, 6); // eras case 'G': // like AD return era('short'); case 'GG': // like Anno Domini return era('long'); case 'GGGGG': return era('narrow'); case 'kk': return _this.num(dt.weekYear.toString().slice(-2), 2); case 'kkkk': return _this.num(dt.weekYear, 4); case 'W': return _this.num(dt.weekNumber); case 'WW': return _this.num(dt.weekNumber, 2); case 'o': return _this.num(dt.ordinal); case 'ooo': return _this.num(dt.ordinal, 3); case 'q': // like 1 return _this.num(dt.quarter); case 'qq': // like 01 return _this.num(dt.quarter, 2); default: return maybeMacro(token); } }; return stringifyTokens(Formatter.parseFormat(fmt), tokenToString); }; Formatter.prototype.formatDurationFromString = function formatDurationFromString(dur, fmt) { var _this2 = this; var tokenToField = function tokenToField(token) { switch (token[0]) { case 'S': return 'millisecond'; case 's': return 'second'; case 'm': return 'minute'; case 'h': return 'hour'; case 'd': return 'day'; case 'M': return 'month'; case 'y': return 'year'; default: return null; } }, tokenToString = function tokenToString(lildur) { return function (token) { var mapped = tokenToField(token); if (mapped) { return _this2.num(lildur.get(mapped), token.length); } else { return token; } }; }, tokens = Formatter.parseFormat(fmt), realTokens = tokens.reduce(function (found, _ref2) { var literal = _ref2.literal, val = _ref2.val; return literal ? found : found.concat(val); }, []), collapsed = dur.shiftTo.apply(dur, realTokens.map(tokenToField).filter(function (t) { return t; })); return stringifyTokens(tokens, tokenToString(collapsed)); }; return Formatter; }(); var sysLocaleCache = null; function systemLocale() { if (sysLocaleCache) { return sysLocaleCache; } else if (hasIntl()) { var computedSys = new Intl.DateTimeFormat().resolvedOptions().locale; // node sometimes defaults to "und". Override that because that is dumb sysLocaleCache = computedSys === 'und' ? 'en-US' : computedSys; return sysLocaleCache; } else { sysLocaleCache = 'en-US'; return sysLocaleCache; } } function intlConfigString(locale, numberingSystem, outputCalendar) { if (hasIntl()) { locale = Array.isArray(locale) ? locale : [locale]; if (outputCalendar || numberingSystem) { locale = locale.map(function (l) { l += '-u'; if (outputCalendar) { l += '-ca-' + outputCalendar; } if (numberingSystem) { l += '-nu-' + numberingSystem; } return l; }); } return locale; } else { return []; } } function mapMonths(f) { var ms = []; for (var i = 1; i <= 12; i++) { var dt = DateTime.utc(2016, i, 1); ms.push(f(dt)); } return ms; } function mapWeekdays(f) { var ms = []; for (var i = 1; i <= 7; i++) { var dt = DateTime.utc(2016, 11, 13 + i); ms.push(f(dt)); } return ms; } function listStuff(loc, length, defaultOK, englishFn, intlFn) { var mode = loc.listingMode(defaultOK); if (mode === 'error') { return null; } else if (mode === 'en') { return englishFn(length); } else { return intlFn(length); } } function supportsFastNumbers(loc) { if (loc.numberingSystem && loc.numberingSystem !== 'latn') { return false; } else { return loc.numberingSystem === 'latn' || !loc.locale || loc.locale.startsWith('en') || hasIntl() && Intl.DateTimeFormat(loc.intl).resolvedOptions().numberingSystem === 'latn'; } } /** * @private */ var SimpleNumberFormatter = function () { function SimpleNumberFormatter(opts) { classCallCheck(this, SimpleNumberFormatter); this.padTo = opts.padTo || 0; this.round = opts.round || false; this.floor = opts.floor || false; } SimpleNumberFormatter.prototype.format = function format(i) { // to match the browser's numberformatter defaults var fixed = this.floor ? Math.floor(i) : roundTo(i, this.round ? 0 : 3); return padStart(fixed, this.padTo); }; return SimpleNumberFormatter; }(); var IntlNumberFormatter = function () { function IntlNumberFormatter(intl, opts) { classCallCheck(this, IntlNumberFormatter); var intlOpts = { useGrouping: false }; if (opts.padTo > 0) { intlOpts.minimumIntegerDigits = opts.padTo; } if (opts.round) { intlOpts.maximumFractionDigits = 0; } this.floor = opts.floor; this.intl = new Intl.NumberFormat(intl, intlOpts); } IntlNumberFormatter.prototype.format = function format(i) { var fixed = this.floor ? Math.floor(i) : i; return this.intl.format(fixed); }; return IntlNumberFormatter; }(); /** * @private */ var PolyDateFormatter = function () { function PolyDateFormatter(dt, intl, opts) { classCallCheck(this, PolyDateFormatter); this.opts = opts; this.hasIntl = hasIntl(); var z = void 0; if (dt.zone.universal && this.hasIntl) { // Chromium doesn't support fixed-offset zones like Etc/GMT+8 in its formatter, // See https://bugs.chromium.org/p/chromium/issues/detail?id=364374. // So we have to make do. Two cases: // 1. The format options tell us to show the zone. We can't do that, so the best // we can do is format the date in UTC. // 2. The format options don't tell us to show the zone. Then we can adjust them // the time and tell the formatter to show it to us in UTC, so that the time is right // and the bad zone doesn't show up. // We can clean all this up when Chrome fixes this. z = 'UTC'; if (opts.timeZoneName) { this.dt = dt; } else { this.dt = dt.offset === 0 ? dt : DateTime.fromMillis(dt.ts + dt.offset * 60 * 1000); } } else if (dt.zone.type === 'local') { this.dt = dt; } else { this.dt = dt; z = dt.zone.name; } if (this.hasIntl) { var realIntlOpts = Object.assign({}, this.opts); if (z) { realIntlOpts.timeZone = z; } this.dtf = new Intl.DateTimeFormat(intl, realIntlOpts); } } PolyDateFormatter.prototype.format = function format() { if (this.hasIntl) { return this.dtf.format(this.dt.toJSDate()); } else { var tokenFormat = formatString(this.opts), loc = Locale.create('en-US'); return Formatter.create(loc).formatDateTimeFromString(this.dt, tokenFormat); } }; PolyDateFormatter.prototype.formatToParts = function formatToParts() { if (this.hasIntl && hasFormatToParts()) { return this.dtf.formatToParts(this.dt.toJSDate()); } else { // This is kind of a cop out. We actually could do this for English. However, we couldn't do it for intl strings // and IMO it's too weird to have an uncanny valley like that return []; } }; PolyDateFormatter.prototype.resolvedOptions = function resolvedOptions() { if (this.hasIntl) { return this.dtf.resolvedOptions(); } else { return { locale: 'en-US', numberingSystem: 'latn', outputCalendar: 'gregory' }; } }; return PolyDateFormatter; }(); /** * @private */ var Locale = function () { Locale.fromOpts = function fromOpts(opts) { return Locale.create(opts.locale, opts.numberingSystem, opts.outputCalendar, opts.defaultToEN); }; Locale.create = function create(locale, numberingSystem, outputCalendar) { var defaultToEN = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var specifiedLocale = locale || Settings.defaultLocale, // the system locale is useful for human readable strings but annoying for parsing/formatting known formats localeR = specifiedLocale || (defaultToEN ? 'en-US' : systemLocale()), numberingSystemR = numberingSystem || Settings.defaultNumberingSystem, outputCalendarR = outputCalendar || Settings.defaultOutputCalendar; return new Locale(localeR, numberingSystemR, outputCalendarR, specifiedLocale); }; Locale.resetCache = function resetCache() { sysLocaleCache = null; }; Locale.fromObject = function fromObject() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, locale = _ref.locale, numberingSystem = _ref.numberingSystem, outputCalendar = _ref.outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar); }; function Locale(locale, numbering, outputCalendar, specifiedLocale) { classCallCheck(this, Locale); this.locale = locale; this.numberingSystem = numbering; this.outputCalendar = outputCalendar; this.intl = intlConfigString(this.locale, this.numberingSystem, this.outputCalendar); this.weekdaysCache = { format: {}, standalone: {} }; this.monthsCache = { format: {}, standalone: {} }; this.meridiemCache = null; this.eraCache = {}; this.specifiedLocale = specifiedLocale; this.fastNumbersCached = null; } // todo: cache me Locale.prototype.listingMode = function listingMode() { var defaultOK = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; var intl = hasIntl(), hasFTP = intl && hasFormatToParts(), isActuallyEn = this.locale === 'en' || this.locale.toLowerCase() === 'en-us' || intl && Intl.DateTimeFormat(this.intl).resolvedOptions().locale.startsWith('en-us'), hasNoWeirdness = (this.numberingSystem === null || this.numberingSystem === 'latn') && (this.outputCalendar === null || this.outputCalendar === 'gregory'); if (!hasFTP && !(isActuallyEn && hasNoWeirdness) && !defaultOK) { return 'error'; } else if (!hasFTP || isActuallyEn && hasNoWeirdness) { return 'en'; } else { return 'intl'; } }; Locale.prototype.clone = function clone(alts) { if (!alts || Object.getOwnPropertyNames(alts).length === 0) { return this; } else { return Locale.create(alts.locale || this.specifiedLocale, alts.numberingSystem || this.numberingSystem, alts.outputCalendar || this.outputCalendar, alts.defaultToEN || false); } }; Locale.prototype.redefaultToEN = function redefaultToEN() { var alts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return this.clone(Object.assign({}, alts, { defaultToEN: true })); }; Locale.prototype.redefaultToSystem = function redefaultToSystem() { var alts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return this.clone(Object.assign({}, alts, { defaultToEN: false })); }; Locale.prototype.months = function months$$1(length) { var _this = this; var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var defaultOK = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return listStuff(this, length, defaultOK, months, function () { var intl = format ? { month: length, day: 'numeric' } : { month: length }, formatStr = format ? 'format' : 'standalone'; if (!_this.monthsCache[formatStr][length]) { _this.monthsCache[formatStr][length] = mapMonths(function (dt) { return _this.extract(dt, intl, 'month'); }); } return _this.monthsCache[formatStr][length]; }); }; Locale.prototype.weekdays = function weekdays$$1(length) { var _this2 = this; var format = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var defaultOK = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; return listStuff(this, length, defaultOK, weekdays, function () { var intl = format ? { weekday: length, year: 'numeric', month: 'long', day: 'numeric' } : { weekday: length }, formatStr = format ? 'format' : 'standalone'; if (!_this2.weekdaysCache[formatStr][length]) { _this2.weekdaysCache[formatStr][length] = mapWeekdays(function (dt) { return _this2.extract(dt, intl, 'weekday'); }); } return _this2.weekdaysCache[formatStr][length]; }); }; Locale.prototype.meridiems = function meridiems$$1() { var _this3 = this; var defaultOK = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; return listStuff(this, undefined, defaultOK, function () { return meridiems; }, function () { // In theory there could be aribitrary day periods. We're gonna assume there are exactly two // for AM and PM. This is probably wrong, but it's makes parsing way easier. if (!_this3.meridiemCache) { var intl = { hour: 'numeric', hour12: true }; _this3.meridiemCache = [DateTime.utc(2016, 11, 13, 9), DateTime.utc(2016, 11, 13, 19)].map(function (dt) { return _this3.extract(dt, intl, 'dayperiod'); }); } return _this3.meridiemCache; }); }; Locale.prototype.eras = function eras$$1(length) { var _this4 = this; var defaultOK = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; return listStuff(this, length, defaultOK, eras, function () { var intl = { era: length }; // This is utter bullshit. Different calendars are going to define eras totally differently. What I need is the minimum set of dates // to definitely enumerate them. if (!_this4.eraCache[length]) { _this4.eraCache[length] = [DateTime.utc(-40, 1, 1), DateTime.utc(2017, 1, 1)].map(function (dt) { return _this4.extract(dt, intl, 'era'); }); } return _this4.eraCache[length]; }); }; Locale.prototype.extract = function extract(dt, intlOpts, field) { var df = this.dtFormatter(dt, intlOpts), results = df.formatToParts(), matching = results.find(function (m) { return m.type.toLowerCase() === field; }); return matching ? matching.value : null; }; Locale.prototype.numberFormatter = function numberFormatter() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; // this forcesimple option is never used (the only caller short-circuits on it, but it seems safer to leave) // (in contrast, the rest of the condition is used heavily) if (opts.forceSimple || this.fastNumbers || !hasIntl()) { return new SimpleNumberFormatter(opts); } else { return new IntlNumberFormatter(this.intl, opts); } }; Locale.prototype.dtFormatter = function dtFormatter(dt) { var intlOpts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new PolyDateFormatter(dt, this.intl, intlOpts); }; Locale.prototype.equals = function equals(other) { return this.locale === other.locale && this.numberingSystem === other.numberingSystem && this.outputCalendar === other.outputCalendar; }; createClass(Locale, [{ key: 'fastNumbers', get: function get$$1() { if (this.fastNumbersCached == null) { this.fastNumbersCached = supportsFastNumbers(this); } return this.fastNumbersCached; } }]); return Locale; }(); /* * This file handles parsing for well-specified formats. Here's how it works: * Two things go into parsing: a regex to match with and an extractor to take apart the groups in the match. * An extractor is just a function that takes a regex match array and returns a { year: ..., month: ... } object * parse() does the work of executing the regex and applying the extractor. It takes multiple regex/extractor pairs to try in sequence. * Extractors can take a "cursor" representing the offset in the match to look at. This makes it easy to combine extractors. * combineExtractors() does the work of combining them, keeping track of the cursor through multiple extractions. * Some extractions are super dumb and simpleParse and fromStrings help DRY them. */ function combineRegexes() { for (var _len = arguments.length, regexes = Array(_len), _key = 0; _key < _len; _key++) { regexes[_key] = arguments[_key]; } var full = regexes.reduce(function (f, r) { return f + r.source; }, ''); return RegExp('^' + full + '$'); } function combineExtractors() { for (var _len2 = arguments.length, extractors = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { extractors[_key2] = arguments[_key2]; } return function (m) { return extractors.reduce(function (_ref, ex) { var mergedVals = _ref[0], mergedZone = _ref[1], cursor = _ref[2]; var _ex = ex(m, cursor), val = _ex[0], zone = _ex[1], next = _ex[2]; return [Object.assign(mergedVals, val), mergedZone || zone, next]; }, [{}, null, 1]).slice(0, 2); }; } function parse(s) { if (s == null) { return [null, null]; } for (var _len3 = arguments.length, patterns = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { patterns[_key3 - 1] = arguments[_key3]; } for (var _iterator = patterns, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref3; if (_isArray) { if (_i >= _iterator.length) break; _ref3 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref3 = _i.value; } var _ref2 = _ref3; var regex = _ref2[0]; var extractor = _ref2[1]; var m = regex.exec(s); if (m) { return extractor(m); } } return [null, null]; } function simpleParse() { for (var _len4 = arguments.length, keys = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { keys[_key4] = arguments[_key4]; } return function (match, cursor) { var ret = {}; var i = void 0; for (i = 0; i < keys.length; i++) { ret[keys[i]] = parseInt(match[cursor + i]); } return [ret, null, cursor + i]; }; } // ISO and SQL parsing var offsetRegex = /(?:(Z)|([+-]\d\d)(?::?(\d\d))?)/; var isoTimeBaseRegex = /(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,9}))?)?)?/; var isoTimeRegex = RegExp('' + isoTimeBaseRegex.source + offsetRegex.source + '?'); var isoTimeExtensionRegex = RegExp('(?:T' + isoTimeRegex.source + ')?'); var isoYmdRegex = /([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/; var isoWeekRegex = /(\d{4})-?W(\d\d)-?(\d)/; var isoOrdinalRegex = /(\d{4})-?(\d{3})/; var extractISOWeekData = simpleParse('weekYear', 'weekNumber', 'weekDay'); var extractISOOrdinalData = simpleParse('year', 'ordinal'); var sqlYmdRegex = /(\d{4})-(\d\d)-(\d\d)/; var sqlTimeRegex = RegExp(isoTimeBaseRegex.source + ' ?(?:' + offsetRegex.source + '|([a-zA-Z_]{1,256}/[a-zA-Z_]{1,256}))?'); var sqlTimeExtensionRegex = RegExp('(?: ' + sqlTimeRegex.source + ')?'); function extractISOYmd(match, cursor) { var item = { year: parseInt(match[cursor]), month: parseInt(match[cursor + 1]) || 1, day: parseInt(match[cursor + 2]) || 1 }; return [item, null, cursor + 3]; } function extractISOTime(match, cursor) { var item = { hour: parseInt(match[cursor]) || 0, minute: parseInt(match[cursor + 1]) || 0, second: parseInt(match[cursor + 2]) || 0, millisecond: parseMillis(match[cursor + 3]) }; return [item, null, cursor + 4]; } function extractISOOffset(match, cursor) { var local = !match[cursor] && !match[cursor + 1], fullOffset = signedOffset(match[cursor + 1], match[cursor + 2]), zone = local ? null : FixedOffsetZone.instance(fullOffset); return [{}, zone, cursor + 3]; } function extractIANAZone(match, cursor) { var zone = match[cursor] ? new IANAZone(match[cursor]) : null; return [{}, zone, cursor + 1]; } // ISO duration parsing var isoDuration = /^P(?:(?:(\d{1,9})Y)?(?:(\d{1,9})M)?(?:(\d{1,9})D)?(?:T(?:(\d{1,9})H)?(?:(\d{1,9})M)?(?:(\d{1,9})(?:[.,](\d{1,9}))?S)?)?|(\d{1,9})W)$/; function extractISODuration(match) { var yearStr = match[1], monthStr = match[2], dayStr = match[3], hourStr = match[4], minuteStr = match[5], secondStr = match[6], millisecondsStr = match[7], weekStr = match[8]; return [{ years: parseInt(yearStr), months: parseInt(monthStr), weeks: parseInt(weekStr), days: parseInt(dayStr), hours: parseInt(hourStr), minutes: parseInt(minuteStr), seconds: parseInt(secondStr), milliseconds: parseMillis(millisecondsStr) }]; } // These are a little braindead. EDT *should* tell us that we're in, say, America/New_York // and not just that we're in -240 *right now*. But since I don't think these are used that often // I'm just going to ignore that var obsOffsets = { GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = { year: yearStr.length === 2 ? untruncateYear(parseInt(yearStr)) : parseInt(yearStr), month: monthStr.length === 2 ? parseInt(monthStr, 10) : monthsShort.indexOf(monthStr) + 1, day: parseInt(dayStr), hour: parseInt(hourStr), minute: parseInt(minuteStr) }; if (secondStr) result.second = parseInt(secondStr); if (weekdayStr) { result.weekday = weekdayStr.length > 3 ? weekdaysLong.indexOf(weekdayStr) + 1 : weekdaysShort.indexOf(weekdayStr) + 1; } return result; } // RFC 2822/5322 var rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/; function extractRFC2822(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], obsOffset = match[8], milOffset = match[9], offHourStr = match[10], offMinuteStr = match[11], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); var offset = void 0; if (obsOffset) { offset = obsOffsets[obsOffset]; } else if (milOffset) { offset = 0; } else { offset = signedOffset(offHourStr, offMinuteStr); } return [result, new FixedOffsetZone(offset)]; } function preprocessRFC2822(s) { // Remove comments and folding whitespace and replace multiple-spaces with a single space return s.replace(/\([^)]*\)|[\n\t]/g, ' ').replace(/(\s\s+)/g, ' ').trim(); } // http date var rfc1123 = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/; var rfc850 = /^(Monday|Tuesday|Wedsday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/; var ascii = /^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/; function extractRFC1123Or850(match) { var weekdayStr = match[1], dayStr = match[2], monthStr = match[3], yearStr = match[4], hourStr = match[5], minuteStr = match[6], secondStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } function extractASCII(match) { var weekdayStr = match[1], monthStr = match[2], dayStr = match[3], hourStr = match[4], minuteStr = match[5], secondStr = match[6], yearStr = match[7], result = fromStrings(weekdayStr, yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr); return [result, FixedOffsetZone.utcInstance]; } /** * @private */ function parseISODate(s) { return parse(s, [combineRegexes(isoYmdRegex, isoTimeExtensionRegex), combineExtractors(extractISOYmd, extractISOTime, extractISOOffset)], [combineRegexes(isoWeekRegex, isoTimeExtensionRegex), combineExtractors(extractISOWeekData, extractISOTime, extractISOOffset)], [combineRegexes(isoOrdinalRegex, isoTimeExtensionRegex), combineExtractors(extractISOOrdinalData, extractISOTime)], [combineRegexes(isoTimeRegex), combineExtractors(extractISOTime, extractISOOffset)]); } function parseRFC2822Date(s) { return parse(preprocessRFC2822(s), [rfc2822, extractRFC2822]); } function parseHTTPDate(s) { return parse(s, [rfc1123, extractRFC1123Or850], [rfc850, extractRFC1123Or850], [ascii, extractASCII]); } function parseISODuration(s) { return parse(s, [isoDuration, extractISODuration]); } function parseSQL(s) { return parse(s, [combineRegexes(sqlYmdRegex, sqlTimeExtensionRegex), combineExtractors(extractISOYmd, extractISOTime, extractISOOffset, extractIANAZone)], [combineRegexes(sqlTimeRegex), combineExtractors(extractISOTime, extractISOOffset, extractIANAZone)]); } var INVALID$1 = 'Invalid Duration'; var UNPARSABLE$1 = 'unparsable'; // unit conversion constants var lowOrderMatrix = { weeks: { days: 7, hours: 7 * 24, minutes: 7 * 24 * 60, seconds: 7 * 24 * 60 * 60, milliseconds: 7 * 24 * 60 * 60 * 1000 }, days: { hours: 24, minutes: 24 * 60, seconds: 24 * 60 * 60, milliseconds: 24 * 60 * 60 * 1000 }, hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 }, minutes: { seconds: 60, milliseconds: 60 * 1000 }, seconds: { milliseconds: 1000 } }; var casualMatrix = Object.assign({ years: { months: 12, weeks: 52, days: 365, hours: 365 * 24, minutes: 365 * 24 * 60, seconds: 365 * 24 * 60 * 60, milliseconds: 365 * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: 13, days: 91, hours: 91 * 24, minutes: 91 * 24 * 60, milliseconds: 91 * 24 * 60 * 60 * 1000 }, months: { weeks: 4, days: 30, hours: 30 * 24, minutes: 30 * 24 * 60, seconds: 30 * 24 * 60 * 60, milliseconds: 30 * 24 * 60 * 60 * 1000 } }, lowOrderMatrix); var daysInYearAccurate = 146097.0 / 400; var daysInMonthAccurate = 146097.0 / 4800; var accurateMatrix = Object.assign({ years: { months: 12, weeks: daysInYearAccurate / 7, days: daysInYearAccurate, hours: daysInYearAccurate * 24, minutes: daysInYearAccurate * 24 * 60, seconds: daysInYearAccurate * 24 * 60 * 60, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 }, quarters: { months: 3, weeks: daysInYearAccurate / 28, days: daysInYearAccurate / 4, hours: daysInYearAccurate * 24 / 4, minutes: daysInYearAccurate * 24 * 60 / 4, seconds: daysInYearAccurate * 24 * 60 * 60 / 4, milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000 / 4 }, months: { weeks: daysInMonthAccurate / 7, days: daysInMonthAccurate, hours: daysInMonthAccurate * 24, minutes: daysInMonthAccurate * 24 * 60, seconds: daysInMonthAccurate * 24 * 60 * 60, milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000 } }, lowOrderMatrix); // units ordered by size var orderedUnits$1 = ['years', 'quarters', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds']; var reverseUnits = orderedUnits$1.slice(0).reverse(); // clone really means "create another instance just like this one, but with these changes" function clone$1(dur, alts) { var clear = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; // deep merge for vals var conf = { values: clear ? alts.values : Object.assign({}, dur.values, alts.values || {}), loc: dur.loc.clone(alts.loc), conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy }; return new Duration(conf); } // some functions really care about the absolute value of a duration, so combined with // normalize() this tells us whether this duration is positive or negative function isHighOrderNegative(obj) { // only rule is that the highest-order part must be non-negative for (var _iterator = orderedUnits$1, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var k = _ref; if (obj[k]) return obj[k] < 0; } return false; } // NB: mutates parameters function convert(matrix, fromMap, fromUnit, toMap, toUnit) { var conv = matrix[toUnit][fromUnit], added = Math.floor(fromMap[fromUnit] / conv); toMap[toUnit] += added; fromMap[fromUnit] -= added * conv; } // NB: mutates parameters function normalizeValues(matrix, vals) { reverseUnits.reduce(function (previous, current) { if (!isUndefined(vals[current])) { if (previous) { convert(matrix, vals, previous, vals, current); } return current; } else { return previous; } }, null); } /** * @private */ function friendlyDuration(duration) { if (isNumber(duration)) { return Duration.fromMillis(duration); } else if (duration instanceof Duration) { return duration; } else if ((typeof duration === 'undefined' ? 'undefined' : _typeof(duration)) === 'object') { return Duration.fromObject(duration); } else { throw new InvalidArgumentError('Unknown duration argument'); } } /** * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime.plus} to add a Duration object to a DateTime, producing another DateTime. * * Here is a brief overview of commonly used methods and getters in Duration: * * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}. * * **Unit values** See the {@link Duration.years}, {@link Duration.months}, {@link Duration.weeks}, {@link Duration.days}, {@link Duration.hours}, {@link Duration.minutes}, {@link Duration.seconds}, {@link Duration.milliseconds} accessors. * * **Configuration** See {@link Duration.locale} and {@link Duration.numberingSystem} accessors. * * **Transformation** To create new Durations out of old ones use {@link Duration.plus}, {@link Duration.minus}, {@link Duration.normalize}, {@link Duration.set}, {@link Duration.reconfigure}, {@link Duration.shiftTo}, and {@link Duration.negate}. * * **Output** To convert the Duration into other representations, see {@link Duration.as}, {@link Duration.toISO}, {@link Duration.toFormat}, and {@link Duration.toJSON} * * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation. */ var Duration = function () { /** * @private */ function Duration(config) { classCallCheck(this, Duration); var accurate = config.conversionAccuracy === 'longterm' || false; /** * @access private */ this.values = config.values; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.conversionAccuracy = accurate ? 'longterm' : 'casual'; /** * @access private */ this.invalid = config.invalidReason || null; /** * @access private */ this.matrix = accurate ? accurateMatrix : casualMatrix; } /** * Create Duration from a number of milliseconds. * @param {number} count of milliseconds * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ Duration.fromMillis = function fromMillis(count, opts) { return Duration.fromObject(Object.assign({ milliseconds: count }, opts)); }; /** * Create a Duration from a Javascript object with keys like 'years' and 'hours. * If this object is empty then zero milliseconds duration is returned. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.years * @param {number} obj.quarters * @param {number} obj.months * @param {number} obj.weeks * @param {number} obj.days * @param {number} obj.hours * @param {number} obj.minutes * @param {number} obj.seconds * @param {number} obj.milliseconds * @param {string} [obj.locale='en-US'] - the locale to use * @param {string} obj.numberingSystem - the numbering system to use * @param {string} [obj.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ Duration.fromObject = function fromObject(obj) { if (obj == null || (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object') { throw new InvalidArgumentError('Duration.fromObject: argument expected to be an object.'); } return new Duration({ values: normalizeObject(obj, Duration.normalizeUnit, true), loc: Locale.fromObject(obj), conversionAccuracy: obj.conversionAccuracy }); }; /** * Create a Duration from an ISO 8601 duration string. * @param {string} text - text to parse * @param {Object} opts - options for parsing * @param {string} [opts.locale='en-US'] - the locale to use * @param {string} opts.numberingSystem - the numbering system to use * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromISO('P3Y6M4DT12H30M5S').toObject() //=> { years: 3, months: 6, day: 4, hours: 12, minutes: 30, seconds: 5 } * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 } * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 } * @return {Duration} */ Duration.fromISO = function fromISO(text, opts) { var _parseISODuration = parseISODuration(text), parsed = _parseISODuration[0]; if (parsed) { var obj = Object.assign(parsed, opts); return Duration.fromObject(obj); } else { return Duration.invalid(UNPARSABLE$1); } }; /** * Create an invalid Duration. * @param {string} reason - reason this is invalid * @return {Duration} */ Duration.invalid = function invalid(reason) { if (!reason) { throw new InvalidArgumentError('need to specify a reason the Duration is invalid'); } if (Settings.throwOnInvalid) { throw new InvalidDurationError(reason); } else { return new Duration({ invalidReason: reason }); } }; /** * @private */ Duration.normalizeUnit = function normalizeUnit(unit) { var ignoreUnknown = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var normalized = { year: 'years', years: 'years', quarter: 'quarters', quarters: 'quarters', month: 'months', months: 'months', week: 'weeks', weeks: 'weeks', day: 'days', days: 'days', hour: 'hours', hours: 'hours', minute: 'minutes', minutes: 'minutes', second: 'seconds', seconds: 'seconds', millisecond: 'milliseconds', milliseconds: 'milliseconds' }[unit ? unit.toLowerCase() : unit]; if (!ignoreUnknown && !normalized) throw new InvalidUnitError(unit); return normalized; }; /** * Get the locale of a Duration, such 'en-GB' * @type {string} */ /** * Returns a string representation of this Duration formatted according to the specified format string. The duration will be converted to the set of units in the format string using {@link Duration.shiftTo} and the Durations's conversion accuracy setting. You may use these tokens: * * `S` for milliseconds * * `s` for seconds * * `m` for minutes * * `h` for hours * * `d` for days * * `M` for months * * `y` for years * @param {string} fmt - the format string * @param {Object} opts - options * @param {boolean} [opts.floor=true] - floor numerical values * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2" * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000" * @return {string} */ Duration.prototype.toFormat = function toFormat(fmt) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; // reverse-compat since 1.2; we always round down now, never up, and we do it by default. So: // 1. always turn off rounding in the underlying formatter // 2. turn off flooring if either rounding is turned off or flooring is turned off, otherwise leave it on var fmtOpts = Object.assign({}, opts, { floor: true, round: false }); if (opts.round === false || opts.floor === false) { fmtOpts.floor = false; } return this.isValid ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt) : INVALID$1; }; /** * Returns a Javascript object with this Duration's values. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 } * @return {Object} */ Duration.prototype.toObject = function toObject() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return {}; var base = Object.assign({}, this.values); if (opts.includeConfig) { base.conversionAccuracy = this.conversionAccuracy; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; }; /** * Returns an ISO 8601-compliant string representation of this Duration. * @see https://en.wikipedia.org/wiki/ISO_8601#Durations * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S' * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S' * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M' * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M' * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S' * @return {string} */ Duration.prototype.toISO = function toISO() { // we could use the formatter, but this is an easier way to get the minimum string if (!this.isValid) return null; var s = 'P', norm = this.normalize(); // ISO durations are always positive, so take the absolute value norm = isHighOrderNegative(norm.values) ? norm.negate() : norm; if (norm.years > 0) s += norm.years + 'Y'; if (norm.months > 0 || norm.quarters > 0) s += norm.months + norm.quarters * 3 + 'M'; if (norm.days > 0 || norm.weeks > 0) s += norm.days + norm.weeks * 7 + 'D'; if (norm.hours > 0 || norm.minutes > 0 || norm.seconds > 0 || norm.milliseconds > 0) s += 'T'; if (norm.hours > 0) s += norm.hours + 'H'; if (norm.minutes > 0) s += norm.minutes + 'M'; if (norm.seconds > 0 || norm.milliseconds > 0) s += norm.seconds + norm.milliseconds / 1000 + 'S'; return s; }; /** * Returns an ISO 8601 representation of this Duration appropriate for use in JSON. * @return {string} */ Duration.prototype.toJSON = function toJSON() { return this.toISO(); }; /** * Returns an ISO 8601 representation of this Duration appropriate for use in debugging. * @return {string} */ Duration.prototype.toString = function toString() { return this.toISO(); }; /** * Returns an milliseconds value of this Duration. * @return {number} */ Duration.prototype.valueOf = function valueOf() { return this.as('milliseconds'); }; /** * Returns a string representation of this Duration appropriate for the REPL. * @return {string} */ Duration.prototype[customInspectSymbol] = function () { if (this.isValid) { var valsInspect = JSON.stringify(this.toObject()); return 'Duration {\n values: ' + valsInspect + ',\n locale: ' + this.locale + ',\n conversionAccuracy: ' + this.conversionAccuracy + ' }'; } else { return 'Duration { Invalid, reason: ' + this.invalidReason + ' }'; } }; /** * Make this Duration longer by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ Duration.prototype.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration), result = {}; for (var _iterator2 = orderedUnits$1, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref2; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref2 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref2 = _i2.value; } var k = _ref2; var val = dur.get(k) + this.get(k); if (val !== 0) { result[k] = val; } } return clone$1(this, { values: result }, true); }; /** * Make this Duration shorter by the specified amount. Return a newly-constructed Duration. * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @return {Duration} */ Duration.prototype.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return this.plus(dur.negate()); }; /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example Duration.fromObject({years: 2, days: 3}).years //=> 2 * @example Duration.fromObject({years: 2, days: 3}).months //=> 0 * @example Duration.fromObject({years: 2, days: 3}).days //=> 3 * @return {number} */ Duration.prototype.get = function get$$1(unit) { return this[Duration.normalizeUnit(unit)]; }; /** * "Set" the values of specified units. Return a newly-constructed Duration. * @param {Object} values - a mapping of units to numbers * @example dur.set({ years: 2017 }) * @example dur.set({ hours: 8, minutes: 30 }) * @return {Duration} */ Duration.prototype.set = function set$$1(values) { var mixed = Object.assign(this.values, normalizeObject(values, Duration.normalizeUnit)); return clone$1(this, { values: mixed }); }; /** * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration. * @example dur.reconfigure({ locale: 'en-GB' }) * @return {Duration} */ Duration.prototype.reconfigure = function reconfigure() { var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, locale = _ref3.locale, numberingSystem = _ref3.numberingSystem, conversionAccuracy = _ref3.conversionAccuracy; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem }), opts = { loc: loc }; if (conversionAccuracy) { opts.conversionAccuracy = conversionAccuracy; } return clone$1(this, opts); }; /** * Return the length of the duration in the specified unit. * @param {string} unit - a unit such as 'minutes' or 'days' * @example Duration.fromObject({years: 1}).as('days') //=> 365 * @example Duration.fromObject({years: 1}).as('months') //=> 12 * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5 * @return {number} */ Duration.prototype.as = function as(unit) { return this.isValid ? this.shiftTo(unit).get(unit) : NaN; }; /** * Reduce this Duration to its canonical representation in its current units. * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 } * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 } * @return {Duration} */ Duration.prototype.normalize = function normalize() { if (!this.isValid) return this; var neg = isHighOrderNegative(this.values), vals = (neg ? this.negate() : this).toObject(); normalizeValues(this.matrix, vals); var dur = Duration.fromObject(vals); return neg ? dur.negate() : dur; }; /** * Convert this Duration into its representation in a different set of units. * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 } * @return {Duration} */ Duration.prototype.shiftTo = function shiftTo() { for (var _len = arguments.length, units = Array(_len), _key = 0; _key < _len; _key++) { units[_key] = arguments[_key]; } if (!this.isValid) return this; if (units.length === 0) { return this; } units = units.map(function (u) { return Duration.normalizeUnit(u); }); var built = {}, accumulated = {}, vals = this.toObject(); var lastUnit = void 0; normalizeValues(this.matrix, vals); for (var _iterator3 = orderedUnits$1, _isArray3 = Array.isArray(_iterator3), _i3 = 0, _iterator3 = _isArray3 ? _iterator3 : _iterator3[Symbol.iterator]();;) { var _ref4; if (_isArray3) { if (_i3 >= _iterator3.length) break; _ref4 = _iterator3[_i3++]; } else { _i3 = _iterator3.next(); if (_i3.done) break; _ref4 = _i3.value; } var k = _ref4; if (units.indexOf(k) >= 0) { lastUnit = k; var own = 0; // anything we haven't boiled down yet should get boiled to this unit for (var ak in accumulated) { if (accumulated.hasOwnProperty(ak)) { own += this.matrix[ak][k] * accumulated[ak]; accumulated[ak] = 0; } } // plus anything that's already in this unit if (isNumber(vals[k])) { own += vals[k]; } var i = Math.trunc(own); built[k] = i; accumulated[k] = own - i; // plus anything further down the chain that should be rolled up in to this for (var down in vals) { if (orderedUnits$1.indexOf(down) > orderedUnits$1.indexOf(k)) { convert(this.matrix, vals, down, built, k); } } // otherwise, keep it in the wings to boil it later } else if (isNumber(vals[k])) { accumulated[k] = vals[k]; } } // anything leftover becomes the decimal for the last unit if (lastUnit) { for (var key in accumulated) { if (accumulated.hasOwnProperty(key)) { if (accumulated[key] > 0) { built[lastUnit] += key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key]; } } } } return clone$1(this, { values: built }, true); }; /** * Return the negative of this Duration. * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 } * @return {Duration} */ Duration.prototype.negate = function negate() { if (!this.isValid) return this; var negated = {}; for (var _iterator4 = Object.keys(this.values), _isArray4 = Array.isArray(_iterator4), _i4 = 0, _iterator4 = _isArray4 ? _iterator4 : _iterator4[Symbol.iterator]();;) { var _ref5; if (_isArray4) { if (_i4 >= _iterator4.length) break; _ref5 = _iterator4[_i4++]; } else { _i4 = _iterator4.next(); if (_i4.done) break; _ref5 = _i4.value; } var k = _ref5; negated[k] = -this.values[k]; } return clone$1(this, { values: negated }, true); }; /** * Get the years. * @type {number} */ /** * Equality check * Two Durations are equal iff they have the same units and the same values for each unit. * @param {Duration} other * @return {boolean} */ Duration.prototype.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } if (!this.loc.equals(other.loc)) { return false; } for (var _iterator5 = orderedUnits$1, _isArray5 = Array.isArray(_iterator5), _i5 = 0, _iterator5 = _isArray5 ? _iterator5 : _iterator5[Symbol.iterator]();;) { var _ref6; if (_isArray5) { if (_i5 >= _iterator5.length) break; _ref6 = _iterator5[_i5++]; } else { _i5 = _iterator5.next(); if (_i5.done) break; _ref6 = _i5.value; } var u = _ref6; if (this.values[u] !== other.values[u]) { return false; } } return true; }; createClass(Duration, [{ key: 'locale', get: function get$$1() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration * * @type {string} */ }, { key: 'numberingSystem', get: function get$$1() { return this.isValid ? this.loc.numberingSystem : null; } }, { key: 'years', get: function get$$1() { return this.isValid ? this.values.years || 0 : NaN; } /** * Get the quarters. * @type {number} */ }, { key: 'quarters', get: function get$$1() { return this.isValid ? this.values.quarters || 0 : NaN; } /** * Get the months. * @type {number} */ }, { key: 'months', get: function get$$1() { return this.isValid ? this.values.months || 0 : NaN; } /** * Get the weeks * @type {number} */ }, { key: 'weeks', get: function get$$1() { return this.isValid ? this.values.weeks || 0 : NaN; } /** * Get the days. * @type {number} */ }, { key: 'days', get: function get$$1() { return this.isValid ? this.values.days || 0 : NaN; } /** * Get the hours. * @type {number} */ }, { key: 'hours', get: function get$$1() { return this.isValid ? this.values.hours || 0 : NaN; } /** * Get the minutes. * @type {number} */ }, { key: 'minutes', get: function get$$1() { return this.isValid ? this.values.minutes || 0 : NaN; } /** * Get the seconds. * @return {number} */ }, { key: 'seconds', get: function get$$1() { return this.isValid ? this.values.seconds || 0 : NaN; } /** * Get the milliseconds. * @return {number} */ }, { key: 'milliseconds', get: function get$$1() { return this.isValid ? this.values.milliseconds || 0 : NaN; } /** * Returns whether the Duration is invalid. Invalid durations are returned by diff operations * on invalid DateTimes or Intervals. * @return {boolean} */ }, { key: 'isValid', get: function get$$1() { return this.invalidReason === null; } /** * Returns an explanation of why this Duration became invalid, or null if the Duration is valid * @return {string} */ }, { key: 'invalidReason', get: function get$$1() { return this.invalid; } }]); return Duration; }(); var INVALID$2 = 'Invalid Interval'; // checks if the start is equal to or before the end function validateStartEnd(start, end) { return !!start && !!end && start.isValid && end.isValid && start <= end; } /** * An Interval object represents a half-open interval of time, where each endpoint is a {@link DateTime}. Conceptually, it's a container for those two endpoints, accompanied by methods for creating, parsing, interrogating, comparing, transforming, and formatting them. * * Here is a brief overview of the most commonly used methods and getters in Interval: * * * **Creation** To create an Interval, use {@link fromDateTimes}, {@link after}, {@link before}, or {@link fromISO}. * * **Accessors** Use {@link start} and {@link end} to get the start and end. * * **Interrogation** To analyze the Interval, use {@link count}, {@link length}, {@link hasSame}, {@link contains}, {@link isAfter}, or {@link isBefore}. * * **Transformation** To create other Intervals out of this one, use {@link set}, {@link splitAt}, {@link splitBy}, {@link divideEqually}, {@link merge}, {@link xor}, {@link union}, {@link intersection}, or {@link difference}. * * **Comparison** To compare this Interval to another one, use {@link equals}, {@link overlaps}, {@link abutsStart}, {@link abutsEnd}, {@link engulfs} * * **Output*** To convert the Interval into other representations, see {@link toString}, {@link toISO}, {@link toFormat}, and {@link toDuration}. */ var Interval = function () { /** * @private */ function Interval(config) { classCallCheck(this, Interval); /** * @access private */ this.s = config.start; /** * @access private */ this.e = config.end; /** * @access private */ this.invalid = config.invalidReason || null; } /** * Create an invalid Interval. * @return {Interval} */ Interval.invalid = function invalid(reason) { if (!reason) { throw new InvalidArgumentError('need to specify a reason the DateTime is invalid'); } if (Settings.throwOnInvalid) { throw new InvalidIntervalError(reason); } else { return new Interval({ invalidReason: reason }); } }; /** * Create an Interval from a start DateTime and an end DateTime. Inclusive of the start but not the end. * @param {DateTime|Date|Object} start * @param {DateTime|Date|Object} end * @return {Interval} */ Interval.fromDateTimes = function fromDateTimes(start, end) { var builtStart = friendlyDateTime(start), builtEnd = friendlyDateTime(end); return new Interval({ start: builtStart, end: builtEnd, invalidReason: validateStartEnd(builtStart, builtEnd) ? null : 'invalid endpoints' }); }; /** * Create an Interval from a start DateTime and a Duration to extend to. * @param {DateTime|Date|Object} start * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ Interval.after = function after(start, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(start); return Interval.fromDateTimes(dt, dt.plus(dur)); }; /** * Create an Interval from an end DateTime and a Duration to extend backwards to. * @param {DateTime|Date|Object} end * @param {Duration|Object|number} duration - the length of the Interval. * @return {Interval} */ Interval.before = function before(end, duration) { var dur = friendlyDuration(duration), dt = friendlyDateTime(end); return Interval.fromDateTimes(dt.minus(dur), dt); }; /** * Create an Interval from an ISO 8601 string * @param {string} string - the ISO string to parse * @param {Object} opts - options to pass {@see DateTime.fromISO} * @return {Interval} */ Interval.fromISO = function fromISO(string, opts) { if (string) { var _string$split = string.split(/\//), s = _string$split[0], e = _string$split[1]; if (s && e) { return Interval.fromDateTimes(DateTime.fromISO(s, opts), DateTime.fromISO(e, opts)); } } return Interval.invalid('invalid ISO format'); }; /** * Returns the start of the Interval * @type {DateTime} */ /** * Returns the length of the Interval in the specified unit. * @param {string} unit - the unit (such as 'hours' or 'days') to return the length in. * @return {number} */ Interval.prototype.length = function length() { var unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'milliseconds'; return this.isValid ? this.toDuration.apply(this, [unit]).get(unit) : NaN; }; /** * Returns the count of minutes, hours, days, months, or years included in the Interval, even in part. * Unlike {@link length} this counts sections of the calendar, not periods of time, e.g. specifying 'day' * asks 'what dates are included in this interval?', not 'how many days long is this interval?' * @param {string} [unit='milliseconds'] - the unit of time to count. * @return {number} */ Interval.prototype.count = function count() { var unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'milliseconds'; if (!this.isValid) return NaN; var start = this.start.startOf(unit), end = this.end.startOf(unit); return Math.floor(end.diff(start, unit).get(unit)) + 1; }; /** * Returns whether this Interval's start and end are both in the same unit of time * @param {string} unit - the unit of time to check sameness on * @return {boolean} */ Interval.prototype.hasSame = function hasSame(unit) { return this.isValid ? this.e.minus(1).hasSame(this.s, unit) : false; }; /** * Return whether this Interval has the same start and end DateTimes. * @return {boolean} */ Interval.prototype.isEmpty = function isEmpty() { return this.s.valueOf() === this.e.valueOf(); }; /** * Return whether this Interval's start is after the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ Interval.prototype.isAfter = function isAfter(dateTime) { if (!this.isValid) return false; return this.s > dateTime; }; /** * Return whether this Interval's end is before the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ Interval.prototype.isBefore = function isBefore(dateTime) { if (!this.isValid) return false; return this.e <= dateTime; }; /** * Return whether this Interval contains the specified DateTime. * @param {DateTime} dateTime * @return {boolean} */ Interval.prototype.contains = function contains(dateTime) { if (!this.isValid) return false; return this.s <= dateTime && this.e > dateTime; }; /** * "Sets" the start and/or end dates. Returns a newly-constructed Interval. * @param {Object} values - the values to set * @param {DateTime} values.start - the starting DateTime * @param {DateTime} values.end - the ending DateTime * @return {Interval} */ Interval.prototype.set = function set$$1() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, start = _ref.start, end = _ref.end; if (!this.isValid) return this; return Interval.fromDateTimes(start || this.s, end || this.e); }; /** * Split this Interval at each of the specified DateTimes * @param {...[DateTime]} dateTimes - the unit of time to count. * @return {[Interval]} */ Interval.prototype.splitAt = function splitAt() { if (!this.isValid) return []; for (var _len = arguments.length, dateTimes = Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } var sorted = dateTimes.map(friendlyDateTime).sort(), results = []; var s = this.s, i = 0; while (s < this.e) { var added = sorted[i] || this.e, next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; i += 1; } return results; }; /** * Split this Interval into smaller Intervals, each of the specified length. * Left over time is grouped into a smaller interval * @param {Duration|Object|number} duration - The length of each resulting interval. * @return {[Interval]} */ Interval.prototype.splitBy = function splitBy(duration) { var dur = friendlyDuration(duration); if (!this.isValid || !dur.isValid || dur.as('milliseconds') === 0) { return []; } var s = this.s, added = void 0, next = void 0; var results = []; while (s < this.e) { added = s.plus(dur); next = +added > +this.e ? this.e : added; results.push(Interval.fromDateTimes(s, next)); s = next; } return results; }; /** * Split this Interval into the specified number of smaller intervals. * @param {number} numberOfParts - The number of Intervals to divide the Interval into. * @return {[Interval]} */ Interval.prototype.divideEqually = function divideEqually(numberOfParts) { if (!this.isValid) return []; return this.splitBy(this.length() / numberOfParts).slice(0, numberOfParts); }; /** * Return whether this Interval overlaps with the specified Interval * @param {Interval} other * @return {boolean} */ Interval.prototype.overlaps = function overlaps(other) { return this.e > other.s && this.s < other.e; }; /** * Return whether this Interval's end is adjacent to the specified Interval's start. * @param {Interval} other * @return {boolean} */ Interval.prototype.abutsStart = function abutsStart(other) { if (!this.isValid) return false; return +this.e === +other.s; }; /** * Return whether this Interval's start is adjacent to the specified Interval's end. * @param {Interval} other * @return {boolean} */ Interval.prototype.abutsEnd = function abutsEnd(other) { if (!this.isValid) return false; return +other.e === +this.s; }; /** * Return whether this Interval engulfs the start and end of the specified Interval. * @param {Interval} other * @return {boolean} */ Interval.prototype.engulfs = function engulfs(other) { if (!this.isValid) return false; return this.s <= other.s && this.e >= other.e; }; /** * Return whether this Interval has the same start and end as the specified Interval. * @param {Interval} other * @return {boolean} */ Interval.prototype.equals = function equals(other) { if (!this.isValid || !other.isValid) { return false; } return this.s.equals(other.s) && this.e.equals(other.e); }; /** * Return an Interval representing the intersection of this Interval and the specified Interval. * Specifically, the resulting Interval has the maximum start time and the minimum end time of the two Intervals. * Returns null if the intersection is empty, i.e., the intervals don't intersect. * @param {Interval} other * @return {Interval} */ Interval.prototype.intersection = function intersection(other) { if (!this.isValid) return this; var s = this.s > other.s ? this.s : other.s, e = this.e < other.e ? this.e : other.e; if (s > e) { return null; } else { return Interval.fromDateTimes(s, e); } }; /** * Return an Interval representing the union of this Interval and the specified Interval. * Specifically, the resulting Interval has the minimum start time and the maximum end time of the two Intervals. * @param {Interval} other * @return {Interval} */ Interval.prototype.union = function union(other) { if (!this.isValid) return this; var s = this.s < other.s ? this.s : other.s, e = this.e > other.e ? this.e : other.e; return Interval.fromDateTimes(s, e); }; /** * Merge an array of Intervals into a equivalent minimal set of Intervals. * Combines overlapping and adjacent Intervals. * @param {[Interval]} intervals * @return {[Interval]} */ Interval.merge = function merge(intervals) { var _intervals$sort$reduc = intervals.sort(function (a, b) { return a.s - b.s; }).reduce(function (_ref2, item) { var sofar = _ref2[0], current = _ref2[1]; if (!current) { return [sofar, item]; } else if (current.overlaps(item) || current.abutsStart(item)) { return [sofar, current.union(item)]; } else { return [sofar.concat([current]), item]; } }, [[], null]), found = _intervals$sort$reduc[0], final = _intervals$sort$reduc[1]; if (final) { found.push(final); } return found; }; /** * Return an array of Intervals representing the spans of time that only appear in one of the specified Intervals. * @param {[Interval]} intervals * @return {[Interval]} */ Interval.xor = function xor(intervals) { var _Array$prototype; var start = null, currentCount = 0; var results = [], ends = intervals.map(function (i) { return [{ time: i.s, type: 's' }, { time: i.e, type: 'e' }]; }), flattened = (_Array$prototype = Array.prototype).concat.apply(_Array$prototype, ends), arr = flattened.sort(function (a, b) { return a.time - b.time; }); for (var _iterator = arr, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref3; if (_isArray) { if (_i >= _iterator.length) break; _ref3 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref3 = _i.value; } var i = _ref3; currentCount += i.type === 's' ? 1 : -1; if (currentCount === 1) { start = i.time; } else { if (start && +start !== +i.time) { results.push(Interval.fromDateTimes(start, i.time)); } start = null; } } return Interval.merge(results); }; /** * Return an Interval representing the span of time in this Interval that doesn't overlap with any of the specified Intervals. * @param {...Interval} intervals * @return {[Interval]} */ Interval.prototype.difference = function difference() { var _this = this; for (var _len2 = arguments.length, intervals = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { intervals[_key2] = arguments[_key2]; } return Interval.xor([this].concat(intervals)).map(function (i) { return _this.intersection(i); }).filter(function (i) { return i && !i.isEmpty(); }); }; /** * Returns a string representation of this Interval appropriate for debugging. * @return {string} */ Interval.prototype.toString = function toString() { if (!this.isValid) return INVALID$2; return '[' + this.s.toISO() + ' \u2013 ' + this.e.toISO() + ')'; }; /** * Returns a string representation of this Interval appropriate for the REPL. * @return {string} */ Interval.prototype[customInspectSymbol] = function () { if (this.isValid) { return 'Interval {\n start: ' + this.start.toISO() + ',\n end: ' + this.end.toISO() + ',\n zone: ' + this.start.zone.name + ',\n locale: ' + this.start.locale + ' }'; } else { return 'Interval { Invalid, reason: ' + this.invalidReason + ' }'; } }; /** * Returns an ISO 8601-compliant string representation of this Interval. * @see https://en.wikipedia.org/wiki/ISO_8601#Time_intervals * @param {Object} opts - The same options as {@link DateTime.toISO} * @return {string} */ Interval.prototype.toISO = function toISO(opts) { if (!this.isValid) return INVALID$2; return this.s.toISO(opts) + '/' + this.e.toISO(opts); }; /** * Returns a string representation of this Interval formatted according to the specified format string. * @param {string} dateFormat - the format string. This string formats the start and end time. See {@link DateTime.toFormat} for details. * @param {Object} opts - options * @param {string} [opts.separator = ' – '] - a separator to place between the start and end representations * @return {string} */ Interval.prototype.toFormat = function toFormat(dateFormat) { var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref4$separator = _ref4.separator, separator = _ref4$separator === undefined ? ' – ' : _ref4$separator; if (!this.isValid) return INVALID$2; return '' + this.s.toFormat(dateFormat) + separator + this.e.toFormat(dateFormat); }; /** * Return a Duration representing the time spanned by this interval. * @param {string|string[]} [unit=['milliseconds']] - the unit or units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example Interval.fromDateTimes(dt1, dt2).toDuration().toObject() //=> { milliseconds: 88489257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('days').toObject() //=> { days: 1.0241812152777778 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes']).toObject() //=> { hours: 24, minutes: 34.82095 } * @example Interval.fromDateTimes(dt1, dt2).toDuration(['hours', 'minutes', 'seconds']).toObject() //=> { hours: 24, minutes: 34, seconds: 49.257 } * @example Interval.fromDateTimes(dt1, dt2).toDuration('seconds').toObject() //=> { seconds: 88489.257 } * @return {Duration} */ Interval.prototype.toDuration = function toDuration(unit, opts) { if (!this.isValid) { return Duration.invalid(this.invalidReason); } return this.e.diff(this.s, unit, opts); }; createClass(Interval, [{ key: 'start', get: function get$$1() { return this.isValid ? this.s : null; } /** * Returns the end of the Interval * @type {DateTime} */ }, { key: 'end', get: function get$$1() { return this.isValid ? this.e : null; } /** * Returns whether this Interval's end is at least its start, i.e. that the Interval isn't 'backwards'. * @type {boolean} */ }, { key: 'isValid', get: function get$$1() { return this.invalidReason === null; } /** * Returns an explanation of why this Interval became invalid, or null if the Interval is valid * @type {string} */ }, { key: 'invalidReason', get: function get$$1() { return this.invalid; } }]); return Interval; }(); /** * The Info class contains static methods for retrieving general time and date related data. For example, it has methods for finding out if a time zone has a DST, for listing the months in any supported locale, and for discovering which of Luxon features are available in the current environment. */ var Info = function () { function Info() { classCallCheck(this, Info); } /** * Return whether the specified zone contains a DST. * @param {string|Zone} [zone='local'] - Zone to check. Defaults to the environment's local zone. * @return {boolean} */ Info.hasDST = function hasDST() { var zone = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Settings.defaultZone; var proto = DateTime.local().setZone(zone).set({ month: 12 }); return !zone.universal && proto.offset !== proto.set({ month: 6 }).offset; }; /** * Return whether the specified zone is a valid IANA specifier. * @param {string} zone - Zone to check * @return {boolean} */ Info.isValidIANAZone = function isValidIANAZone(zone) { return !!IANAZone.isValidSpecifier(zone) && IANAZone.isValidZone(zone); }; /** * Return an array of standalone month names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @example Info.months()[0] //=> 'January' * @example Info.months('short')[0] //=> 'Jan' * @example Info.months('numeric')[0] //=> '1' * @example Info.months('short', { locale: 'fr-CA' } )[0] //=> 'janv.' * @example Info.months('numeric', { locale: 'ar' })[0] //=> '١' * @example Info.months('long', { outputCalendar: 'islamic' })[0] //=> 'Rabiʻ I' * @return {[string]} */ Info.months = function months() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'long'; var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref$locale = _ref.locale, locale = _ref$locale === undefined ? null : _ref$locale, _ref$numberingSystem = _ref.numberingSystem, numberingSystem = _ref$numberingSystem === undefined ? null : _ref$numberingSystem, _ref$outputCalendar = _ref.outputCalendar, outputCalendar = _ref$outputCalendar === undefined ? 'gregory' : _ref$outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar).months(length); }; /** * Return an array of format month names. * Format months differ from standalone months in that they're meant to appear next to the day of the month. In some languages, that * changes the string. * See {@link months} * @param {string} [length='long'] - the length of the month representation, such as "numeric", "2-digit", "narrow", "short", "long" * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @param {string} [opts.outputCalendar='gregory'] - the calendar * @return {[string]} */ Info.monthsFormat = function monthsFormat() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'long'; var _ref2 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref2$locale = _ref2.locale, locale = _ref2$locale === undefined ? null : _ref2$locale, _ref2$numberingSystem = _ref2.numberingSystem, numberingSystem = _ref2$numberingSystem === undefined ? null : _ref2$numberingSystem, _ref2$outputCalendar = _ref2.outputCalendar, outputCalendar = _ref2$outputCalendar === undefined ? 'gregory' : _ref2$outputCalendar; return Locale.create(locale, numberingSystem, outputCalendar).months(length, true); }; /** * Return an array of standalone week names. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @example Info.weekdays()[0] //=> 'Monday' * @example Info.weekdays('short')[0] //=> 'Mon' * @example Info.weekdays('short', { locale: 'fr-CA' })[0] //=> 'lun.' * @example Info.weekdays('short', { locale: 'ar' })[0] //=> 'الاثنين' * @return {[string]} */ Info.weekdays = function weekdays() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'long'; var _ref3 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref3$locale = _ref3.locale, locale = _ref3$locale === undefined ? null : _ref3$locale, _ref3$numberingSystem = _ref3.numberingSystem, numberingSystem = _ref3$numberingSystem === undefined ? null : _ref3$numberingSystem; return Locale.create(locale, numberingSystem, null).weekdays(length); }; /** * Return an array of format week names. * Format weekdays differ from standalone weekdays in that they're meant to appear next to more date information. In some languages, that * changes the string. * See {@link weekdays} * @param {string} [length='long'] - the length of the month representation, such as "narrow", "short", "long". * @param {Object} opts - options * @param {string} [opts.locale=null] - the locale code * @param {string} [opts.numberingSystem=null] - the numbering system * @return {[string]} */ Info.weekdaysFormat = function weekdaysFormat() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'long'; var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref4$locale = _ref4.locale, locale = _ref4$locale === undefined ? null : _ref4$locale, _ref4$numberingSystem = _ref4.numberingSystem, numberingSystem = _ref4$numberingSystem === undefined ? null : _ref4$numberingSystem; return Locale.create(locale, numberingSystem, null).weekdays(length, true); }; /** * Return an array of meridiems. * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.meridiems() //=> [ 'AM', 'PM' ] * @example Info.meridiems({ locale: 'de' }) //=> [ 'vorm.', 'nachm.' ] * @return {[string]} */ Info.meridiems = function meridiems() { var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref5$locale = _ref5.locale, locale = _ref5$locale === undefined ? null : _ref5$locale; return Locale.create(locale).meridiems(); }; /** * Return an array of eras, such as ['BC', 'AD']. The locale can be specified, but the calendar system is always Gregorian. * @param {string} [length='short'] - the length of the era representation, such as "short" or "long". * @param {Object} opts - options * @param {string} [opts.locale] - the locale code * @example Info.eras() //=> [ 'BC', 'AD' ] * @example Info.eras('long') //=> [ 'Before Christ', 'Anno Domini' ] * @example Info.eras('long', { locale: 'fr' }) //=> [ 'avant Jésus-Christ', 'après Jésus-Christ' ] * @return {[string]} */ Info.eras = function eras() { var length = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'short'; var _ref6 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref6$locale = _ref6.locale, locale = _ref6$locale === undefined ? null : _ref6$locale; return Locale.create(locale, null, 'gregory').eras(length); }; /** * Return the set of available features in this environment. * Some features of Luxon are not available in all environments. For example, on older browsers, timezone support is not available. Use this function to figure out if that's the case. * Keys: * * `zones`: whether this environment supports IANA timezones * * `intlTokens`: whether this environment supports internationalized token-based formatting/parsing * * `intl`: whether this environment supports general internationalization * @example Info.features() //=> { intl: true, intlTokens: false, zones: true } * @return {Object} */ Info.features = function features() { var intl = false, intlTokens = false, zones = false; if (hasIntl()) { intl = true; intlTokens = hasFormatToParts(); try { zones = new Intl.DateTimeFormat('en', { timeZone: 'America/New_York' }).resolvedOptions().timeZone === 'America/New_York'; } catch (e) { zones = false; } } return { intl: intl, intlTokens: intlTokens, zones: zones }; }; return Info; }(); function dayDiff(earlier, later) { var utcDayStart = function utcDayStart(dt) { return dt.toUTC(0, { keepLocalTime: true }).startOf('day').valueOf(); }, ms = utcDayStart(later) - utcDayStart(earlier); return Math.floor(Duration.fromMillis(ms).as('days')); } function highOrderDiffs(cursor, later, units) { var differs = [['years', function (a, b) { return b.year - a.year; }], ['months', function (a, b) { return b.month - a.month + (b.year - a.year) * 12; }], ['weeks', function (a, b) { var days = dayDiff(a, b); return (days - days % 7) / 7; }], ['days', dayDiff]]; var results = {}; var lowestOrder = void 0, highWater = void 0; for (var _iterator = differs, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref2; if (_isArray) { if (_i >= _iterator.length) break; _ref2 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref2 = _i.value; } var _ref = _ref2; var unit = _ref[0]; var differ = _ref[1]; if (units.indexOf(unit) >= 0) { var _cursor$plus; lowestOrder = unit; var delta = differ(cursor, later); highWater = cursor.plus((_cursor$plus = {}, _cursor$plus[unit] = delta, _cursor$plus)); if (highWater > later) { var _highWater$minus; cursor = highWater.minus((_highWater$minus = {}, _highWater$minus[unit] = 1, _highWater$minus)); delta -= 1; } else { cursor = highWater; } if (delta > 0) { results[unit] = delta; } } } return [cursor, results, highWater, lowestOrder]; } function _diff (earlier, later, units, opts) { var _highOrderDiffs = highOrderDiffs(earlier, later, units), cursor = _highOrderDiffs[0], results = _highOrderDiffs[1], highWater = _highOrderDiffs[2], lowestOrder = _highOrderDiffs[3]; var remainingMillis = later - cursor; var lowerOrderUnits = units.filter(function (u) { return ['hours', 'minutes', 'seconds', 'milliseconds'].indexOf(u) >= 0; }); if (lowerOrderUnits.length === 0) { if (highWater < later) { var _cursor$plus2; highWater = cursor.plus((_cursor$plus2 = {}, _cursor$plus2[lowestOrder] = 1, _cursor$plus2)); } if (highWater !== cursor) { results[lowestOrder] = (results[lowestOrder] || 0) + remainingMillis / (highWater - cursor); } } var duration = Duration.fromObject(Object.assign(results, opts)); if (lowerOrderUnits.length > 0) { var _Duration$fromMillis; return (_Duration$fromMillis = Duration.fromMillis(remainingMillis, opts)).shiftTo.apply(_Duration$fromMillis, lowerOrderUnits).plus(duration); } else { return duration; } } var MISSING_FTP = 'missing Intl.DateTimeFormat.formatToParts support'; function intUnit(regex) { var post = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : function (i) { return i; }; return { regex: regex, deser: function deser(_ref) { var s = _ref[0]; return post(parseInt(s)); } }; } function fixListRegex(s) { // make dots optional and also make them literal return s.replace(/\./, '\\.?'); } function stripInsensitivities(s) { return s.replace(/\./, '').toLowerCase(); } function oneOf(strings, startIndex) { if (strings === null) { return null; } else { return { regex: RegExp(strings.map(fixListRegex).join('|')), deser: function deser(_ref2) { var s = _ref2[0]; return strings.findIndex(function (i) { return stripInsensitivities(s) === stripInsensitivities(i); }) + startIndex; } }; } } function offset(regex, groups) { return { regex: regex, deser: function deser(_ref3) { var h = _ref3[1], m = _ref3[2]; return signedOffset(h, m); }, groups: groups }; } function simple(regex) { return { regex: regex, deser: function deser(_ref4) { var s = _ref4[0]; return s; } }; } function unitForToken(token, loc) { var one = /\d/, two = /\d{2}/, three = /\d{3}/, four = /\d{4}/, oneOrTwo = /\d{1,2}/, oneToThree = /\d{1,3}/, twoToFour = /\d{2,4}/, literal = function literal(t) { return { regex: RegExp(t.val), deser: function deser(_ref5) { var s = _ref5[0]; return s; }, literal: true }; }, unitate = function unitate(t) { if (token.literal) { return literal(t); } switch (t.val) { // era case 'G': return oneOf(loc.eras('short', false), 0); case 'GG': return oneOf(loc.eras('long', false), 0); // years case 'y': return intUnit(/\d{1,6}/); case 'yy': return intUnit(twoToFour, untruncateYear); case 'yyyy': return intUnit(four); case 'yyyyy': return intUnit(/\d{4,6}/); case 'yyyyyy': return intUnit(/\d{6}/); // months case 'M': return intUnit(oneOrTwo); case 'MM': return intUnit(two); case 'MMM': return oneOf(loc.months('short', false, false), 1); case 'MMMM': return oneOf(loc.months('long', false, false), 1); case 'L': return intUnit(oneOrTwo); case 'LL': return intUnit(two); case 'LLL': return oneOf(loc.months('short', true, false), 1); case 'LLLL': return oneOf(loc.months('long', true, false), 1); // dates case 'd': return intUnit(oneOrTwo); case 'dd': return intUnit(two); // ordinals case 'o': return intUnit(oneToThree); case 'ooo': return intUnit(three); // time case 'HH': return intUnit(two); case 'H': return intUnit(oneOrTwo); case 'hh': return intUnit(two); case 'h': return intUnit(oneOrTwo); case 'mm': return intUnit(two); case 'm': return intUnit(oneOrTwo); case 's': return intUnit(oneOrTwo); case 'ss': return intUnit(two); case 'S': return intUnit(oneToThree); case 'SSS': return intUnit(three); case 'u': return simple(/\d{1,9}/); // meridiem case 'a': return oneOf(loc.meridiems(), 0); // weekYear (k) case 'kkkk': return intUnit(four); case 'kk': return intUnit(twoToFour, untruncateYear); // weekNumber (W) case 'W': return intUnit(oneOrTwo); case 'WW': return intUnit(two); // weekdays case 'E': case 'c': return intUnit(one); case 'EEE': return oneOf(loc.weekdays('short', false, false), 1); case 'EEEE': return oneOf(loc.weekdays('long', false, false), 1); case 'ccc': return oneOf(loc.weekdays('short', true, false), 1); case 'cccc': return oneOf(loc.weekdays('long', true, false), 1); // offset/zone case 'Z': case 'ZZ': return offset(/([+-]\d{1,2})(?::(\d{2}))?/, 2); case 'ZZZ': return offset(/([+-]\d{1,2})(\d{2})?/, 2); // we don't support ZZZZ (PST) or ZZZZZ (Pacific Standard Time) in parsing // because we don't have any way to figure out what they are case 'z': return simple(/[A-Za-z_]{1,256}\/[A-Za-z_]{1,256}/); default: return literal(t); } }; var unit = unitate(token) || { invalidReason: MISSING_FTP }; unit.token = token; return unit; } function buildRegex(units) { var re = units.map(function (u) { return u.regex; }).reduce(function (f, r) { return f + '(' + r.source + ')'; }, ''); return ['^' + re + '$', units]; } function match(input, regex, handlers) { var matches = input.match(regex); if (matches) { var all = {}; var matchIndex = 1; for (var i in handlers) { if (handlers.hasOwnProperty(i)) { var h = handlers[i], groups = h.groups ? h.groups + 1 : 1; if (!h.literal && h.token) { all[h.token.val[0]] = h.deser(matches.slice(matchIndex, matchIndex + groups)); } matchIndex += groups; } } return [matches, all]; } else { return [matches, {}]; } } function dateTimeFromMatches(matches) { var toField = function toField(token) { switch (token) { case 'S': return 'millisecond'; case 's': return 'second'; case 'm': return 'minute'; case 'h': case 'H': return 'hour'; case 'd': return 'day'; case 'o': return 'ordinal'; case 'L': case 'M': return 'month'; case 'y': return 'year'; case 'E': case 'c': return 'weekday'; case 'W': return 'weekNumber'; case 'k': return 'weekYear'; default: return null; } }; var zone = void 0; if (!isUndefined(matches.Z)) { zone = new FixedOffsetZone(matches.Z); } else if (!isUndefined(matches.z)) { zone = new IANAZone(matches.z); } else { zone = null; } if (!isUndefined(matches.h)) { if (matches.h < 12 && matches.a === 1) { matches.h += 12; } else if (matches.h === 12 && matches.a === 0) { matches.h = 0; } } if (matches.G === 0 && matches.y) { matches.y = -matches.y; } if (!isUndefined(matches.u)) { matches.S = parseMillis(matches.u); } var vals = Object.keys(matches).reduce(function (r, k) { var f = toField(k); if (f) { r[f] = matches[k]; } return r; }, {}); return [vals, zone]; } /** * @private */ function explainFromTokens(locale, input, format) { var tokens = Formatter.parseFormat(format), units = tokens.map(function (t) { return unitForToken(t, locale); }), disqualifyingUnit = units.find(function (t) { return t.invalidReason; }); if (disqualifyingUnit) { return { input: input, tokens: tokens, invalidReason: disqualifyingUnit.invalidReason }; } else { var _buildRegex = buildRegex(units), regexString = _buildRegex[0], handlers = _buildRegex[1], regex = RegExp(regexString, 'i'), _match = match(input, regex, handlers), rawMatches = _match[0], matches = _match[1], _ref6 = matches ? dateTimeFromMatches(matches) : [null, null], result = _ref6[0], zone = _ref6[1]; return { input: input, tokens: tokens, regex: regex, rawMatches: rawMatches, matches: matches, result: result, zone: zone }; } } function parseFromTokens(locale, input, format) { var _explainFromTokens = explainFromTokens(locale, input, format), result = _explainFromTokens.result, zone = _explainFromTokens.zone, invalidReason = _explainFromTokens.invalidReason; return [result, zone, invalidReason]; } var nonLeapLadder = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; var leapLadder = [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335]; function dayOfWeek(year, month, day) { var js = new Date(Date.UTC(year, month - 1, day)).getUTCDay(); return js === 0 ? 7 : js; } function computeOrdinal(year, month, day) { return day + (isLeapYear(year) ? leapLadder : nonLeapLadder)[month - 1]; } function uncomputeOrdinal(year, ordinal) { var table = isLeapYear(year) ? leapLadder : nonLeapLadder, month0 = table.findIndex(function (i) { return i < ordinal; }), day = ordinal - table[month0]; return { month: month0 + 1, day: day }; } /** * @private */ function gregorianToWeek(gregObj) { var year = gregObj.year, month = gregObj.month, day = gregObj.day, ordinal = computeOrdinal(year, month, day), weekday = dayOfWeek(year, month, day); var weekNumber = Math.floor((ordinal - weekday + 10) / 7), weekYear = void 0; if (weekNumber < 1) { weekYear = year - 1; weekNumber = weeksInWeekYear(weekYear); } else if (weekNumber > weeksInWeekYear(year)) { weekYear = year + 1; weekNumber = 1; } else { weekYear = year; } return Object.assign({ weekYear: weekYear, weekNumber: weekNumber, weekday: weekday }, timeObject(gregObj)); } function weekToGregorian(weekData) { var weekYear = weekData.weekYear, weekNumber = weekData.weekNumber, weekday = weekData.weekday, weekdayOfJan4 = dayOfWeek(weekYear, 1, 4), yearInDays = daysInYear(weekYear); var ordinal = weekNumber * 7 + weekday - weekdayOfJan4 - 3, year = void 0; if (ordinal < 1) { year = weekYear - 1; ordinal += daysInYear(year); } else if (ordinal > yearInDays) { year = weekYear + 1; ordinal -= daysInYear(year); } else { year = weekYear; } var _uncomputeOrdinal = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal.month, day = _uncomputeOrdinal.day; return Object.assign({ year: year, month: month, day: day }, timeObject(weekData)); } function gregorianToOrdinal(gregData) { var year = gregData.year, month = gregData.month, day = gregData.day, ordinal = computeOrdinal(year, month, day); return Object.assign({ year: year, ordinal: ordinal }, timeObject(gregData)); } function ordinalToGregorian(ordinalData) { var year = ordinalData.year, ordinal = ordinalData.ordinal, _uncomputeOrdinal2 = uncomputeOrdinal(year, ordinal), month = _uncomputeOrdinal2.month, day = _uncomputeOrdinal2.day; return Object.assign({ year: year, month: month, day: day }, timeObject(ordinalData)); } function hasInvalidWeekData(obj) { var validYear = isNumber(obj.weekYear), validWeek = numberBetween(obj.weekNumber, 1, weeksInWeekYear(obj.weekYear)), validWeekday = numberBetween(obj.weekday, 1, 7); if (!validYear) { return 'weekYear out of range'; } else if (!validWeek) { return 'week out of range'; } else if (!validWeekday) { return 'weekday out of range'; } else return false; } function hasInvalidOrdinalData(obj) { var validYear = isNumber(obj.year), validOrdinal = numberBetween(obj.ordinal, 1, daysInYear(obj.year)); if (!validYear) { return 'year out of range'; } else if (!validOrdinal) { return 'ordinal out of range'; } else return false; } function hasInvalidGregorianData(obj) { var validYear = isNumber(obj.year), validMonth = numberBetween(obj.month, 1, 12), validDay = numberBetween(obj.day, 1, daysInMonth(obj.year, obj.month)); if (!validYear) { return 'year out of range'; } else if (!validMonth) { return 'month out of range'; } else if (!validDay) { return 'day out of range'; } else return false; } function hasInvalidTimeData(obj) { var validHour = numberBetween(obj.hour, 0, 23), validMinute = numberBetween(obj.minute, 0, 59), validSecond = numberBetween(obj.second, 0, 59), validMillisecond = numberBetween(obj.millisecond, 0, 999); if (!validHour) { return 'hour out of range'; } else if (!validMinute) { return 'minute out of range'; } else if (!validSecond) { return 'second out of range'; } else if (!validMillisecond) { return 'millisecond out of range'; } else return false; } var INVALID = 'Invalid DateTime'; var INVALID_INPUT = 'invalid input'; var UNSUPPORTED_ZONE = 'unsupported zone'; var UNPARSABLE = 'unparsable'; // we cache week data on the DT object and this intermediates the cache function possiblyCachedWeekData(dt) { if (dt.weekData === null) { dt.weekData = gregorianToWeek(dt.c); } return dt.weekData; } // clone really means, "make a new object with these modifications". all "setters" really use this // to create a new object while only changing some of the properties function clone(inst, alts) { var current = { ts: inst.ts, zone: inst.zone, c: inst.c, o: inst.o, loc: inst.loc, invalidReason: inst.invalidReason }; return new DateTime(Object.assign({}, current, alts, { old: current })); } // find the right offset a given local time. The o input is our guess, which determines which // offset we'll pick in ambiguous cases (e.g. there are two 3 AMs b/c Fallback DST) function fixOffset(localTS, o, tz) { // Our UTC time is just a guess because our offset is just a guess var utcGuess = localTS - o * 60 * 1000; // Test whether the zone matches the offset for this ts var o2 = tz.offset(utcGuess); // If so, offset didn't change and we're done if (o === o2) { return [utcGuess, o]; } // If not, change the ts by the difference in the offset utcGuess -= (o2 - o) * 60 * 1000; // If that gives us the local time we want, we're done var o3 = tz.offset(utcGuess); if (o2 === o3) { return [utcGuess, o2]; } // If it's different, we're in a hole time. The offset has changed, but the we don't adjust the time return [localTS - Math.min(o2, o3) * 60 * 1000, Math.max(o2, o3)]; } // convert an epoch timestamp into a calendar object with the given offset function tsToObj(ts, offset) { ts += offset * 60 * 1000; var d = new Date(ts); return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate(), hour: d.getUTCHours(), minute: d.getUTCMinutes(), second: d.getUTCSeconds(), millisecond: d.getUTCMilliseconds() }; } // covert a calendar object to a local timestamp (epoch, but with the offset baked in) function objToLocalTS(obj) { var d = Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour, obj.minute, obj.second, obj.millisecond); // for legacy reasons, years between 0 and 99 are interpreted as 19XX; revert that if (obj.year < 100 && obj.year >= 0) { d = new Date(d); d.setUTCFullYear(obj.year); } return +d; } // convert a calendar object to a epoch timestamp function objToTS(obj, offset, zone) { return fixOffset(objToLocalTS(obj), offset, zone); } // create a new DT instance by adding a duration, adjusting for DSTs function adjustTime(inst, dur) { var oPre = inst.o, year = inst.c.year + dur.years, month = inst.c.month + dur.months + dur.quarters * 3, c = Object.assign({}, inst.c, { year: year, month: month, day: Math.min(inst.c.day, daysInMonth(year, month)) + dur.days + dur.weeks * 7 }), millisToAdd = Duration.fromObject({ hours: dur.hours, minutes: dur.minutes, seconds: dur.seconds, milliseconds: dur.milliseconds }).as('milliseconds'), localTS = objToLocalTS(c); var _fixOffset = fixOffset(localTS, oPre, inst.zone), ts = _fixOffset[0], o = _fixOffset[1]; if (millisToAdd !== 0) { ts += millisToAdd; // that could have changed the offset by going over a DST, but we want to keep the ts the same o = inst.zone.offset(ts); } return { ts: ts, o: o }; } // helper useful in turning the results of parsing into real dates // by handling the zone options function parseDataToDateTime(parsed, parsedZone, opts) { var setZone = opts.setZone, zone = opts.zone; if (parsed && Object.keys(parsed).length !== 0) { var interpretationZone = parsedZone || zone, inst = DateTime.fromObject(Object.assign(parsed, opts, { zone: interpretationZone })); return setZone ? inst : inst.setZone(zone); } else { return DateTime.invalid(UNPARSABLE); } } // if you want to output a technical format (e.g. RFC 2822), this helper // helps handle the details function toTechFormat(dt, format) { return dt.isValid ? Formatter.create(Locale.create('en-US'), { allowZ: true, forceSimple: true }).formatDateTimeFromString(dt, format) : null; } // technical time formats (e.g. the time part of ISO 8601), take some options // and this commonizes their handling function toTechTimeFormat(dt, _ref) { var _ref$suppressSeconds = _ref.suppressSeconds, suppressSeconds = _ref$suppressSeconds === undefined ? false : _ref$suppressSeconds, _ref$suppressMillisec = _ref.suppressMilliseconds, suppressMilliseconds = _ref$suppressMillisec === undefined ? false : _ref$suppressMillisec, _ref$includeOffset = _ref.includeOffset, includeOffset = _ref$includeOffset === undefined ? true : _ref$includeOffset, _ref$includeZone = _ref.includeZone, includeZone = _ref$includeZone === undefined ? false : _ref$includeZone, _ref$spaceZone = _ref.spaceZone, spaceZone = _ref$spaceZone === undefined ? false : _ref$spaceZone; var fmt = 'HH:mm'; if (!suppressSeconds || dt.second !== 0 || dt.millisecond !== 0) { fmt += ':ss'; if (!suppressMilliseconds || dt.millisecond !== 0) { fmt += '.SSS'; } } if ((includeZone || includeOffset) && spaceZone) { fmt += ' '; } if (includeZone) { fmt += 'z'; } else if (includeOffset) { fmt += 'ZZ'; } return toTechFormat(dt, fmt); } // defaults for unspecified units in the supported calendars var defaultUnitValues = { month: 1, day: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; var defaultWeekUnitValues = { weekNumber: 1, weekday: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; var defaultOrdinalUnitValues = { ordinal: 1, hour: 0, minute: 0, second: 0, millisecond: 0 }; // Units in the supported calendars, sorted by bigness var orderedUnits = ['year', 'month', 'day', 'hour', 'minute', 'second', 'millisecond']; var orderedWeekUnits = ['weekYear', 'weekNumber', 'weekday', 'hour', 'minute', 'second', 'millisecond']; var orderedOrdinalUnits = ['year', 'ordinal', 'hour', 'minute', 'second', 'millisecond']; // standardize case and plurality in units function normalizeUnit(unit) { var ignoreUnknown = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var normalized = { year: 'year', years: 'year', month: 'month', months: 'month', day: 'day', days: 'day', hour: 'hour', hours: 'hour', minute: 'minute', minutes: 'minute', second: 'second', seconds: 'second', millisecond: 'millisecond', milliseconds: 'millisecond', weekday: 'weekday', weekdays: 'weekday', weeknumber: 'weekNumber', weeksnumber: 'weekNumber', weeknumbers: 'weekNumber', weekyear: 'weekYear', weekyears: 'weekYear', ordinal: 'ordinal' }[unit ? unit.toLowerCase() : unit]; if (!ignoreUnknown && !normalized) throw new InvalidUnitError(unit); return normalized; } // this is a dumbed down version of fromObject() that runs about 60% faster // but doesn't do any validation, makes a bunch of assumptions about what units // are present, and so on. function quickDT(obj, zone) { // assume we have the higher-order units for (var _iterator = orderedUnits, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref2; if (_isArray) { if (_i >= _iterator.length) break; _ref2 = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref2 = _i.value; } var u = _ref2; if (isUndefined(obj[u])) { obj[u] = defaultUnitValues[u]; } } var invalidReason = hasInvalidGregorianData(obj) || hasInvalidTimeData(obj); if (invalidReason) { return DateTime.invalid(invalidReason); } var tsNow = Settings.now(), offsetProvis = zone.offset(tsNow), _objToTS = objToTS(obj, offsetProvis, zone), ts = _objToTS[0], o = _objToTS[1]; return new DateTime({ ts: ts, zone: zone, o: o }); } /** * A DateTime is an immutable data structure representing a specific date and time and accompanying methods. It contains class and instance methods for creating, parsing, interrogating, transforming, and formatting them. * * A DateTime comprises of: * * A timestamp. Each DateTime instance refers to a specific millisecond of the Unix epoch. * * A time zone. Each instance is considered in the context of a specific zone (by default the local system's zone). * * Configuration properties that effect how output strings are formatted, such as `locale`, `numberingSystem`, and `outputCalendar`. * * Here is a brief overview of the most commonly used functionality it provides: * * * **Creation**: To create a DateTime from its components, use one of its factory class methods: {@link local}, {@link utc}, and (most flexibly) {@link fromObject}. To create one from a standard string format, use {@link fromISO}, {@link fromHTTP}, and {@link fromRFC2822}. To create one from a custom string format, use {@link fromFormat}. To create one from a native JS date, use {@link fromJSDate}. * * **Gregorian calendar and time**: To examine the Gregorian properties of a DateTime individually (i.e as opposed to collectively through {@link toObject}), use the {@link year}, {@link month}, * {@link day}, {@link hour}, {@link minute}, {@link second}, {@link millisecond} accessors. * * **Week calendar**: For ISO week calendar attributes, see the {@link weekYear}, {@link weekNumber}, and {@link weekday} accessors. * * **Configuration** See the {@link locale} and {@link numberingSystem} accessors. * * **Transformation**: To transform the DateTime into other DateTimes, use {@link set}, {@link reconfigure}, {@link setZone}, {@link setLocale}, {@link plus}, {@link minus}, {@link endOf}, {@link startOf}, {@link toUTC}, and {@link toLocal}. * * **Output**: To convert the DateTime to other representations, use the {@link toJSON}, {@link toISO}, {@link toHTTP}, {@link toObject}, {@link toRFC2822}, {@link toString}, {@link toLocaleString}, {@link toFormat}, {@link toMillis} and {@link toJSDate}. * * There's plenty others documented below. In addition, for more information on subtler topics like internationalization, time zones, alternative calendars, validity, and so on, see the external documentation. */ var DateTime = function () { /** * @access private */ function DateTime(config) { classCallCheck(this, DateTime); var zone = config.zone || Settings.defaultZone, invalidReason = config.invalidReason || (Number.isNaN(config.ts) ? INVALID_INPUT : null) || (!zone.isValid ? UNSUPPORTED_ZONE : null); /** * @access private */ this.ts = isUndefined(config.ts) ? Settings.now() : config.ts; var c = null, o = null; if (!invalidReason) { var unchanged = config.old && config.old.ts === this.ts && config.old.zone.equals(zone); c = unchanged ? config.old.c : tsToObj(this.ts, zone.offset(this.ts)); o = unchanged ? config.old.o : zone.offset(this.ts); } /** * @access private */ this.zone = zone; /** * @access private */ this.loc = config.loc || Locale.create(); /** * @access private */ this.invalid = invalidReason; /** * @access private */ this.weekData = null; /** * @access private */ this.c = c; /** * @access private */ this.o = o; } // CONSTRUCT /** * Create a local DateTime * @param {number} year - The calendar year. If omitted (as in, call `local()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59 * @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999 * @example DateTime.local() //~> now * @example DateTime.local(2017) //~> 2017-01-01T00:00:00 * @example DateTime.local(2017, 3) //~> 2017-03-01T00:00:00 * @example DateTime.local(2017, 3, 12) //~> 2017-03-12T00:00:00 * @example DateTime.local(2017, 3, 12, 5) //~> 2017-03-12T05:00:00 * @example DateTime.local(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00 * @example DateTime.local(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10 * @example DateTime.local(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765 * @return {DateTime} */ DateTime.local = function local(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({ ts: Settings.now() }); } else { return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, Settings.defaultZone); } }; /** * Create a DateTime in UTC * @param {number} year - The calendar year. If omitted (as in, call `utc()` with no arguments), the current time will be used * @param {number} [month=1] - The month, 1-indexed * @param {number} [day=1] - The day of the month * @param {number} [hour=0] - The hour of the day, in 24-hour time * @param {number} [minute=0] - The minute of the hour, i.e. a number between 0 and 59 * @param {number} [second=0] - The second of the minute, i.e. a number between 0 and 59 * @param {number} [millisecond=0] - The millisecond of the second, i.e. a number between 0 and 999 * @example DateTime.utc() //~> now * @example DateTime.utc(2017) //~> 2017-01-01T00:00:00Z * @example DateTime.utc(2017, 3) //~> 2017-03-01T00:00:00Z * @example DateTime.utc(2017, 3, 12) //~> 2017-03-12T00:00:00Z * @example DateTime.utc(2017, 3, 12, 5) //~> 2017-03-12T05:00:00Z * @example DateTime.utc(2017, 3, 12, 5, 45) //~> 2017-03-12T05:45:00Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10) //~> 2017-03-12T05:45:10Z * @example DateTime.utc(2017, 3, 12, 5, 45, 10, 765) //~> 2017-03-12T05:45:10.765Z * @return {DateTime} */ DateTime.utc = function utc(year, month, day, hour, minute, second, millisecond) { if (isUndefined(year)) { return new DateTime({ ts: Settings.now(), zone: FixedOffsetZone.utcInstance }); } else { return quickDT({ year: year, month: month, day: day, hour: hour, minute: minute, second: second, millisecond: millisecond }, FixedOffsetZone.utcInstance); } }; /** * Create a DateTime from a Javascript Date object. Uses the default zone. * @param {Date} date - a Javascript Date object * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @return {DateTime} */ DateTime.fromJSDate = function fromJSDate(date) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new DateTime({ ts: isDate(date) ? date.valueOf() : NaN, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); }; /** * Create a DateTime from a number of milliseconds since the epoch (i.e. since 1 January 1970 00:00:00 UTC). Uses the default zone. * @param {number} milliseconds - a number of milliseconds since 1970 UTC * @param {Object} options - configuration options for the DateTime * @param {string|Zone} [options.zone='local'] - the zone to place the DateTime into * @param {string} [options.locale] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @return {DateTime} */ DateTime.fromMillis = function fromMillis(milliseconds) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!isNumber(milliseconds)) { throw new InvalidArgumentError('fromMillis requires a numerical input'); } else { return new DateTime({ ts: milliseconds, zone: normalizeZone(options.zone, Settings.defaultZone), loc: Locale.fromObject(options) }); } }; /** * Create a DateTime from a Javascript object with keys like 'year' and 'hour' with reasonable defaults. * @param {Object} obj - the object to create the DateTime from * @param {number} obj.year - a year, such as 1987 * @param {number} obj.month - a month, 1-12 * @param {number} obj.day - a day of the month, 1-31, depending on the month * @param {number} obj.ordinal - day of the year, 1-365 or 366 * @param {number} obj.weekYear - an ISO week year * @param {number} obj.weekNumber - an ISO week number, between 1 and 52 or 53, depending on the year * @param {number} obj.weekday - an ISO weekday, 1-7, where 1 is Monday and 7 is Sunday * @param {number} obj.hour - hour of the day, 0-23 * @param {number} obj.minute - minute of the hour, 0-59 * @param {number} obj.second - second of the minute, 0-59 * @param {number} obj.millisecond - millisecond of the second, 0-999 * @param {string|Zone} [obj.zone='local'] - interpret the numbers in the context of a particular zone. Can take any value taken as the first argument to setZone() * @param {string} [obj.locale='en-US'] - a locale to set on the resulting DateTime instance * @param {string} obj.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} obj.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromObject({ year: 1982, month: 5, day: 25}).toISODate() //=> '1982-05-25' * @example DateTime.fromObject({ year: 1982 }).toISODate() //=> '1982-01-01T00' * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6 }) //~> today at 10:26:06 * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'utc' }), * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'local' }) * @example DateTime.fromObject({ hour: 10, minute: 26, second: 6, zone: 'America/New_York' }) * @example DateTime.fromObject({ weekYear: 2016, weekNumber: 2, weekday: 3 }).toISODate() //=> '2016-01-13' * @return {DateTime} */ DateTime.fromObject = function fromObject(obj) { var zoneToUse = normalizeZone(obj.zone, Settings.defaultZone); if (!zoneToUse.isValid) { return DateTime.invalid(UNSUPPORTED_ZONE); } var tsNow = Settings.now(), offsetProvis = zoneToUse.offset(tsNow), normalized = normalizeObject(obj, normalizeUnit, true), containsOrdinal = !isUndefined(normalized.ordinal), containsGregorYear = !isUndefined(normalized.year), containsGregorMD = !isUndefined(normalized.month) || !isUndefined(normalized.day), containsGregor = containsGregorYear || containsGregorMD, definiteWeekDef = normalized.weekYear || normalized.weekNumber, loc = Locale.fromObject(obj); // cases: // just a weekday -> this week's instance of that weekday, no worries // (gregorian data or ordinal) + (weekYear or weekNumber) -> error // (gregorian month or day) + ordinal -> error // otherwise just use weeks or ordinals or gregorian, depending on what's specified if ((containsGregor || containsOrdinal) && definiteWeekDef) { throw new ConflictingSpecificationError("Can't mix weekYear/weekNumber units with year/month/day or ordinals"); } if (containsGregorMD && containsOrdinal) { throw new ConflictingSpecificationError("Can't mix ordinal dates with month/day"); } var useWeekData = definiteWeekDef || normalized.weekday && !containsGregor; // configure ourselves to deal with gregorian dates or week stuff var units = void 0, defaultValues = void 0, objNow = tsToObj(tsNow, offsetProvis); if (useWeekData) { units = orderedWeekUnits; defaultValues = defaultWeekUnitValues; objNow = gregorianToWeek(objNow); } else if (containsOrdinal) { units = orderedOrdinalUnits; defaultValues = defaultOrdinalUnitValues; objNow = gregorianToOrdinal(objNow); } else { units = orderedUnits; defaultValues = defaultUnitValues; } // set default values for missing stuff var foundFirst = false; for (var _iterator2 = units, _isArray2 = Array.isArray(_iterator2), _i2 = 0, _iterator2 = _isArray2 ? _iterator2 : _iterator2[Symbol.iterator]();;) { var _ref3; if (_isArray2) { if (_i2 >= _iterator2.length) break; _ref3 = _iterator2[_i2++]; } else { _i2 = _iterator2.next(); if (_i2.done) break; _ref3 = _i2.value; } var u = _ref3; var v = normalized[u]; if (!isUndefined(v)) { foundFirst = true; } else if (foundFirst) { normalized[u] = defaultValues[u]; } else { normalized[u] = objNow[u]; } } // make sure the values we have are in range var higherOrderInvalid = useWeekData ? hasInvalidWeekData(normalized) : containsOrdinal ? hasInvalidOrdinalData(normalized) : hasInvalidGregorianData(normalized), invalidReason = higherOrderInvalid || hasInvalidTimeData(normalized); if (invalidReason) { return DateTime.invalid(invalidReason); } // compute the actual time var gregorian = useWeekData ? weekToGregorian(normalized) : containsOrdinal ? ordinalToGregorian(normalized) : normalized, _objToTS2 = objToTS(gregorian, offsetProvis, zoneToUse), tsFinal = _objToTS2[0], offsetFinal = _objToTS2[1], inst = new DateTime({ ts: tsFinal, zone: zoneToUse, o: offsetFinal, loc: loc }); // gregorian data + weekday serves only to validate if (normalized.weekday && containsGregor && obj.weekday !== inst.weekday) { return DateTime.invalid('mismatched weekday'); } return inst; }; /** * Create a DateTime from an ISO 8601 string * @param {string} text - the ISO string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the time to this zone * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromISO('2016-05-25T09:08:34.123') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00') * @example DateTime.fromISO('2016-05-25T09:08:34.123+06:00', {setZone: true}) * @example DateTime.fromISO('2016-05-25T09:08:34.123', {zone: 'utc'}) * @example DateTime.fromISO('2016-W05-4') * @return {DateTime} */ DateTime.fromISO = function fromISO(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _parseISODate = parseISODate(text), vals = _parseISODate[0], parsedZone = _parseISODate[1]; return parseDataToDateTime(vals, parsedZone, opts); }; /** * Create a DateTime from an RFC 2822 string * @param {string} text - the RFC 2822 string * @param {Object} opts - options to affect the creation * @param {string|Zone} [opts.zone='local'] - convert the time to this zone. Since the offset is always specified in the string itself, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [opts.setZone=false] - override the zone with a fixed-offset zone specified in the string itself, if it specifies one * @param {string} [opts.locale='en-US'] - a locale to set on the resulting DateTime instance * @param {string} opts.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} opts.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromRFC2822('25 Nov 2016 13:23:12 GMT') * @example DateTime.fromRFC2822('Tue, 25 Nov 2016 13:23:12 +0600') * @example DateTime.fromRFC2822('25 Nov 2016 13:23 Z') * @return {DateTime} */ DateTime.fromRFC2822 = function fromRFC2822(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _parseRFC2822Date = parseRFC2822Date(text), vals = _parseRFC2822Date[0], parsedZone = _parseRFC2822Date[1]; return parseDataToDateTime(vals, parsedZone, opts); }; /** * Create a DateTime from an HTTP header date * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @param {string} text - the HTTP header date * @param {Object} options - options to affect the creation * @param {string|Zone} [options.zone='local'] - convert the time to this zone. Since HTTP dates are always in UTC, this has no effect on the interpretation of string, merely the zone the resulting DateTime is expressed in. * @param {boolean} [options.setZone=false] - override the zone with the fixed-offset zone specified in the string. For HTTP dates, this is always UTC, so this option is equivalent to setting the `zone` option to 'utc', but this option is included for consistency with similar methods. * @param {string} [options.locale='en-US'] - a locale to set on the resulting DateTime instance * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @param {string} options.numberingSystem - the numbering system to set on the resulting DateTime instance * @example DateTime.fromHTTP('Sun, 06 Nov 1994 08:49:37 GMT') * @example DateTime.fromHTTP('Sunday, 06-Nov-94 08:49:37 GMT') * @example DateTime.fromHTTP('Sun Nov 6 08:49:37 1994') * @return {DateTime} */ DateTime.fromHTTP = function fromHTTP(text) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _parseHTTPDate = parseHTTPDate(text), vals = _parseHTTPDate[0], parsedZone = _parseHTTPDate[1]; return parseDataToDateTime(vals, parsedZone, options); }; /** * Create a DateTime from an input string and format string * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options to affect the creation * @param {string|Zone} [options.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [options.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [options.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} options.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @return {DateTime} */ DateTime.fromFormat = function fromFormat(text, fmt) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (isUndefined(text) || isUndefined(fmt)) { throw new InvalidArgumentError('fromFormat requires an input string and a format'); } var _options$locale = options.locale, locale = _options$locale === undefined ? null : _options$locale, _options$numberingSys = options.numberingSystem, numberingSystem = _options$numberingSys === undefined ? null : _options$numberingSys, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }), _parseFromTokens = parseFromTokens(localeToUse, text, fmt), vals = _parseFromTokens[0], parsedZone = _parseFromTokens[1], invalidReason = _parseFromTokens[2]; if (invalidReason) { return DateTime.invalid(invalidReason); } else { return parseDataToDateTime(vals, parsedZone, options); } }; /** * @deprecated use fromFormat instead */ DateTime.fromString = function fromString(text, fmt) { var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return DateTime.fromFormat(text, fmt, opts); }; /** * Create a DateTime from a SQL date, time, or datetime * Defaults to en-US if no locale has been specified, regardless of the system's locale * @param {string} text - the string to parse * @param {Object} options - options to affect the creation * @param {string|Zone} [options.zone='local'] - use this zone if no offset is specified in the input string itself. Will also convert the DateTime to this zone * @param {boolean} [options.setZone=false] - override the zone with a zone specified in the string itself, if it specifies one * @param {string} [options.locale='en-US'] - a locale string to use when parsing. Will also set the DateTime to this locale * @param {string} options.numberingSystem - the numbering system to use when parsing. Will also set the resulting DateTime to this numbering system * @param {string} options.outputCalendar - the output calendar to set on the resulting DateTime instance * @example DateTime.fromSQL('2017-05-15') * @example DateTime.fromSQL('2017-05-15 09:12:34') * @example DateTime.fromSQL('2017-05-15 09:12:34.342') * @example DateTime.fromSQL('2017-05-15 09:12:34.342+06:00') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles') * @example DateTime.fromSQL('2017-05-15 09:12:34.342 America/Los_Angeles', { setZone: true }) * @example DateTime.fromSQL('2017-05-15 09:12:34.342', { zone: 'America/Los_Angeles' }) * @example DateTime.fromSQL('09:12:34.342') * @return {DateTime} */ DateTime.fromSQL = function fromSQL(text) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _parseSQL = parseSQL(text), vals = _parseSQL[0], parsedZone = _parseSQL[1]; return parseDataToDateTime(vals, parsedZone, options); }; /** * Create an invalid DateTime. * @return {DateTime} */ DateTime.invalid = function invalid(reason) { if (!reason) { throw new InvalidArgumentError('need to specify a reason the DateTime is invalid'); } if (Settings.throwOnInvalid) { throw new InvalidDateTimeError(reason); } else { return new DateTime({ invalidReason: reason }); } }; // INFO /** * Get the value of unit. * @param {string} unit - a unit such as 'minute' or 'day' * @example DateTime.local(2017, 7, 4).get('month'); //=> 7 * @example DateTime.local(2017, 7, 4).get('day'); //=> 4 * @return {number} */ DateTime.prototype.get = function get$$1(unit) { return this[unit]; }; /** * Returns whether the DateTime is valid. Invalid DateTimes occur when: * * The DateTime was created from invalid calendar information, such as the 13th month or February 30 * * The DateTime was created by an operation on another invalid date * @type {boolean} */ /** * Returns the resolved Intl options for this DateTime. * This is useful in understanding the behavior of formatting methods * @param {Object} opts - the same options as toLocaleString * @return {Object} */ DateTime.prototype.resolvedLocaleOpts = function resolvedLocaleOpts() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _Formatter$create$res = Formatter.create(this.loc.clone(opts), opts).resolvedOptions(this), locale = _Formatter$create$res.locale, numberingSystem = _Formatter$create$res.numberingSystem, calendar = _Formatter$create$res.calendar; return { locale: locale, numberingSystem: numberingSystem, outputCalendar: calendar }; }; // TRANSFORM /** * "Set" the DateTime's zone to UTC. Returns a newly-constructed DateTime. * * Equivalent to {@link setZone}('utc') * @param {number} [offset=0] - optionally, an offset from UTC in minutes * @param {Object} [opts={}] - options to pass to `setZone()` * @return {DateTime} */ DateTime.prototype.toUTC = function toUTC() { var offset = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.setZone(FixedOffsetZone.instance(offset), opts); }; /** * "Set" the DateTime's zone to the host's local zone. Returns a newly-constructed DateTime. * * Equivalent to `setZone('local')` * @return {DateTime} */ DateTime.prototype.toLocal = function toLocal() { return this.setZone(new LocalZone()); }; /** * "Set" the DateTime's zone to specified zone. Returns a newly-constructed DateTime. * * By default, the setter keeps the underlying time the same (as in, the same UTC timestamp), but the new instance will report different local times and consider DSTs when making computations, as with {@link plus}. You may wish to use {@link toLocal} and {@link toUTC} which provide simple convenience wrappers for commonly used zones. * @param {string|Zone} [zone='local'] - a zone identifier. As a string, that can be any IANA zone supported by the host environment, or a fixed-offset name of the form 'utc+3', or the strings 'local' or 'utc'. You may also supply an instance of a {@link Zone} class. * @param {Object} opts - options * @param {boolean} [opts.keepLocalTime=false] - If true, adjust the underlying time so that the local time stays the same, but in the target zone. You should rarely need this. * @return {DateTime} */ DateTime.prototype.setZone = function setZone(zone) { var _ref4 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, _ref4$keepLocalTime = _ref4.keepLocalTime, keepLocalTime = _ref4$keepLocalTime === undefined ? false : _ref4$keepLocalTime, _ref4$keepCalendarTim = _ref4.keepCalendarTime, keepCalendarTime = _ref4$keepCalendarTim === undefined ? false : _ref4$keepCalendarTim; zone = normalizeZone(zone, Settings.defaultZone); if (zone.equals(this.zone)) { return this; } else if (!zone.isValid) { return DateTime.invalid(UNSUPPORTED_ZONE); } else { var newTS = keepLocalTime || keepCalendarTime // keepCalendarTime is the deprecated name for keepLocalTime ? this.ts + (this.o - zone.offset(this.ts)) * 60 * 1000 : this.ts; return clone(this, { ts: newTS, zone: zone }); } }; /** * "Set" the locale, numberingSystem, or outputCalendar. Returns a newly-constructed DateTime. * @param {Object} properties - the properties to set * @example DateTime.local(2017, 5, 25).reconfigure({ locale: 'en-GB' }) * @return {DateTime} */ DateTime.prototype.reconfigure = function reconfigure() { var _ref5 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, locale = _ref5.locale, numberingSystem = _ref5.numberingSystem, outputCalendar = _ref5.outputCalendar; var loc = this.loc.clone({ locale: locale, numberingSystem: numberingSystem, outputCalendar: outputCalendar }); return clone(this, { loc: loc }); }; /** * "Set" the locale. Returns a newly-constructed DateTime. * Just a convenient alias for reconfigure({ locale }) * @example DateTime.local(2017, 5, 25).setLocale('en-GB') * @return {DateTime} */ DateTime.prototype.setLocale = function setLocale(locale) { return this.reconfigure({ locale: locale }); }; /** * "Set" the values of specified units. Returns a newly-constructed DateTime. * You can only set units with this method; for "setting" metadata, see {@link reconfigure} and {@link setZone}. * @param {Object} values - a mapping of units to numbers * @example dt.set({ year: 2017 }) * @example dt.set({ hour: 8, minute: 30 }) * @example dt.set({ weekday: 5 }) * @example dt.set({ year: 2005, ordinal: 234 }) * @return {DateTime} */ DateTime.prototype.set = function set$$1(values) { if (!this.isValid) return this; var normalized = normalizeObject(values, normalizeUnit), settingWeekStuff = !isUndefined(normalized.weekYear) || !isUndefined(normalized.weekNumber) || !isUndefined(normalized.weekday); var mixed = void 0; if (settingWeekStuff) { mixed = weekToGregorian(Object.assign(gregorianToWeek(this.c), normalized)); } else if (!isUndefined(normalized.ordinal)) { mixed = ordinalToGregorian(Object.assign(gregorianToOrdinal(this.c), normalized)); } else { mixed = Object.assign(this.toObject(), normalized); // if we didn't set the day but we ended up on an overflow date, // use the last day of the right month if (isUndefined(normalized.day)) { mixed.day = Math.min(daysInMonth(mixed.year, mixed.month), mixed.day); } } var _objToTS3 = objToTS(mixed, this.o, this.zone), ts = _objToTS3[0], o = _objToTS3[1]; return clone(this, { ts: ts, o: o }); }; /** * Add a period of time to this DateTime and return the resulting DateTime * * Adding hours, minutes, seconds, or milliseconds increases the timestamp by the right number of milliseconds. Adding days, months, or years shifts the calendar, accounting for DSTs and leap years along the way. Thus, `dt.plus({ hours: 24 })` may result in a different time than `dt.plus({ days: 1 })` if there's a DST shift in between. * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() * @example DateTime.local().plus(123) //~> in 123 milliseconds * @example DateTime.local().plus({ minutes: 15 }) //~> in 15 minutes * @example DateTime.local().plus({ days: 1 }) //~> this time tomorrow * @example DateTime.local().plus({ days: -1 }) //~> this time yesterday * @example DateTime.local().plus({ hours: 3, minutes: 13 }) //~> in 1 hr, 13 min * @example DateTime.local().plus(Duration.fromObject({ hours: 3, minutes: 13 })) //~> in 1 hr, 13 min * @return {DateTime} */ DateTime.prototype.plus = function plus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration); return clone(this, adjustTime(this, dur)); }; /** * Subtract a period of time to this DateTime and return the resulting DateTime * See {@link plus} * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject() @return {DateTime} */ DateTime.prototype.minus = function minus(duration) { if (!this.isValid) return this; var dur = friendlyDuration(duration).negate(); return clone(this, adjustTime(this, dur)); }; /** * "Set" this DateTime to the beginning of a unit of time. * @param {string} unit - The unit to go to the beginning of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).startOf('month').toISODate(); //=> '2014-03-01' * @example DateTime.local(2014, 3, 3).startOf('year').toISODate(); //=> '2014-01-01' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('day').toISOTime(); //=> '00:00.000-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).startOf('hour').toISOTime(); //=> '05:00:00.000-05:00' * @return {DateTime} */ DateTime.prototype.startOf = function startOf(unit) { if (!this.isValid) return this; var o = {}, normalizedUnit = Duration.normalizeUnit(unit); switch (normalizedUnit) { case 'years': o.month = 1; // falls through case 'quarters': case 'months': o.day = 1; // falls through case 'weeks': case 'days': o.hour = 0; // falls through case 'hours': o.minute = 0; // falls through case 'minutes': o.second = 0; // falls through case 'seconds': o.millisecond = 0; break; case 'milliseconds': break; default: throw new InvalidUnitError(unit); } if (normalizedUnit === 'weeks') { o.weekday = 1; } if (normalizedUnit === 'quarters') { var q = Math.ceil(this.month / 3); o.month = (q - 1) * 3 + 1; } return this.set(o); }; /** * "Set" this DateTime to the end (i.e. the last millisecond) of a unit of time * @param {string} unit - The unit to go to the end of. Can be 'year', 'month', 'day', 'hour', 'minute', 'second', or 'millisecond'. * @example DateTime.local(2014, 3, 3).endOf('month').toISO(); //=> '2014-03-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3).endOf('year').toISO(); //=> '2014-12-31T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('day').toISO(); //=> '2014-03-03T23:59:59.999-05:00' * @example DateTime.local(2014, 3, 3, 5, 30).endOf('hour').toISO(); //=> '2014-03-03T05:59:59.999-05:00' * @return {DateTime} */ DateTime.prototype.endOf = function endOf(unit) { var _startOf$plus; return this.isValid ? this.startOf(unit).plus((_startOf$plus = {}, _startOf$plus[unit] = 1, _startOf$plus)).minus(1) : this; }; // OUTPUT /** * Returns a string representation of this DateTime formatted according to the specified format string. * **You may not want this.** See {@link toLocaleString} for a more flexible formatting tool. For a table of tokens and their interpretations, see [here](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens). * Defaults to en-US if no locale has been specified, regardless of the system's locale. * @see https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens * @param {string} fmt - the format string * @param {Object} opts - options * @param {boolean} opts.round - round numerical values * @example DateTime.local().toFormat('yyyy LLL dd') //=> '2017 Apr 22' * @example DateTime.local().setLocale('fr').toFormat('yyyy LLL dd') //=> '2017 avr. 22' * @example DateTime.local().toFormat("HH 'hours and' mm 'minutes'") //=> '20 hours and 55 minutes' * @return {string} */ DateTime.prototype.toFormat = function toFormat(fmt) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.isValid ? Formatter.create(this.loc.redefaultToEN(), opts).formatDateTimeFromString(this, fmt) : INVALID; }; /** * Returns a localized string representing this date. Accepts the same options as the Intl.DateTimeFormat constructor and any presets defined by Luxon, such as `DateTime.DATE_FULL` or `DateTime.TIME_SIMPLE`. * The exact behavior of this method is browser-specific, but in general it will return an appropriate representation. * of the DateTime in the assigned locale. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat * @param opts {Object} - Intl.DateTimeFormat constructor options * @example DateTime.local().toLocaleString(); //=> 4/20/2017 * @example DateTime.local().setLocale('en-gb').toLocaleString(); //=> '20/04/2017' * @example DateTime.local().toLocaleString(DateTime.DATE_FULL); //=> 'April 20, 2017' * @example DateTime.local().toLocaleString(DateTime.TIME_SIMPLE); //=> '11:32 AM' * @example DateTime.local().toLocaleString(DateTime.DATETIME_SHORT); //=> '4/20/2017, 11:32 AM' * @example DateTime.local().toLocaleString({weekday: 'long', month: 'long', day: '2-digit'}); //=> 'Thu, Apr 20' * @example DateTime.local().toLocaleString({weekday: 'long', month: 'long', day: '2-digit', hour: '2-digit', minute: '2-digit'}); //=> 'Thu, Apr 20, 11:27' * @example DateTime.local().toLocaleString({hour: '2-digit', minute: '2-digit'}); //=> '11:32' * @return {string} */ DateTime.prototype.toLocaleString = function toLocaleString() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DATE_SHORT; return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTime(this) : INVALID; }; /** * Returns an array of format "parts", i.e. individual tokens along with metadata. This is allows callers to post-process individual sections of the formatted output. * Defaults to the system's locale if no locale has been specified * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DateTimeFormat/formatToParts * @param opts {Object} - Intl.DateTimeFormat constructor options, same as `toLocaleString`. * @example DateTime.local().toLocaleString(); //=> [ * //=> { type: 'day', value: '25' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'month', value: '05' }, * //=> { type: 'literal', value: '/' }, * //=> { type: 'year', value: '1982' } * //=> ] */ DateTime.prototype.toLocaleParts = function toLocaleParts() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; return this.isValid ? Formatter.create(this.loc.clone(opts), opts).formatDateTimeParts(this) : []; }; /** * Returns an ISO 8601-compliant string representation of this DateTime * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc(1982, 5, 25).toISO() //=> '1982-05-25T00:00:00.000Z' * @example DateTime.local().toISO() //=> '2017-04-22T20:47:05.335-04:00' * @example DateTime.local().toISO({ includeOffset: false }) //=> '2017-04-22T20:47:05.335' * @return {string} */ DateTime.prototype.toISO = function toISO() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) { return null; } return this.toISODate() + 'T' + this.toISOTime(opts); }; /** * Returns an ISO 8601-compliant string representation of this DateTime's date component * @example DateTime.utc(1982, 5, 25).toISODate() //=> '1982-05-25' * @return {string} */ DateTime.prototype.toISODate = function toISODate() { return toTechFormat(this, 'yyyy-MM-dd'); }; /** * Returns an ISO 8601-compliant string representation of this DateTime's week date * @example DateTime.utc(1982, 5, 25).toISOWeekDate() //=> '1982-W21-2' * @return {string} */ DateTime.prototype.toISOWeekDate = function toISOWeekDate() { return toTechFormat(this, "kkkk-'W'WW-c"); }; /** * Returns an ISO 8601-compliant string representation of this DateTime's time component * @param {Object} opts - options * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0 * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0 * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc().hour(7).minute(34).toISOTime() //=> '07:34:19.361Z' * @example DateTime.utc().hour(7).minute(34).toISOTime({ suppressSeconds: true }) //=> '07:34Z' * @return {string} */ DateTime.prototype.toISOTime = function toISOTime() { var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref6$suppressMillise = _ref6.suppressMilliseconds, suppressMilliseconds = _ref6$suppressMillise === undefined ? false : _ref6$suppressMillise, _ref6$suppressSeconds = _ref6.suppressSeconds, suppressSeconds = _ref6$suppressSeconds === undefined ? false : _ref6$suppressSeconds, _ref6$includeOffset = _ref6.includeOffset, includeOffset = _ref6$includeOffset === undefined ? true : _ref6$includeOffset; return toTechTimeFormat(this, { suppressSeconds: suppressSeconds, suppressMilliseconds: suppressMilliseconds, includeOffset: includeOffset }); }; /** * Returns an RFC 2822-compatible string representation of this DateTime, always in UTC * @example DateTime.utc(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 +0000' * @example DateTime.local(2014, 7, 13).toRFC2822() //=> 'Sun, 13 Jul 2014 00:00:00 -0400' * @return {string} */ DateTime.prototype.toRFC2822 = function toRFC2822() { return toTechFormat(this, 'EEE, dd LLL yyyy hh:mm:ss ZZZ'); }; /** * Returns a string representation of this DateTime appropriate for use in HTTP headers. * Specifically, the string conforms to RFC 1123. * @see https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1 * @example DateTime.utc(2014, 7, 13).toHTTP() //=> 'Sun, 13 Jul 2014 00:00:00 GMT' * @example DateTime.utc(2014, 7, 13, 19).toHTTP() //=> 'Sun, 13 Jul 2014 19:00:00 GMT' * @return {string} */ DateTime.prototype.toHTTP = function toHTTP() { return toTechFormat(this.toUTC(), "EEE, dd LLL yyyy HH:mm:ss 'GMT'"); }; /** * Returns a string representation of this DateTime appropriate for use in SQL Date * @example DateTime.utc(2014, 7, 13).toSQLDate() //=> '2014-07-13' * @return {string} */ DateTime.prototype.toSQLDate = function toSQLDate() { return toTechFormat(this, 'yyyy-MM-dd'); }; /** * Returns a string representation of this DateTime appropriate for use in SQL Time * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc().toSQL() //=> '05:15:16.345' * @example DateTime.local().toSQL() //=> '05:15:16.345 -04:00' * @example DateTime.local().toSQL({ includeOffset: false }) //=> '05:15:16.345' * @example DateTime.local().toSQL({ includeZone: false }) //=> '05:15:16.345 America/New_York' * @return {string} */ DateTime.prototype.toSQLTime = function toSQLTime() { var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref7$includeOffset = _ref7.includeOffset, includeOffset = _ref7$includeOffset === undefined ? true : _ref7$includeOffset, _ref7$includeZone = _ref7.includeZone, includeZone = _ref7$includeZone === undefined ? false : _ref7$includeZone; return toTechTimeFormat(this, { includeOffset: includeOffset, includeZone: includeZone, spaceZone: true }); }; /** * Returns a string representation of this DateTime appropriate for use in SQL DateTime * @param {Object} opts - options * @param {boolean} [opts.includeZone=false] - include the zone, such as 'America/New_York'. Overrides includeOffset. * @param {boolean} [opts.includeOffset=true] - include the offset, such as 'Z' or '-04:00' * @example DateTime.utc(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 Z' * @example DateTime.local(2014, 7, 13).toSQL() //=> '2014-07-13 00:00:00.000 -04:00' * @example DateTime.local(2014, 7, 13).toSQL({ includeOffset: false }) //=> '2014-07-13 00:00:00.000' * @example DateTime.local(2014, 7, 13).toSQL({ includeZone: false }) //=> '2014-07-13 00:00:00.000 America/New_York' * @return {string} */ DateTime.prototype.toSQL = function toSQL() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) { return null; } return this.toSQLDate() + ' ' + this.toSQLTime(opts); }; /** * Returns a string representation of this DateTime appropriate for debugging * @return {string} */ DateTime.prototype.toString = function toString() { return this.isValid ? this.toISO() : INVALID; }; /** * Returns a string representation of this DateTime appropriate for the REPL. * @return {string} */ DateTime.prototype[customInspectSymbol] = function () { if (this.isValid) { return 'DateTime {\n ts: ' + this.toISO() + ',\n zone: ' + this.zone.name + ',\n locale: ' + this.locale + ' }'; } else { return 'DateTime { Invalid, reason: ' + this.invalidReason + ' }'; } }; /** * Returns the epoch milliseconds of this DateTime. Alias of {@link toMillis} * @return {number} */ DateTime.prototype.valueOf = function valueOf() { return this.toMillis(); }; /** * Returns the epoch milliseconds of this DateTime. * @return {number} */ DateTime.prototype.toMillis = function toMillis() { return this.isValid ? this.ts : NaN; }; /** * Returns an ISO 8601 representation of this DateTime appropriate for use in JSON. * @return {string} */ DateTime.prototype.toJSON = function toJSON() { return this.toISO(); }; /** * Returns a BSON serializable equivalent to this DateTime. * @return {Date} */ DateTime.prototype.toBSON = function toBSON() { return this.toJSDate(); }; /** * Returns a Javascript object with this DateTime's year, month, day, and so on. * @param opts - options for generating the object * @param {boolean} [opts.includeConfig=false] - include configuration attributes in the output * @example DateTime.local().toObject() //=> { year: 2017, month: 4, day: 22, hour: 20, minute: 49, second: 42, millisecond: 268 } * @return {Object} */ DateTime.prototype.toObject = function toObject() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; if (!this.isValid) return {}; var base = Object.assign({}, this.c); if (opts.includeConfig) { base.outputCalendar = this.outputCalendar; base.numberingSystem = this.loc.numberingSystem; base.locale = this.loc.locale; } return base; }; /** * Returns a Javascript Date equivalent to this DateTime. * @return {Date} */ DateTime.prototype.toJSDate = function toJSDate() { return new Date(this.isValid ? this.ts : NaN); }; // COMPARE /** * Return the difference between two DateTimes as a Duration. * @param {DateTime} otherDateTime - the DateTime to compare this one to * @param {string|string[]} [unit=['milliseconds']] - the unit or array of units (such as 'hours' or 'days') to include in the duration. * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @example * var i1 = DateTime.fromISO('1982-05-25T09:45'), * i2 = DateTime.fromISO('1983-10-14T10:30'); * i2.diff(i1).toObject() //=> { milliseconds: 43807500000 } * i2.diff(i1, 'hours').toObject() //=> { hours: 12168.75 } * i2.diff(i1, ['months', 'days']).toObject() //=> { months: 16, days: 19.03125 } * i2.diff(i1, ['months', 'days', 'hours']).toObject() //=> { months: 16, days: 19, hours: 0.75 } * @return {Duration} */ DateTime.prototype.diff = function diff(otherDateTime) { var unit = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'milliseconds'; var opts = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!this.isValid || !otherDateTime.isValid) return Duration.invalid(this.invalidReason || otherDateTime.invalidReason); var units = maybeArray(unit).map(Duration.normalizeUnit), otherIsLater = otherDateTime.valueOf() > this.valueOf(), earlier = otherIsLater ? this : otherDateTime, later = otherIsLater ? otherDateTime : this, diffed = _diff(earlier, later, units, opts); return otherIsLater ? diffed.negate() : diffed; }; /** * Return the difference between this DateTime and right now. * See {@link diff} * @param {string|string[]} [unit=['milliseconds']] - the unit or units units (such as 'hours' or 'days') to include in the duration * @param {Object} opts - options that affect the creation of the Duration * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use * @return {Duration} */ DateTime.prototype.diffNow = function diffNow() { var unit = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'milliseconds'; var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return this.diff(DateTime.local(), unit, opts); }; /** * Return an Interval spanning between this DateTime and another DateTime * @param {DateTime} otherDateTime - the other end point of the Interval * @return {Interval} */ DateTime.prototype.until = function until(otherDateTime) { return this.isValid ? Interval.fromDateTimes(this, otherDateTime) : this; }; /** * Return whether this DateTime is in the same unit of time as another DateTime * @param {DateTime} otherDateTime - the other DateTime * @param {string} unit - the unit of time to check sameness on * @example DateTime.local().hasSame(otherDT, 'day'); //~> true if both the same calendar day * @return {boolean} */ DateTime.prototype.hasSame = function hasSame(otherDateTime, unit) { if (!this.isValid) return false; if (unit === 'millisecond') { return this.valueOf() === otherDateTime.valueOf(); } else { var inputMs = otherDateTime.valueOf(); return this.startOf(unit) <= inputMs && inputMs <= this.endOf(unit); } }; /** * Equality check * Two DateTimes are equal iff they represent the same millisecond, have the same zone and location, and are both valid. * To compare just the millisecond values, use `+dt1 === ~dt2`. * @param {DateTime} other - the other DateTime * @return {boolean} */ DateTime.prototype.equals = function equals(other) { return this.isValid && other.isValid && this.valueOf() === other.valueOf() && this.zone.equals(other.zone) && this.loc.equals(other.loc); }; /** * Return the min of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the minimum * @return {DateTime} the min DateTime, or undefined if called with no argument */ DateTime.min = function min() { for (var _len = arguments.length, dateTimes = Array(_len), _key = 0; _key < _len; _key++) { dateTimes[_key] = arguments[_key]; } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.min); }; /** * Return the max of several date times * @param {...DateTime} dateTimes - the DateTimes from which to choose the maximum * @return {DateTime} the max DateTime, or undefined if called with no argument */ DateTime.max = function max() { for (var _len2 = arguments.length, dateTimes = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { dateTimes[_key2] = arguments[_key2]; } return bestBy(dateTimes, function (i) { return i.valueOf(); }, Math.max); }; // MISC /** * Explain how a string would be parsed by fromFormat() * @param {string} text - the string to parse * @param {string} fmt - the format the string is expected to be in (see description) * @param {Object} options - options taken by fromFormat() * @return {Object} */ DateTime.fromFormatExplain = function fromFormatExplain(text, fmt) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _options$locale2 = options.locale, locale = _options$locale2 === undefined ? null : _options$locale2, _options$numberingSys2 = options.numberingSystem, numberingSystem = _options$numberingSys2 === undefined ? null : _options$numberingSys2, localeToUse = Locale.fromOpts({ locale: locale, numberingSystem: numberingSystem, defaultToEN: true }); return explainFromTokens(localeToUse, text, fmt); }; /** * @deprecated use fromFormatExplain instead */ DateTime.fromStringExplain = function fromStringExplain(text, fmt) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; return DateTime.fromFormatExplain(text, fmt, options); }; // FORMAT PRESETS /** * {@link toLocaleString} format like 10/14/1983 * @type {Object} */ createClass(DateTime, [{ key: 'isValid', get: function get$$1() { return this.invalidReason === null; } /** * Returns an explanation of why this DateTime became invalid, or null if the DateTime is valid * @type {string} */ }, { key: 'invalidReason', get: function get$$1() { return this.invalid; } /** * Get the locale of a DateTime, such 'en-GB'. The locale is used when formatting the DateTime * * @type {string} */ }, { key: 'locale', get: function get$$1() { return this.isValid ? this.loc.locale : null; } /** * Get the numbering system of a DateTime, such 'beng'. The numbering system is used when formatting the DateTime * * @type {string} */ }, { key: 'numberingSystem', get: function get$$1() { return this.isValid ? this.loc.numberingSystem : null; } /** * Get the output calendar of a DateTime, such 'islamic'. The output calendar is used when formatting the DateTime * * @type {string} */ }, { key: 'outputCalendar', get: function get$$1() { return this.isValid ? this.loc.outputCalendar : null; } /** * Get the name of the time zone. * @type {string} */ }, { key: 'zoneName', get: function get$$1() { return this.isValid ? this.zone.name : null; } /** * Get the year * @example DateTime.local(2017, 5, 25).year //=> 2017 * @type {number} */ }, { key: 'year', get: function get$$1() { return this.isValid ? this.c.year : NaN; } /** * Get the quarter * @example DateTime.local(2017, 5, 25).quarter //=> 2 * @type {number} */ }, { key: 'quarter', get: function get$$1() { return this.isValid ? Math.ceil(this.c.month / 3) : NaN; } /** * Get the month (1-12). * @example DateTime.local(2017, 5, 25).month //=> 5 * @type {number} */ }, { key: 'month', get: function get$$1() { return this.isValid ? this.c.month : NaN; } /** * Get the day of the month (1-30ish). * @example DateTime.local(2017, 5, 25).day //=> 25 * @type {number} */ }, { key: 'day', get: function get$$1() { return this.isValid ? this.c.day : NaN; } /** * Get the hour of the day (0-23). * @example DateTime.local(2017, 5, 25, 9).hour //=> 9 * @type {number} */ }, { key: 'hour', get: function get$$1() { return this.isValid ? this.c.hour : NaN; } /** * Get the minute of the hour (0-59). * @example DateTime.local(2017, 5, 25, 9, 30).minute //=> 30 * @type {number} */ }, { key: 'minute', get: function get$$1() { return this.isValid ? this.c.minute : NaN; } /** * Get the second of the minute (0-59). * @example DateTime.local(2017, 5, 25, 9, 30, 52).second //=> 52 * @type {number} */ }, { key: 'second', get: function get$$1() { return this.isValid ? this.c.second : NaN; } /** * Get the millisecond of the second (0-999). * @example DateTime.local(2017, 5, 25, 9, 30, 52, 654).millisecond //=> 654 * @type {number} */ }, { key: 'millisecond', get: function get$$1() { return this.isValid ? this.c.millisecond : NaN; } /** * Get the week year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekYear //=> 2015 * @type {number} */ }, { key: 'weekYear', get: function get$$1() { return this.isValid ? possiblyCachedWeekData(this).weekYear : NaN; } /** * Get the week number of the week year (1-52ish). * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2017, 5, 25).weekNumber //=> 21 * @type {number} */ }, { key: 'weekNumber', get: function get$$1() { return this.isValid ? possiblyCachedWeekData(this).weekNumber : NaN; } /** * Get the day of the week. * 1 is Monday and 7 is Sunday * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2014, 11, 31).weekday //=> 4 * @type {number} */ }, { key: 'weekday', get: function get$$1() { return this.isValid ? possiblyCachedWeekData(this).weekday : NaN; } /** * Get the ordinal (i.e. the day of the year) * @example DateTime.local(2017, 5, 25).ordinal //=> 145 * @type {number|DateTime} */ }, { key: 'ordinal', get: function get$$1() { return this.isValid ? gregorianToOrdinal(this.c).ordinal : NaN; } /** * Get the human readable short month name, such as 'Oct'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthShort //=> Oct * @type {string} */ }, { key: 'monthShort', get: function get$$1() { return this.isValid ? Info.months('short', { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable long month name, such as 'October'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).monthLong //=> October * @type {string} */ }, { key: 'monthLong', get: function get$$1() { return this.isValid ? Info.months('long', { locale: this.locale })[this.month - 1] : null; } /** * Get the human readable short weekday, such as 'Mon'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayShort //=> Mon * @type {string} */ }, { key: 'weekdayShort', get: function get$$1() { return this.isValid ? Info.weekdays('short', { locale: this.locale })[this.weekday - 1] : null; } /** * Get the human readable long weekday, such as 'Monday'. * Defaults to the system's locale if no locale has been specified * @example DateTime.local(2017, 10, 30).weekdayLong //=> Monday * @type {string} */ }, { key: 'weekdayLong', get: function get$$1() { return this.isValid ? Info.weekdays('long', { locale: this.locale })[this.weekday - 1] : null; } /** * Get the UTC offset of this DateTime in minutes * @example DateTime.local().offset //=> -240 * @example DateTime.utc().offset //=> 0 * @type {number} */ }, { key: 'offset', get: function get$$1() { return this.isValid ? this.zone.offset(this.ts) : NaN; } /** * Get the short human name for the zone's current offset, for example "EST" or "EDT". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: 'offsetNameShort', get: function get$$1() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: 'short', locale: this.locale }); } else { return null; } } /** * Get the long human name for the zone's current offset, for example "Eastern Standard Time" or "Eastern Daylight Time". * Defaults to the system's locale if no locale has been specified * @type {string} */ }, { key: 'offsetNameLong', get: function get$$1() { if (this.isValid) { return this.zone.offsetName(this.ts, { format: 'long', locale: this.locale }); } else { return null; } } /** * Get whether this zone's offset ever changes, as in a DST. * @type {boolean} */ }, { key: 'isOffsetFixed', get: function get$$1() { return this.isValid ? this.zone.universal : null; } /** * Get whether the DateTime is in a DST. * @type {boolean} */ }, { key: 'isInDST', get: function get$$1() { if (this.isOffsetFixed) { return false; } else { return this.offset > this.set({ month: 1 }).offset || this.offset > this.set({ month: 5 }).offset; } } /** * Returns true if this DateTime is in a leap year, false otherwise * @example DateTime.local(2016).isInLeapYear //=> true * @example DateTime.local(2013).isInLeapYear //=> false * @type {boolean} */ }, { key: 'isInLeapYear', get: function get$$1() { return isLeapYear(this.year); } /** * Returns the number of days in this DateTime's month * @example DateTime.local(2016, 2).daysInMonth //=> 29 * @example DateTime.local(2016, 3).daysInMonth //=> 31 * @type {number} */ }, { key: 'daysInMonth', get: function get$$1() { return daysInMonth(this.year, this.month); } /** * Returns the number of days in this DateTime's year * @example DateTime.local(2016).daysInYear //=> 366 * @example DateTime.local(2013).daysInYear //=> 365 * @type {number} */ }, { key: 'daysInYear', get: function get$$1() { return this.isValid ? daysInYear(this.year) : NaN; } /** * Returns the number of weeks in this DateTime's year * @see https://en.wikipedia.org/wiki/ISO_week_date * @example DateTime.local(2004).weeksInWeekYear //=> 53 * @example DateTime.local(2013).weeksInWeekYear //=> 52 * @type {number} */ }, { key: 'weeksInWeekYear', get: function get$$1() { return this.isValid ? weeksInWeekYear(this.weekYear) : NaN; } }], [{ key: 'DATE_SHORT', get: function get$$1() { return DATE_SHORT; } /** * {@link toLocaleString} format like 'Oct 14, 1983' * @type {Object} */ }, { key: 'DATE_MED', get: function get$$1() { return DATE_MED; } /** * {@link toLocaleString} format like 'October 14, 1983' * @type {Object} */ }, { key: 'DATE_FULL', get: function get$$1() { return DATE_FULL; } /** * {@link toLocaleString} format like 'Tuesday, October 14, 1983' * @type {Object} */ }, { key: 'DATE_HUGE', get: function get$$1() { return DATE_HUGE; } /** * {@link toLocaleString} format like '09:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'TIME_SIMPLE', get: function get$$1() { return TIME_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'TIME_WITH_SECONDS', get: function get$$1() { return TIME_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'TIME_WITH_SHORT_OFFSET', get: function get$$1() { return TIME_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'TIME_WITH_LONG_OFFSET', get: function get$$1() { return TIME_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '09:30', always 24-hour. * @type {Object} */ }, { key: 'TIME_24_SIMPLE', get: function get$$1() { return TIME_24_SIMPLE; } /** * {@link toLocaleString} format like '09:30:23', always 24-hour. * @type {Object} */ }, { key: 'TIME_24_WITH_SECONDS', get: function get$$1() { return TIME_24_WITH_SECONDS; } /** * {@link toLocaleString} format like '09:30:23 EDT', always 24-hour. * @type {Object} */ }, { key: 'TIME_24_WITH_SHORT_OFFSET', get: function get$$1() { return TIME_24_WITH_SHORT_OFFSET; } /** * {@link toLocaleString} format like '09:30:23 Eastern Daylight Time', always 24-hour. * @type {Object} */ }, { key: 'TIME_24_WITH_LONG_OFFSET', get: function get$$1() { return TIME_24_WITH_LONG_OFFSET; } /** * {@link toLocaleString} format like '10/14/1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_SHORT', get: function get$$1() { return DATETIME_SHORT; } /** * {@link toLocaleString} format like '10/14/1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_SHORT_WITH_SECONDS', get: function get$$1() { return DATETIME_SHORT_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_MED', get: function get$$1() { return DATETIME_MED; } /** * {@link toLocaleString} format like 'Oct 14, 1983, 9:30:33 AM'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_MED_WITH_SECONDS', get: function get$$1() { return DATETIME_MED_WITH_SECONDS; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_FULL', get: function get$$1() { return DATETIME_FULL; } /** * {@link toLocaleString} format like 'October 14, 1983, 9:30:33 AM EDT'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_FULL_WITH_SECONDS', get: function get$$1() { return DATETIME_FULL_WITH_SECONDS; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_HUGE', get: function get$$1() { return DATETIME_HUGE; } /** * {@link toLocaleString} format like 'Friday, October 14, 1983, 9:30:33 AM Eastern Daylight Time'. Only 12-hour if the locale is. * @type {Object} */ }, { key: 'DATETIME_HUGE_WITH_SECONDS', get: function get$$1() { return DATETIME_HUGE_WITH_SECONDS; } }]); return DateTime; }(); function friendlyDateTime(dateTimeish) { if (dateTimeish instanceof DateTime) { return dateTimeish; } else if (dateTimeish.valueOf && isNumber(dateTimeish.valueOf())) { return DateTime.fromJSDate(dateTimeish); } else if ((typeof dateTimeish === 'undefined' ? 'undefined' : _typeof(dateTimeish)) === 'object') { return DateTime.fromObject(dateTimeish); } else { throw new InvalidArgumentError('Unknown datetime argument'); } } exports.DateTime = DateTime; exports.Duration = Duration; exports.Interval = Interval; exports.Info = Info; exports.Zone = Zone; exports.FixedOffsetZone = FixedOffsetZone; exports.IANAZone = IANAZone; exports.LocalZone = LocalZone; exports.Settings = Settings; //# sourceMappingURL=luxon.js.map /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = __webpack_require__(6); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = __webpack_require__(7); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(4), __webpack_require__(5))) /***/ }), /* 4 */ /***/ (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 || Function("return this")() || (1, eval)("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; /***/ }), /* 5 */ /***/ (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; }; /***/ }), /* 6 */ /***/ (function(module, exports) { module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } /***/ }), /* 7 */ /***/ (function(module, exports) { if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } /***/ }), /* 8 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // CONCATENATED MODULE: ./src/nlp/i18n.ts // ============================================================================= // i18n // ============================================================================= var ENGLISH = { dayNames: [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ], monthNames: [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ], tokens: { 'SKIP': /^[ \r\n\t]+|^\.$/, 'number': /^[1-9][0-9]*/, 'numberAsText': /^(one|two|three)/i, 'every': /^every/i, 'day(s)': /^days?/i, 'weekday(s)': /^weekdays?/i, 'week(s)': /^weeks?/i, 'hour(s)': /^hours?/i, 'minute(s)': /^minutes?/i, 'month(s)': /^months?/i, 'year(s)': /^years?/i, 'on': /^(on|in)/i, 'at': /^(at)/i, 'the': /^the/i, 'first': /^first/i, 'second': /^second/i, 'third': /^third/i, 'nth': /^([1-9][0-9]*)(\.|th|nd|rd|st)/i, 'last': /^last/i, 'for': /^for/i, 'time(s)': /^times?/i, 'until': /^(un)?til/i, 'monday': /^mo(n(day)?)?/i, 'tuesday': /^tu(e(s(day)?)?)?/i, 'wednesday': /^we(d(n(esday)?)?)?/i, 'thursday': /^th(u(r(sday)?)?)?/i, 'friday': /^fr(i(day)?)?/i, 'saturday': /^sa(t(urday)?)?/i, 'sunday': /^su(n(day)?)?/i, 'january': /^jan(uary)?/i, 'february': /^feb(ruary)?/i, 'march': /^mar(ch)?/i, 'april': /^apr(il)?/i, 'may': /^may/i, 'june': /^june?/i, 'july': /^july?/i, 'august': /^aug(ust)?/i, 'september': /^sep(t(ember)?)?/i, 'october': /^oct(ober)?/i, 'november': /^nov(ember)?/i, 'december': /^dec(ember)?/i, 'comma': /^(,\s*|(and|or)\s*)+/i } }; /* harmony default export */ var i18n = (ENGLISH); // EXTERNAL MODULE: ./src/index.ts + 23 modules var src = __webpack_require__(1); // EXTERNAL MODULE: ./src/helpers.ts var helpers = __webpack_require__(0); // CONCATENATED MODULE: ./src/nlp/totext.ts // ============================================================================= // Helper functions // ============================================================================= /** * Return true if a value is in an array */ var contains = function (arr, val) { return arr.indexOf(val) !== -1; }; var defaultGetText = function (id) { return id.toString(); }; var defaultDateFormatter = function (year, month, day) { return month + " " + day + ", " + year; }; /** * * @param {RRule} rrule * Optional: * @param {Function} gettext function * @param {Object} language definition * @constructor */ var totext_ToText = /** @class */ (function () { function ToText(rrule, gettext, language, dateFormatter) { if (gettext === void 0) { gettext = defaultGetText; } if (language === void 0) { language = i18n; } if (dateFormatter === void 0) { dateFormatter = defaultDateFormatter; } this.text = []; this.language = language || i18n; this.gettext = gettext; this.dateFormatter = dateFormatter; this.rrule = rrule; this.options = rrule.options; this.origOptions = rrule.origOptions; if (this.origOptions.bymonthday) { var bymonthday = [].concat(this.options.bymonthday); var bynmonthday = [].concat(this.options.bynmonthday); bymonthday.sort(function (a, b) { return a - b; }); bynmonthday.sort(function (a, b) { return b - a; }); // 1, 2, 3, .., -5, -4, -3, .. this.bymonthday = bymonthday.concat(bynmonthday); if (!this.bymonthday.length) this.bymonthday = null; } if (Object(helpers["f" /* isPresent */])(this.origOptions.byweekday)) { var byweekday = !Object(helpers["d" /* isArray */])(this.origOptions.byweekday) ? [this.origOptions.byweekday] : this.origOptions.byweekday; var days = String(byweekday); this.byweekday = { allWeeks: byweekday.filter(function (weekday) { return !weekday.n; }), someWeeks: byweekday.filter(function (weekday) { return Boolean(weekday.n); }), isWeekdays: days.indexOf('MO') !== -1 && days.indexOf('TU') !== -1 && days.indexOf('WE') !== -1 && days.indexOf('TH') !== -1 && days.indexOf('FR') !== -1 && days.indexOf('SA') === -1 && days.indexOf('SU') === -1, isEveryDay: days.indexOf('MO') !== -1 && days.indexOf('TU') !== -1 && days.indexOf('WE') !== -1 && days.indexOf('TH') !== -1 && days.indexOf('FR') !== -1 && days.indexOf('SA') !== -1 && days.indexOf('SU') !== -1 }; var sortWeekDays = function (a, b) { return a.weekday - b.weekday; }; this.byweekday.allWeeks.sort(sortWeekDays); this.byweekday.someWeeks.sort(sortWeekDays); if (!this.byweekday.allWeeks.length) this.byweekday.allWeeks = null; if (!this.byweekday.someWeeks.length) this.byweekday.someWeeks = null; } else { this.byweekday = null; } } /** * Test whether the rrule can be fully converted to text. * @param {RRule} rrule * @return {Boolean} */ ToText.isFullyConvertible = function (rrule) { var canConvert = true; if (!(rrule.options.freq in ToText.IMPLEMENTED)) return false; if (rrule.origOptions.until && rrule.origOptions.count) return false; for (var key in rrule.origOptions) { if (contains(['dtstart', 'wkst', 'freq'], key)) return true; if (!contains(ToText.IMPLEMENTED[rrule.options.freq], key)) return false; } return canConvert; }; ToText.prototype.isFullyConvertible = function () { return ToText.isFullyConvertible(this.rrule); }; /** * Perform the conversion. Only some of the frequencies are supported. * If some of the rrule's options aren't supported, they'll * be omitted from the output an "(~ approximate)" will be appended. * @return {*} */ ToText.prototype.toString = function () { var gettext = this.gettext; if (!(this.options.freq in ToText.IMPLEMENTED)) { return gettext('RRule error: Unable to fully convert this rrule to text'); } this.text = [gettext('every')]; // @ts-ignore this[src["default"].FREQUENCIES[this.options.freq]](); if (this.options.until) { this.add(gettext('until')); var until = this.options.until; this.add(this.dateFormatter(until.getUTCFullYear(), this.language.monthNames[until.getUTCMonth()], until.getUTCDate())); } else if (this.options.count) { this.add(gettext('for')) .add(this.options.count.toString()) .add(this.plural(this.options.count) ? gettext('times') : gettext('time')); } if (!this.isFullyConvertible()) this.add(gettext('(~ approximate)')); return this.text.join(''); }; ToText.prototype.HOURLY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('hours') : gettext('hour')); }; ToText.prototype.MINUTELY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('minutes') : gettext('minutes')); }; ToText.prototype.DAILY = function () { var gettext = this.gettext; if (this.options.interval !== 1) this.add(this.options.interval.toString()); if (this.byweekday && this.byweekday.isWeekdays) { this.add(this.plural(this.options.interval) ? gettext('weekdays') : gettext('weekday')); } else { this.add(this.plural(this.options.interval) ? gettext('days') : gettext('day')); } if (this.origOptions.bymonth) { this.add(gettext('in')); this._bymonth(); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } else if (this.origOptions.byhour) { this._byhour(); } }; ToText.prototype.WEEKLY = function () { var gettext = this.gettext; if (this.options.interval !== 1) { this.add(this.options.interval.toString()).add(this.plural(this.options.interval) ? gettext('weeks') : gettext('week')); } if (this.byweekday && this.byweekday.isWeekdays) { if (this.options.interval === 1) { this.add(this.plural(this.options.interval) ? gettext('weekdays') : gettext('weekday')); } else { this.add(gettext('on')).add(gettext('weekdays')); } } else if (this.byweekday && this.byweekday.isEveryDay) { this.add(this.plural(this.options.interval) ? gettext('days') : gettext('day')); } else { if (this.options.interval === 1) this.add(gettext('week')); if (this.origOptions.bymonth) { this.add(gettext('in')); this._bymonth(); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } } }; ToText.prototype.MONTHLY = function () { var gettext = this.gettext; if (this.origOptions.bymonth) { if (this.options.interval !== 1) { this.add(this.options.interval.toString()).add(gettext('months')); if (this.plural(this.options.interval)) this.add(gettext('in')); } else { // this.add(gettext('MONTH')) } this._bymonth(); } else { if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('months') : gettext('month')); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday && this.byweekday.isWeekdays) { this.add(gettext('on')).add(gettext('weekdays')); } else if (this.byweekday) { this._byweekday(); } }; ToText.prototype.YEARLY = function () { var gettext = this.gettext; if (this.origOptions.bymonth) { if (this.options.interval !== 1) { this.add(this.options.interval.toString()); this.add(gettext('years')); } else { // this.add(gettext('YEAR')) } this._bymonth(); } else { if (this.options.interval !== 1) this.add(this.options.interval.toString()); this.add(this.plural(this.options.interval) ? gettext('years') : gettext('year')); } if (this.bymonthday) { this._bymonthday(); } else if (this.byweekday) { this._byweekday(); } if (this.options.byyearday) { this.add(gettext('on the')) .add(this.list(this.options.byyearday, this.nth, gettext('and'))) .add(gettext('day')); } if (this.options.byweekno) { this.add(gettext('in')) .add(this.plural(this.options.byweekno.length) ? gettext('weeks') : gettext('week')) .add(this.list(this.options.byweekno, undefined, gettext('and'))); } }; ToText.prototype._bymonthday = function () { var gettext = this.gettext; if (this.byweekday && this.byweekday.allWeeks) { this.add(gettext('on')) .add(this.list(this.byweekday.allWeeks, this.weekdaytext, gettext('or'))) .add(gettext('the')) .add(this.list(this.bymonthday, this.nth, gettext('or'))); } else { this.add(gettext('on the')).add(this.list(this.bymonthday, this.nth, gettext('and'))); } // this.add(gettext('DAY')) }; ToText.prototype._byweekday = function () { var gettext = this.gettext; if (this.byweekday.allWeeks && !this.byweekday.isWeekdays) { this.add(gettext('on')).add(this.list(this.byweekday.allWeeks, this.weekdaytext)); } if (this.byweekday.someWeeks) { if (this.byweekday.allWeeks) this.add(gettext('and')); this.add(gettext('on the')).add(this.list(this.byweekday.someWeeks, this.weekdaytext, gettext('and'))); } }; ToText.prototype._byhour = function () { var gettext = this.gettext; this.add(gettext('at')).add(this.list(this.origOptions.byhour, undefined, gettext('and'))); }; ToText.prototype._bymonth = function () { this.add(this.list(this.options.bymonth, this.monthtext, this.gettext('and'))); }; ToText.prototype.nth = function (n) { n = parseInt(n.toString(), 10); var nth; var npos; var gettext = this.gettext; if (n === -1) return gettext('last'); npos = Math.abs(n); switch (npos) { case 1: case 21: case 31: nth = npos + gettext('st'); break; case 2: case 22: nth = npos + gettext('nd'); break; case 3: case 23: nth = npos + gettext('rd'); break; default: nth = npos + gettext('th'); } return n < 0 ? nth + ' ' + gettext('last') : nth; }; ToText.prototype.monthtext = function (m) { return this.language.monthNames[m - 1]; }; ToText.prototype.weekdaytext = function (wday) { var weekday = Object(helpers["e" /* isNumber */])(wday) ? (wday + 1) % 7 : wday.getJsWeekday(); return ((wday.n ? this.nth(wday.n) + ' ' : '') + this.language.dayNames[weekday]); }; ToText.prototype.plural = function (n) { return n % 100 !== 1; }; ToText.prototype.add = function (s) { this.text.push(' '); this.text.push(s); return this; }; ToText.prototype.list = function (arr, callback, finalDelim, delim) { if (delim === void 0) { delim = ','; } if (!Object(helpers["d" /* isArray */])(arr)) { arr = [arr]; } var delimJoin = function (array, delimiter, finalDelimiter) { var list = ''; for (var i = 0; i < array.length; i++) { if (i !== 0) { if (i === array.length - 1) { list += ' ' + finalDelimiter + ' '; } else { list += delimiter + ' '; } } list += array[i]; } return list; }; callback = callback || function (o) { return o.toString(); }; var self = this; var realCallback = function (arg) { return callback && callback.call(self, arg); }; if (finalDelim) { return delimJoin(arr.map(realCallback), delim, finalDelim); } else { return arr.map(realCallback).join(delim + ' '); } }; return ToText; }()); /* harmony default export */ var totext = (totext_ToText); // CONCATENATED MODULE: ./src/nlp/parsetext.ts // ============================================================================= // Parser // ============================================================================= var Parser = /** @class */ (function () { function Parser(rules) { this.done = true; this.rules = rules; } Parser.prototype.start = function (text) { this.text = text; this.done = false; return this.nextSymbol(); }; Parser.prototype.isDone = function () { return this.done && this.symbol === null; }; Parser.prototype.nextSymbol = function () { var best; var bestSymbol; var p = this; this.symbol = null; this.value = null; do { if (this.done) return false; var rule = void 0; best = null; for (var name_1 in this.rules) { rule = this.rules[name_1]; var match = rule.exec(p.text); if (match) { if (best === null || match[0].length > best[0].length) { best = match; bestSymbol = name_1; } } } if (best != null) { this.text = this.text.substr(best[0].length); if (this.text === '') this.done = true; } if (best == null) { this.done = true; this.symbol = null; this.value = null; return; } // @ts-ignore } while (bestSymbol === 'SKIP'); // @ts-ignore this.symbol = bestSymbol; this.value = best; return true; }; Parser.prototype.accept = function (name) { if (this.symbol === name) { if (this.value) { var v = this.value; this.nextSymbol(); return v; } this.nextSymbol(); return true; } return false; }; Parser.prototype.acceptNumber = function () { return this.accept('number'); }; Parser.prototype.expect = function (name) { if (this.accept(name)) return true; throw new Error('expected ' + name + ' but found ' + this.symbol); }; return Parser; }()); function parseText(text, language) { if (language === void 0) { language = i18n; } var options = {}; var ttr = new Parser(language.tokens); if (!ttr.start(text)) return null; S(); return options; function S() { // every [n] ttr.expect('every'); var n = ttr.acceptNumber(); if (n) options.interval = parseInt(n[0], 10); if (ttr.isDone()) throw new Error('Unexpected end'); switch (ttr.symbol) { case 'day(s)': options.freq = src["default"].DAILY; if (ttr.nextSymbol()) { AT(); F(); } break; // FIXME Note: every 2 weekdays != every two weeks on weekdays. // DAILY on weekdays is not a valid rule case 'weekday(s)': options.freq = src["default"].WEEKLY; options.byweekday = [ src["default"].MO, src["default"].TU, src["default"].WE, src["default"].TH, src["default"].FR ]; ttr.nextSymbol(); F(); break; case 'week(s)': options.freq = src["default"].WEEKLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'hour(s)': options.freq = src["default"].HOURLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'minute(s)': options.freq = src["default"].MINUTELY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'month(s)': options.freq = src["default"].MONTHLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'year(s)': options.freq = src["default"].YEARLY; if (ttr.nextSymbol()) { ON(); F(); } break; case 'monday': case 'tuesday': case 'wednesday': case 'thursday': case 'friday': case 'saturday': case 'sunday': options.freq = src["default"].WEEKLY; var key = ttr.symbol.substr(0, 2).toUpperCase(); options.byweekday = [src["default"][key]]; if (!ttr.nextSymbol()) return; // TODO check for duplicates while (ttr.accept('comma')) { if (ttr.isDone()) throw new Error('Unexpected end'); var wkd = decodeWKD(); if (!wkd) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected weekday'); } // @ts-ignore options.byweekday.push(src["default"][wkd]); ttr.nextSymbol(); } MDAYs(); F(); break; case 'january': case 'february': case 'march': case 'april': case 'may': case 'june': case 'july': case 'august': case 'september': case 'october': case 'november': case 'december': options.freq = src["default"].YEARLY; options.bymonth = [decodeM()]; if (!ttr.nextSymbol()) return; // TODO check for duplicates while (ttr.accept('comma')) { if (ttr.isDone()) throw new Error('Unexpected end'); var m = decodeM(); if (!m) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected month'); } options.bymonth.push(m); ttr.nextSymbol(); } ON(); F(); break; default: throw new Error('Unknown symbol'); } } function ON() { var on = ttr.accept('on'); var the = ttr.accept('the'); if (!(on || the)) return; do { var nth = decodeNTH(); var wkd = decodeWKD(); var m = decodeM(); // nth <weekday> | <weekday> if (nth) { // ttr.nextSymbol() if (wkd) { ttr.nextSymbol(); if (!options.byweekday) options.byweekday = []; // @ts-ignore options.byweekday.push(src["default"][wkd].nth(nth)); } else { if (!options.bymonthday) options.bymonthday = []; // @ts-ignore options.bymonthday.push(nth); ttr.accept('day(s)'); } // <weekday> } else if (wkd) { ttr.nextSymbol(); if (!options.byweekday) options.byweekday = []; // @ts-ignore options.byweekday.push(src["default"][wkd]); } else if (ttr.symbol === 'weekday(s)') { ttr.nextSymbol(); if (!options.byweekday) { options.byweekday = [ src["default"].MO, src["default"].TU, src["default"].WE, src["default"].TH, src["default"].FR ]; } } else if (ttr.symbol === 'week(s)') { ttr.nextSymbol(); var n = ttr.acceptNumber(); if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected week number'); } options.byweekno = [parseInt(n[0], 10)]; while (ttr.accept('comma')) { n = ttr.acceptNumber(); if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected monthday'); } options.byweekno.push(parseInt(n[0], 10)); } } else if (m) { ttr.nextSymbol(); if (!options.bymonth) options.bymonth = []; // @ts-ignore options.bymonth.push(m); } else { return; } } while (ttr.accept('comma') || ttr.accept('the') || ttr.accept('on')); } function AT() { var at = ttr.accept('at'); if (!at) return; do { var n = ttr.acceptNumber(); if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + ', expected hour'); } options.byhour = [parseInt(n[0], 10)]; while (ttr.accept('comma')) { n = ttr.acceptNumber(); if (!n) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected hour'); } options.byhour.push(parseInt(n[0], 10)); } } while (ttr.accept('comma') || ttr.accept('at')); } function decodeM() { switch (ttr.symbol) { case 'january': return 1; case 'february': return 2; case 'march': return 3; case 'april': return 4; case 'may': return 5; case 'june': return 6; case 'july': return 7; case 'august': return 8; case 'september': return 9; case 'october': return 10; case 'november': return 11; case 'december': return 12; default: return false; } } function decodeWKD() { switch (ttr.symbol) { case 'monday': case 'tuesday': case 'wednesday': case 'thursday': case 'friday': case 'saturday': case 'sunday': return ttr.symbol.substr(0, 2).toUpperCase(); default: return false; } } function decodeNTH() { switch (ttr.symbol) { case 'last': ttr.nextSymbol(); return -1; case 'first': ttr.nextSymbol(); return 1; case 'second': ttr.nextSymbol(); return ttr.accept('last') ? -2 : 2; case 'third': ttr.nextSymbol(); return ttr.accept('last') ? -3 : 3; case 'nth': var v = parseInt(ttr.value[1], 10); if (v < -366 || v > 366) throw new Error('Nth out of range: ' + v); ttr.nextSymbol(); return ttr.accept('last') ? -v : v; default: return false; } } function MDAYs() { ttr.accept('on'); ttr.accept('the'); var nth = decodeNTH(); if (!nth) return; options.bymonthday = [nth]; ttr.nextSymbol(); while (ttr.accept('comma')) { nth = decodeNTH(); if (!nth) { throw new Error('Unexpected symbol ' + ttr.symbol + '; expected monthday'); } options.bymonthday.push(nth); ttr.nextSymbol(); } } function F() { if (ttr.symbol === 'until') { var date = Date.parse(ttr.text); if (!date) throw new Error('Cannot parse until date:' + ttr.text); options.until = new Date(date); } else if (ttr.accept('for')) { options.count = parseInt(ttr.value[0], 10); ttr.expect('number'); // ttr.expect('times') } } } // CONCATENATED MODULE: ./src/nlp/index.ts /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "fromText", function() { return fromText; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "isFullyConvertible", function() { return isFullyConvertible; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "toText", function() { return toText; }); /* concated harmony reexport */__webpack_require__.d(__webpack_exports__, "parseText", function() { return parseText; }); /*! * rrule.js - Library for working with recurrence rules for calendar dates. * https://github.com/jakubroztocil/rrule * * Copyright 2010, Jakub Roztocil and Lars Schoning * Licenced under the BSD licence. * https://github.com/jakubroztocil/rrule/blob/master/LICENCE * */ /** * * Implementation of RRule.fromText() and RRule::toText(). * * * On the client side, this file needs to be included * when those functions are used. * */ // ============================================================================= // fromText // ============================================================================= /** * Will be able to convert some of the below described rules from * text format to a rule object. * * * RULES * * Every ([n]) * day(s) * | [weekday], ..., (and) [weekday] * | weekday(s) * | week(s) * | month(s) * | [month], ..., (and) [month] * | year(s) * * * Plus 0, 1, or multiple of these: * * on [weekday], ..., (or) [weekday] the [monthday], [monthday], ... (or) [monthday] * * on [weekday], ..., (and) [weekday] * * on the [monthday], [monthday], ... (and) [monthday] (day of the month) * * on the [nth-weekday], ..., (and) [nth-weekday] (of the month/year) * * * Plus 0 or 1 of these: * * for [n] time(s) * * until [date] * * Plus (.) * * * Definitely no supported for parsing: * * (for year): * in week(s) [n], ..., (and) [n] * * on the [yearday], ..., (and) [n] day of the year * on day [yearday], ..., (and) [n] * * * NON-TERMINALS * * [n]: 1, 2 ..., one, two, three .. * [month]: January, February, March, April, May, ... December * [weekday]: Monday, ... Sunday * [nth-weekday]: first [weekday], 2nd [weekday], ... last [weekday], ... * [monthday]: first, 1., 2., 1st, 2nd, second, ... 31st, last day, 2nd last day, .. * [date]: * [month] (0-31(,) ([year])), * (the) 0-31.(1-12.([year])), * (the) 0-31/(1-12/([year])), * [weekday] * * [year]: 0000, 0001, ... 01, 02, .. * * Definitely not supported for parsing: * * [yearday]: first, 1., 2., 1st, 2nd, second, ... 366th, last day, 2nd last day, .. * * @param {String} text * @return {Object, Boolean} the rule, or null. */ var fromText = function (text, language) { if (language === void 0) { language = i18n; } return new src["default"](parseText(text, language) || undefined); }; var common = [ 'count', 'until', 'interval', 'byweekday', 'bymonthday', 'bymonth' ]; totext.IMPLEMENTED = []; totext.IMPLEMENTED[src["default"].HOURLY] = common; totext.IMPLEMENTED[src["default"].MINUTELY] = common; totext.IMPLEMENTED[src["default"].DAILY] = ['byhour'].concat(common); totext.IMPLEMENTED[src["default"].WEEKLY] = common; totext.IMPLEMENTED[src["default"].MONTHLY] = common; totext.IMPLEMENTED[src["default"].YEARLY] = ['byweekno', 'byyearday'].concat(common); // ============================================================================= // Export // ============================================================================= var toText = function (rrule, gettext, language, dateFormatter) { return new totext(rrule, gettext, language, dateFormatter).toString(); }; var isFullyConvertible = totext.isFullyConvertible; /***/ }) /******/ ]); }); //# sourceMappingURL=rrule-tz.js.map