text
stringlengths
3
1.05M
// THIS FILE IS AUTO GENERATED import { GenIcon } from '../lib'; export function ImXing2 (props) { return GenIcon({"tag":"svg","attr":{"version":"1.1","viewBox":"0 0 16 16"},"child":[{"tag":"path","attr":{"d":"M2.431 3.159c-0.138 0-0.256 0.050-0.316 0.144-0.059 0.1-0.050 0.225 0.013 0.353l1.559 2.7c0.003 0.006 0.003 0.009 0 0.013l-2.45 4.331c-0.063 0.128-0.059 0.256 0 0.353 0.059 0.094 0.163 0.156 0.3 0.156h2.306c0.344 0 0.513-0.234 0.628-0.447 0 0 2.397-4.241 2.491-4.406-0.009-0.016-1.588-2.766-1.588-2.766-0.116-0.203-0.287-0.431-0.644-0.431h-2.3z"}},{"tag":"path","attr":{"d":"M12.125 0c-0.344 0-0.494 0.216-0.619 0.441 0 0-4.972 8.816-5.134 9.106 0.009 0.016 3.278 6.016 3.278 6.016 0.116 0.203 0.291 0.441 0.644 0.441h2.306c0.137 0 0.247-0.053 0.306-0.147 0.063-0.1 0.059-0.228-0.006-0.356l-3.25-5.947c-0.003-0.006-0.003-0.009 0-0.016l5.109-9.034c0.063-0.128 0.066-0.256 0.006-0.356-0.059-0.094-0.169-0.147-0.306-0.147h-2.334z"}}]})(props); };
from abc import ABC, abstractmethod from PIL import Image # type: ignore class View(ABC): @property @abstractmethod def width(self) -> int: raise NotImplementedError() @property @abstractmethod def height(self) -> int: raise NotImplementedError() def paint(self, image: Image) -> None: raise NotImplementedError()
for i in range(1,int(input())+1): #More than 2 lines will result in 0 score. Do not leave a blank line also print(((10**i)//9)**2)
/*! * # Semantic UI undefined - Transition * http://github.com/semantic-org/semantic-ui/ * * * Released under the MIT license * http://opensource.org/licenses/MIT * */ ;(function ($, window, document, undefined) { "use strict"; window = (typeof window != 'undefined' && window.Math == Math) ? window : (typeof self != 'undefined' && self.Math == Math) ? self : Function('return this')() ; $.fn.transition = function() { var $allModules = $(this), moduleSelector = $allModules.selector || '', time = new Date().getTime(), performance = [], moduleArguments = arguments, query = moduleArguments[0], queryArguments = [].slice.call(arguments, 1), methodInvoked = (typeof query === 'string'), requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { setTimeout(callback, 0); }, returnedValue ; $allModules .each(function(index) { var $module = $(this), element = this, // set at run time settings, instance, error, className, metadata, animationEnd, animationName, namespace, moduleNamespace, eventNamespace, module ; module = { initialize: function() { // get full settings settings = module.get.settings.apply(element, moduleArguments); // shorthand className = settings.className; error = settings.error; metadata = settings.metadata; // define namespace eventNamespace = '.' + settings.namespace; moduleNamespace = 'module-' + settings.namespace; instance = $module.data(moduleNamespace) || module; // get vendor specific events animationEnd = module.get.animationEndEvent(); if(methodInvoked) { methodInvoked = module.invoke(query); } // method not invoked, lets run an animation if(methodInvoked === false) { module.verbose('Converted arguments into settings object', settings); if(settings.interval) { module.delay(settings.animate); } else { module.animate(); } module.instantiate(); } }, instantiate: function() { module.verbose('Storing instance of module', module); instance = module; $module .data(moduleNamespace, instance) ; }, destroy: function() { module.verbose('Destroying previous module for', element); $module .removeData(moduleNamespace) ; }, refresh: function() { module.verbose('Refreshing display type on next animation'); delete module.displayType; }, forceRepaint: function() { module.verbose('Forcing element repaint'); var $parentElement = $module.parent(), $nextElement = $module.next() ; if($nextElement.length === 0) { $module.detach().appendTo($parentElement); } else { $module.detach().insertBefore($nextElement); } }, repaint: function() { module.verbose('Repainting element'); var fakeAssignment = element.offsetWidth ; }, delay: function(interval) { var direction = module.get.animationDirection(), shouldReverse, delay ; if(!direction) { direction = module.can.transition() ? module.get.direction() : 'static' ; } interval = (interval !== undefined) ? interval : settings.interval ; shouldReverse = (settings.reverse == 'auto' && direction == className.outward); delay = (shouldReverse || settings.reverse == true) ? ($allModules.length - index) * settings.interval : index * settings.interval ; module.debug('Delaying animation by', delay); setTimeout(module.animate, delay); }, animate: function(overrideSettings) { settings = overrideSettings || settings; if(!module.is.supported()) { module.error(error.support); return false; } module.debug('Preparing animation', settings.animation); if(module.is.animating()) { if(settings.queue) { if(!settings.allowRepeats && module.has.direction() && module.is.occurring() && module.queuing !== true) { module.debug('Animation is currently occurring, preventing queueing same animation', settings.animation); } else { module.queue(settings.animation); } return false; } else if(!settings.allowRepeats && module.is.occurring()) { module.debug('Animation is already occurring, will not execute repeated animation', settings.animation); return false; } else { module.debug('New animation started, completing previous early', settings.animation); instance.complete(); } } if( module.can.animate() ) { module.set.animating(settings.animation); } else { module.error(error.noAnimation, settings.animation, element); } }, reset: function() { module.debug('Resetting animation to beginning conditions'); module.remove.animationCallbacks(); module.restore.conditions(); module.remove.animating(); }, queue: function(animation) { module.debug('Queueing animation of', animation); module.queuing = true; $module .one(animationEnd + '.queue' + eventNamespace, function() { module.queuing = false; module.repaint(); module.animate.apply(this, settings); }) ; }, complete: function (event) { module.debug('Animation complete', settings.animation); module.remove.completeCallback(); module.remove.failSafe(); if(!module.is.looping()) { if( module.is.outward() ) { module.verbose('Animation is outward, hiding element'); module.restore.conditions(); module.hide(); } else if( module.is.inward() ) { module.verbose('Animation is outward, showing element'); module.restore.conditions(); module.show(); } else { module.verbose('Static animation completed'); module.restore.conditions(); settings.onComplete.call(element); } } }, force: { visible: function() { var style = $module.attr('style'), userStyle = module.get.userStyle(), displayType = module.get.displayType(), overrideStyle = userStyle + 'display: ' + displayType + ' !important;', currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== displayType) { module.verbose('Overriding default display to show element', displayType); $module .attr('style', overrideStyle) ; } else if(emptyStyle) { $module.removeAttr('style'); } }, hidden: function() { var style = $module.attr('style'), currentDisplay = $module.css('display'), emptyStyle = (style === undefined || style === '') ; if(currentDisplay !== 'none' && !module.is.hidden()) { module.verbose('Overriding default display to hide element'); $module .css('display', 'none') ; } else if(emptyStyle) { $module .removeAttr('style') ; } } }, has: { direction: function(animation) { var hasDirection = false ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); $.each(animation, function(index, word){ if(word === className.inward || word === className.outward) { hasDirection = true; } }); } return hasDirection; }, inlineDisplay: function() { var style = $module.attr('style') || '' ; return $.isArray(style.match(/display.*?;/, '')); } }, set: { animating: function(animation) { var animationClass, direction ; // remove previous callbacks module.remove.completeCallback(); // determine exact animation animation = animation || settings.animation; animationClass = module.get.animationClass(animation); // save animation class in cache to restore class names module.save.animation(animationClass); // override display if necessary so animation appears visibly module.force.visible(); module.remove.hidden(); module.remove.direction(); module.start.animation(animationClass); }, duration: function(animationName, duration) { duration = duration || settings.duration; duration = (typeof duration == 'number') ? duration + 'ms' : duration ; if(duration || duration === 0) { module.verbose('Setting animation duration', duration); $module .css({ 'animation-duration': duration }) ; } }, direction: function(direction) { direction = direction || module.get.direction(); if(direction == className.inward) { module.set.inward(); } else { module.set.outward(); } }, looping: function() { module.debug('Transition set to loop'); $module .addClass(className.looping) ; }, hidden: function() { $module .addClass(className.transition) .addClass(className.hidden) ; }, inward: function() { module.debug('Setting direction to inward'); $module .removeClass(className.outward) .addClass(className.inward) ; }, outward: function() { module.debug('Setting direction to outward'); $module .removeClass(className.inward) .addClass(className.outward) ; }, visible: function() { $module .addClass(className.transition) .addClass(className.visible) ; } }, start: { animation: function(animationClass) { animationClass = animationClass || module.get.animationClass(); module.debug('Starting tween', animationClass); $module .addClass(animationClass) .one(animationEnd + '.complete' + eventNamespace, module.complete) ; if(settings.useFailSafe) { module.add.failSafe(); } module.set.duration(settings.duration); settings.onStart.call(element); } }, save: { animation: function(animation) { if(!module.cache) { module.cache = {}; } module.cache.animation = animation; }, displayType: function(displayType) { if(displayType !== 'none') { $module.data(metadata.displayType, displayType); } }, transitionExists: function(animation, exists) { $.fn.transition.exists[animation] = exists; module.verbose('Saving existence of transition', animation, exists); } }, restore: { conditions: function() { var animation = module.get.currentAnimation() ; if(animation) { $module .removeClass(animation) ; module.verbose('Removing animation class', module.cache); } module.remove.duration(); } }, add: { failSafe: function() { var duration = module.get.duration() ; module.timer = setTimeout(function() { $module.triggerHandler(animationEnd); }, duration + settings.failSafeDelay); module.verbose('Adding fail safe timer', module.timer); } }, remove: { animating: function() { $module.removeClass(className.animating); }, animationCallbacks: function() { module.remove.queueCallback(); module.remove.completeCallback(); }, queueCallback: function() { $module.off('.queue' + eventNamespace); }, completeCallback: function() { $module.off('.complete' + eventNamespace); }, display: function() { $module.css('display', ''); }, direction: function() { $module .removeClass(className.inward) .removeClass(className.outward) ; }, duration: function() { $module .css('animation-duration', '') ; }, failSafe: function() { module.verbose('Removing fail safe timer', module.timer); if(module.timer) { clearTimeout(module.timer); } }, hidden: function() { $module.removeClass(className.hidden); }, visible: function() { $module.removeClass(className.visible); }, looping: function() { module.debug('Transitions are no longer looping'); if( module.is.looping() ) { module.reset(); $module .removeClass(className.looping) ; } }, transition: function() { $module .removeClass(className.visible) .removeClass(className.hidden) ; } }, get: { settings: function(animation, duration, onComplete) { // single settings object if(typeof animation == 'object') { return $.extend(true, {}, $.fn.transition.settings, animation); } // all arguments provided else if(typeof onComplete == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : onComplete, duration : duration }); } // only duration provided else if(typeof duration == 'string' || typeof duration == 'number') { return $.extend({}, $.fn.transition.settings, { animation : animation, duration : duration }); } // duration is actually settings object else if(typeof duration == 'object') { return $.extend({}, $.fn.transition.settings, duration, { animation : animation }); } // duration is actually callback else if(typeof duration == 'function') { return $.extend({}, $.fn.transition.settings, { animation : animation, onComplete : duration }); } // only animation provided else { return $.extend({}, $.fn.transition.settings, { animation : animation }); } }, animationClass: function(animation) { var animationClass = animation || settings.animation, directionClass = (module.can.transition() && !module.has.direction()) ? module.get.direction() + ' ' : '' ; return className.animating + ' ' + className.transition + ' ' + directionClass + animationClass ; }, currentAnimation: function() { return (module.cache && module.cache.animation !== undefined) ? module.cache.animation : false ; }, currentDirection: function() { return module.is.inward() ? className.inward : className.outward ; }, direction: function() { return module.is.hidden() || !module.is.visible() ? className.inward : className.outward ; }, animationDirection: function(animation) { var direction ; animation = animation || settings.animation; if(typeof animation === 'string') { animation = animation.split(' '); // search animation name for out/in class $.each(animation, function(index, word){ if(word === className.inward) { direction = className.inward; } else if(word === className.outward) { direction = className.outward; } }); } // return found direction if(direction) { return direction; } return false; }, duration: function(duration) { duration = duration || settings.duration; if(duration === false) { duration = $module.css('animation-duration') || 0; } return (typeof duration === 'string') ? (duration.indexOf('ms') > -1) ? parseFloat(duration) : parseFloat(duration) * 1000 : duration ; }, displayType: function(shouldDetermine) { shouldDetermine = (shouldDetermine !== undefined) ? shouldDetermine : true ; if(settings.displayType) { return settings.displayType; } if(shouldDetermine && $module.data(metadata.displayType) === undefined) { // create fake element to determine display state module.can.transition(true); } return $module.data(metadata.displayType); }, userStyle: function(style) { style = style || $module.attr('style') || ''; return style.replace(/display.*?;/, ''); }, transitionExists: function(animation) { return $.fn.transition.exists[animation]; }, animationStartEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationstart', 'OAnimation' :'oAnimationStart', 'MozAnimation' :'mozAnimationStart', 'WebkitAnimation' :'webkitAnimationStart' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; }, animationEndEvent: function() { var element = document.createElement('div'), animations = { 'animation' :'animationend', 'OAnimation' :'oAnimationEnd', 'MozAnimation' :'mozAnimationEnd', 'WebkitAnimation' :'webkitAnimationEnd' }, animation ; for(animation in animations){ if( element.style[animation] !== undefined ){ return animations[animation]; } } return false; } }, can: { transition: function(forced) { var animation = settings.animation, transitionExists = module.get.transitionExists(animation), displayType = module.get.displayType(false), elementClass, tagName, $clone, currentAnimation, inAnimation, directionExists ; if( transitionExists === undefined || forced) { module.verbose('Determining whether animation exists'); elementClass = $module.attr('class'); tagName = $module.prop('tagName'); $clone = $('<' + tagName + ' />').addClass( elementClass ).insertAfter($module); currentAnimation = $clone .addClass(animation) .removeClass(className.inward) .removeClass(className.outward) .addClass(className.animating) .addClass(className.transition) .css('animationName') ; inAnimation = $clone .addClass(className.inward) .css('animationName') ; if(!displayType) { displayType = $clone .attr('class', elementClass) .removeAttr('style') .removeClass(className.hidden) .removeClass(className.visible) .show() .css('display') ; module.verbose('Determining final display state', displayType); module.save.displayType(displayType); } $clone.remove(); if(currentAnimation != inAnimation) { module.debug('Direction exists for animation', animation); directionExists = true; } else if(currentAnimation == 'none' || !currentAnimation) { module.debug('No animation defined in css', animation); return; } else { module.debug('Static animation found', animation, displayType); directionExists = false; } module.save.transitionExists(animation, directionExists); } return (transitionExists !== undefined) ? transitionExists : directionExists ; }, animate: function() { // can transition does not return a value if animation does not exist return (module.can.transition() !== undefined); } }, is: { animating: function() { return $module.hasClass(className.animating); }, inward: function() { return $module.hasClass(className.inward); }, outward: function() { return $module.hasClass(className.outward); }, looping: function() { return $module.hasClass(className.looping); }, occurring: function(animation) { animation = animation || settings.animation; animation = '.' + animation.replace(' ', '.'); return ( $module.filter(animation).length > 0 ); }, visible: function() { return $module.is(':visible'); }, hidden: function() { return $module.css('visibility') === 'hidden'; }, supported: function() { return(animationEnd !== false); } }, hide: function() { module.verbose('Hiding element'); if( module.is.animating() ) { module.reset(); } element.blur(); // IE will trigger focus change if element is not blurred before hiding module.remove.display(); module.remove.visible(); module.set.hidden(); module.force.hidden(); settings.onHide.call(element); settings.onComplete.call(element); // module.repaint(); }, show: function(display) { module.verbose('Showing element', display); module.remove.hidden(); module.set.visible(); module.force.visible(); settings.onShow.call(element); settings.onComplete.call(element); // module.repaint(); }, toggle: function() { if( module.is.visible() ) { module.hide(); } else { module.show(); } }, stop: function() { module.debug('Stopping current animation'); $module.triggerHandler(animationEnd); }, stopAll: function() { module.debug('Stopping all animation'); module.remove.queueCallback(); $module.triggerHandler(animationEnd); }, clear: { queue: function() { module.debug('Clearing animation queue'); module.remove.queueCallback(); } }, enable: function() { module.verbose('Starting animation'); $module.removeClass(className.disabled); }, disable: function() { module.debug('Stopping animation'); $module.addClass(className.disabled); }, setting: function(name, value) { module.debug('Changing setting', name, value); if( $.isPlainObject(name) ) { $.extend(true, settings, name); } else if(value !== undefined) { if($.isPlainObject(settings[name])) { $.extend(true, settings[name], value); } else { settings[name] = value; } } else { return settings[name]; } }, internal: function(name, value) { if( $.isPlainObject(name) ) { $.extend(true, module, name); } else if(value !== undefined) { module[name] = value; } else { return module[name]; } }, debug: function() { if(!settings.silent && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.debug.apply(console, arguments); } } }, verbose: function() { if(!settings.silent && settings.verbose && settings.debug) { if(settings.performance) { module.performance.log(arguments); } else { module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':'); module.verbose.apply(console, arguments); } } }, error: function() { if(!settings.silent) { module.error = Function.prototype.bind.call(console.error, console, settings.name + ':'); module.error.apply(console, arguments); } }, performance: { log: function(message) { var currentTime, executionTime, previousTime ; if(settings.performance) { currentTime = new Date().getTime(); previousTime = time || currentTime; executionTime = currentTime - previousTime; time = currentTime; performance.push({ 'Name' : message[0], 'Arguments' : [].slice.call(message, 1) || '', 'Element' : element, 'Execution Time' : executionTime }); } clearTimeout(module.performance.timer); module.performance.timer = setTimeout(module.performance.display, 500); }, display: function() { var title = settings.name + ':', totalTime = 0 ; time = false; clearTimeout(module.performance.timer); $.each(performance, function(index, data) { totalTime += data['Execution Time']; }); title += ' ' + totalTime + 'ms'; if(moduleSelector) { title += ' \'' + moduleSelector + '\''; } if($allModules.length > 1) { title += ' ' + '(' + $allModules.length + ')'; } if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) { console.groupCollapsed(title); if(console.table) { console.table(performance); } else { $.each(performance, function(index, data) { console.log(data['Name'] + ': ' + data['Execution Time']+'ms'); }); } console.groupEnd(); } performance = []; } }, // modified for transition to return invoke success invoke: function(query, passedArguments, context) { var object = instance, maxDepth, found, response ; passedArguments = passedArguments || queryArguments; context = element || context; if(typeof query == 'string' && object !== undefined) { query = query.split(/[\. ]/); maxDepth = query.length - 1; $.each(query, function(depth, value) { var camelCaseValue = (depth != maxDepth) ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1) : query ; if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) { object = object[camelCaseValue]; } else if( object[camelCaseValue] !== undefined ) { found = object[camelCaseValue]; return false; } else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) { object = object[value]; } else if( object[value] !== undefined ) { found = object[value]; return false; } else { return false; } }); } if ( $.isFunction( found ) ) { response = found.apply(context, passedArguments); } else if(found !== undefined) { response = found; } if($.isArray(returnedValue)) { returnedValue.push(response); } else if(returnedValue !== undefined) { returnedValue = [returnedValue, response]; } else if(response !== undefined) { returnedValue = response; } return (found !== undefined) ? found : false ; } }; module.initialize(); }) ; return (returnedValue !== undefined) ? returnedValue : this ; }; // Records if CSS transition is available $.fn.transition.exists = {}; $.fn.transition.settings = { // module info name : 'Transition', // hide all output from this component regardless of other settings silent : false, // debug content outputted to console debug : false, // verbose debug output verbose : false, // performance data output performance : true, // event namespace namespace : 'transition', // delay between animations in group interval : 0, // whether group animations should be reversed reverse : 'auto', // animation callback event onStart : function() {}, onComplete : function() {}, onShow : function() {}, onHide : function() {}, // whether timeout should be used to ensure callback fires in cases animationend does not useFailSafe : true, // delay in ms for fail safe failSafeDelay : 100, // whether EXACT animation can occur twice in a row allowRepeats : false, // Override final display type on visible displayType : false, // animation duration animation : 'fade', duration : false, // new animations will occur after previous ones queue : true, metadata : { displayType: 'display' }, className : { animating : 'animating', disabled : 'disabled', hidden : 'hidden', inward : 'in', loading : 'loading', looping : 'looping', outward : 'out', transition : 'transition', visible : 'visible' }, // possible errors error: { noAnimation : 'Element is no longer attached to DOM. Unable to animate. Use silent setting to surpress this warning in production.', repeated : 'That animation is already occurring, cancelling repeated animation', method : 'The method you called is not defined', support : 'This browser does not support CSS animations' } }; })( jQuery, window, document );
export function mergeObject(base, ...objects) { for(const obj of objects) for(const key in obj) { base[key] = obj[key]; const descriptor = Object.getOwnPropertyDescriptor(obj.constructor, key); Object.defineProperty(base, key, {...descriptor, value: obj[key]}); } }
# ---------------------------------------------------------------------------- # pyglet # Copyright (c) 2006-2008 Alex Holkner # Copyright (c) 2008-2019 pyglet contributors # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # * Neither the name of pyglet nor the names of its # contributors may be used to endorse or promote products # derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- """Mouse constants and utilities for pyglet.window. """ __docformat__ = 'restructuredtext' __version__ = '$Id$' def buttons_string(buttons): """Return a string describing a set of active mouse buttons. Example:: >>> buttons_string(LEFT | RIGHT) 'LEFT|RIGHT' :Parameters: `buttons` : int Bitwise combination of mouse button constants. :rtype: str """ button_names = [] if buttons & LEFT: button_names.append('LEFT') if buttons & MIDDLE: button_names.append('MIDDLE') if buttons & RIGHT: button_names.append('RIGHT') return '|'.join(button_names) # Symbolic names for the mouse buttons LEFT = 1 << 0 MIDDLE = 1 << 1 RIGHT = 1 << 2
# Copyright 2012 Pinterest.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. import collections import errno import functools import ipaddress import json import os import platform from unittest import mock import socket import unittest import pytest from pymemcache.client.base import ( PooledClient, Client, normalize_server_spec, KeepaliveOpts, check_key_helper ) from pymemcache.exceptions import ( MemcacheClientError, MemcacheServerError, MemcacheUnexpectedCloseError, MemcacheUnknownCommandError, MemcacheUnknownError, MemcacheIllegalInputError ) from pymemcache import pool from pymemcache.test.utils import MockMemcacheClient def is_ipv6(address): try: return ipaddress.ip_address(address).version == 6 except ValueError: # Fail to parse as valid ip address return False @pytest.mark.parametrize( 'key,allow_unicode_keys,key_prefix,ex_exception,ex_excinfo', [ ('b'*251, True, b'', MemcacheIllegalInputError, 'Key is too long'), ('foo bar', True, b'', MemcacheIllegalInputError, 'Key contains whitespace'), ('\00', True, b'', MemcacheIllegalInputError, 'Key contains null'), (None, True, b'', TypeError, None), ]) @pytest.mark.unit() def test_check_key_helper_failing_conditions(key, allow_unicode_keys, key_prefix, ex_exception, ex_excinfo): with pytest.raises(ex_exception) as excinfo: check_key_helper(key, allow_unicode_keys, key_prefix) # Allow to ignore the excinfo value. Different implementation (2.7, # pypy, 3.x) comes with various error messages for the same thing. # We just check the kind of the exception. if ex_excinfo: assert ex_excinfo in str(excinfo.value) @pytest.mark.unit() def test_check_key_helper(): assert check_key_helper(b"key", True, b'') == b"key" assert check_key_helper("key", True) == b"key" assert isinstance(check_key_helper(b"key", True), bytes) assert check_key_helper("", True) == b"" class MockSocket: def __init__(self, recv_bufs, connect_failure=None, close_failure=None): self.recv_bufs = collections.deque(recv_bufs) self.send_bufs = [] self.closed = False self.timeouts = [] self.connect_failure = connect_failure self.close_failure = close_failure self.connections = [] self.socket_options = [] @property def family(self): any_ipv6 = any(is_ipv6(c[0]) for c in self.connections) return socket.AF_INET6 if any_ipv6 else socket.AF_INET def sendall(self, value): self.send_bufs.append(value) def close(self): if isinstance(self.close_failure, Exception): raise self.close_failure self.closed = True def recv(self, size): value = self.recv_bufs.popleft() if isinstance(value, Exception): raise value return value def settimeout(self, timeout): self.timeouts.append(timeout) def connect(self, server): if isinstance(self.connect_failure, Exception): raise self.connect_failure self.connections.append(server) def setsockopt(self, level, option, value): self.socket_options.append((level, option, value)) class MockUnixSocketServer: def __init__(self, socket_path): if os.path.exists(socket_path): os.remove(socket_path) self.socket_path = socket_path self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) def __enter__(self): self.socket.bind(self.socket_path) self.socket.listen(1) return self.socket def __exit__(self, *args): self.socket.close() os.remove(self.socket_path) class MockSocketModule: def __init__(self, connect_failure=None, close_failure=None): self.connect_failure = connect_failure self.close_failure = close_failure self.sockets = [] def socket(self, family, type, proto=0, fileno=None): socket = MockSocket( [], connect_failure=self.connect_failure, close_failure=self.close_failure) self.sockets.append(socket) return socket def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): family = family or ( socket.AF_INET6 if is_ipv6(host) else socket.AF_INET ) type = type or socket.SOCK_STREAM proto = proto or socket.IPPROTO_TCP sockaddr = ( ('::1', 11211, 0, 0) if family == socket.AF_INET6 else ('127.0.0.1', 11211) ) return [(family, type, proto, '', sockaddr)] def __getattr__(self, name): return getattr(socket, name) class CustomizedClient(Client): def _extract_value(self, expect_cas, line, buf, remapped_keys, prefixed_keys): return b'key', b'value', b'END\r\n' @pytest.mark.unit() class ClientTestMixin: def make_client(self, mock_socket_values, **kwargs): client = Client(None, **kwargs) # mock out client._connect() rather than hard-setting client.sock to # ensure methods are checking whether self.sock is None before # attempting to use it sock = MockSocket(list(mock_socket_values)) client._connect = mock.Mock(side_effect=functools.partial( setattr, client, "sock", sock)) return client def make_customized_client(self, mock_socket_values, **kwargs): client = CustomizedClient(None, **kwargs) # mock out client._connect() rather than hard-setting client.sock to # ensure methods are checking whether self.sock is None before # attempting to use it sock = MockSocket(list(mock_socket_values)) client._connect = mock.Mock(side_effect=functools.partial( setattr, client, "sock", sock)) return client def test_set_success(self): client = self.make_client([b'STORED\r\n']) result = client.set(b'key', b'value', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.set(b'key', b'value', noreply=False) assert result is True # unit test for set operation with parameter flags client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.set(b'key', b'value', noreply=False, flags=0x00000030) assert result is True def test_set_unicode_key(self): client = self.make_client([b'']) def _set(): client.set('\u0FFF', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_unicode_key_ok(self): client = self.make_client([b'STORED\r\n'], allow_unicode_keys=True) result = client.set('\u0FFF', b'value', noreply=False) assert result is True def test_set_unicode_key_ok_snowman(self): client = self.make_client([b'STORED\r\n'], allow_unicode_keys=True) result = client.set('my☃', b'value', noreply=False) assert result is True def test_set_unicode_char_in_middle_of_key(self): client = self.make_client([b'STORED\r\n']) def _set(): client.set('helloworld_\xb1901520_%c3', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_unicode_char_in_middle_of_key_snowman(self): client = self.make_client([b'STORED\r\n']) def _set(): client.set('my☃', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_unicode_value(self): client = self.make_client([b'']) def _set(): client.set(b'key', '\u0FFF', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_unicode_char_in_middle_of_key_ok(self): client = self.make_client([b'STORED\r\n'], allow_unicode_keys=True) result = client.set('helloworld_\xb1901520_%c3', b'value', noreply=False) assert result is True def test_set_noreply(self): client = self.make_client([]) result = client.set(b'key', b'value', noreply=True) assert result is True # unit test for encoding passed in __init__() client = self.make_client([], encoding='utf-8') result = client.set(b'key', b'value', noreply=True) assert result is True def test_set_many_success(self): client = self.make_client([b'STORED\r\n']) result = client.set_many({b'key': b'value'}, noreply=False) assert result == [] # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.set_many({b'key': b'value'}, noreply=False) assert result == [] def test_set_multi_success(self): # Should just map to set_many client = self.make_client([b'STORED\r\n']) result = client.set_multi({b'key': b'value'}, noreply=False) assert result == [] # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.set_multi({b'key': b'value'}, noreply=False) assert result == [] def test_add_stored(self): client = self.make_client([b'STORED\r', b'\n']) result = client.add(b'key', b'value', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r', b'\n'], encoding='utf-8') result = client.add(b'key', b'value', noreply=False) assert result is True def test_add_not_stored(self): client = self.make_client([b'STORED\r', b'\n', b'NOT_', b'STOR', b'ED', b'\r\n']) client.add(b'key', b'value', noreply=False) result = client.add(b'key', b'value', noreply=False) assert result is False # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r', b'\n', b'NOT_', b'STOR', b'ED', b'\r\n'], encoding='utf-8') client.add(b'key', b'value', noreply=False) result = client.add(b'key', b'value', noreply=False) assert result is False def test_get_not_found(self): client = self.make_client([b'END\r\n']) result = client.get(b'key') assert result is None # Unit test for customized client (override _extract_value) client = self.make_customized_client([b'END\r\n']) result = client.get(b'key') assert result is None def test_space_key(self): client = self.make_client([b'']) with pytest.raises(MemcacheIllegalInputError): client.get(b'space key') with pytest.raises(MemcacheIllegalInputError): client.set(b'space key', b'value') def test_get_not_found_default(self): client = self.make_client([b'END\r\n']) result = client.get(b'key', default='foobar') assert result == 'foobar' # Unit test for customized client (override _extract_value) client = self.make_customized_client([b'END\r\n']) result = client.get(b'key', default='foobar') assert result == 'foobar' def test_get_ignore_exc_default(self): client = self.make_client([b'INVALID DATA\r\n'], ignore_exc=True) result = client.get(b'key', default='foobar') assert result == 'foobar' # Unit test for customized client (override _extract_value) client = self.make_client([b'INVALID DATA\r\n'], ignore_exc=True) result = client.get(b'key', default='foobar') assert result == 'foobar' def test_get_found(self): client = self.make_client([ b'STORED\r\n', b'VALUE key 0 5\r\nvalue\r\nEND\r\n', ]) client.set(b'key', b'value', noreply=False) result = client.get(b'key') assert result == b'value' # Unit test for customized client (override _extract_value) client = self.make_customized_client([ b'STORED\r\n', b'VALUE key 0 5\r\nvalue\r\nEND\r\n', ]) client.set(b'key', b'value', noreply=False) result = client.get(b'key') assert result == b'value' def test_get_many_none_found(self): client = self.make_client([b'END\r\n']) result = client.get_many([b'key1', b'key2']) assert result == {} def test_get_multi_none_found(self): client = self.make_client([b'END\r\n']) result = client.get_multi([b'key1', b'key2']) assert result == {} def test_get_many_some_found(self): client = self.make_client([ b'STORED\r\n', b'VALUE key1 0 6\r\nvalue1\r\nEND\r\n', ]) client.set(b'key1', b'value1', noreply=False) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1'} def test_get_many_all_found(self): client = self.make_client([ b'STORED\r\n', b'STORED\r\n', b'VALUE key1 0 6\r\nvalue1\r\n', b'VALUE key2 0 6\r\nvalue2\r\nEND\r\n', ]) client.set(b'key1', b'value1', noreply=False) client.set(b'key2', b'value2', noreply=False) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} def test_get_unicode_key(self): client = self.make_client([b'']) def _get(): client.get('\u0FFF') with pytest.raises(MemcacheIllegalInputError): _get() def test_delete_not_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.delete(b'key', noreply=False) assert result is False def test_delete_found(self): client = self.make_client([b'STORED\r', b'\n', b'DELETED\r\n']) client.add(b'key', b'value', noreply=False) result = client.delete(b'key', noreply=False) assert result is True def test_delete_noreply(self): client = self.make_client([]) result = client.delete(b'key', noreply=True) assert result is True def test_delete_many_no_keys(self): client = self.make_client([]) result = client.delete_many([], noreply=False) assert result is True def test_delete_many_none_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.delete_many([b'key'], noreply=False) assert result is True def test_delete_many_found(self): client = self.make_client([b'STORED\r', b'\n', b'DELETED\r\n']) client.add(b'key', b'value', noreply=False) result = client.delete_many([b'key'], noreply=False) assert result is True def test_delete_many_some_found(self): client = self.make_client([ b'STORED\r\n', b'DELETED\r\n', b'NOT_FOUND\r\n' ]) client.add(b'key', b'value', noreply=False) result = client.delete_many([b'key', b'key2'], noreply=False) assert result is True def test_delete_multi_some_found(self): client = self.make_client([ b'STORED\r\n', b'DELETED\r\n', b'NOT_FOUND\r\n' ]) client.add(b'key', b'value', noreply=False) result = client.delete_multi([b'key', b'key2'], noreply=False) assert result is True def test_incr_not_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.incr(b'key', 1, noreply=False) assert result is None def test_incr_found(self): client = self.make_client([b'STORED\r\n', b'1\r\n']) client.set(b'key', 0, noreply=False) result = client.incr(b'key', 1, noreply=False) assert result == 1 def test_incr_noreply(self): client = self.make_client([b'STORED\r\n']) client.set(b'key', 0, noreply=False) client = self.make_client([]) result = client.incr(b'key', 1, noreply=True) assert result is None def test_decr_not_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.decr(b'key', 1, noreply=False) assert result is None def test_decr_found(self): client = self.make_client([b'STORED\r\n', b'1\r\n']) client.set(b'key', 2, noreply=False) result = client.decr(b'key', 1, noreply=False) assert result == 1 class TestClient(ClientTestMixin, unittest.TestCase): Client = Client def test_append_stored(self): client = self.make_client([b'STORED\r\n']) result = client.append(b'key', b'value', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.append(b'key', b'value', noreply=False) assert result is True def test_prepend_stored(self): client = self.make_client([b'STORED\r\n']) result = client.prepend(b'key', b'value', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.prepend(b'key', b'value', noreply=False) assert result is True def test_cas_malformed(self): client = self.make_client([b'STORED\r\n']) with pytest.raises(MemcacheIllegalInputError): client.cas(b'key', b'value', None, noreply=False) with pytest.raises(MemcacheIllegalInputError): client.cas(b'key', b'value', 'nonintegerstring', noreply=False) with pytest.raises(MemcacheIllegalInputError): # even a space makes it a noninteger string client.cas(b'key', b'value', '123 ', noreply=False) with pytest.raises(MemcacheIllegalInputError): # non-ASCII digit client.cas(b'key', b'value', '⁰', noreply=False) def test_cas_stored(self): client = self.make_client([b'STORED\r\n']) result = client.cas(b'key', b'value', b'123', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.cas(b'key', b'value', b'123', noreply=False) assert result is True def test_cas_exists(self): client = self.make_client([b'EXISTS\r\n']) result = client.cas(b'key', b'value', b'123', noreply=False) assert result is False # unit test for encoding passed in __init__() client = self.make_client([b'EXISTS\r\n'], encoding='utf-8') result = client.cas(b'key', b'value', b'123', noreply=False) assert result is False def test_cas_not_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.cas(b'key', b'value', b'123', noreply=False) assert result is None # unit test for encoding passed in __init__() client = self.make_client([b'NOT_FOUND\r\n'], encoding='utf-8') result = client.cas(b'key', b'value', b'123', noreply=False) assert result is None def test_cr_nl_boundaries(self): client = self.make_client([b'VALUE key1 0 6\r', b'\nvalue1\r\n' b'VALUE key2 0 6\r\n', b'value2\r\n' b'END\r\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} client = self.make_client([b'VALUE key1 0 6\r\n', b'value1\r', b'\nVALUE key2 0 6\r\n', b'value2\r\n', b'END\r\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} client = self.make_client([b'VALUE key1 0 6\r\n', b'value1\r\n', b'VALUE key2 0 6\r', b'\nvalue2\r\n', b'END\r\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} client = self.make_client([b'VALUE key1 0 6\r\n', b'value1\r\n', b'VALUE key2 0 6\r\n', b'value2\r', b'\nEND\r\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} client = self.make_client([b'VALUE key1 0 6\r\n', b'value1\r\n', b'VALUE key2 0 6\r\n', b'value2\r\n', b'END\r', b'\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} client = self.make_client([b'VALUE key1 0 6\r', b'\nvalue1\r', b'\nVALUE key2 0 6\r', b'\nvalue2\r', b'\nEND\r', b'\n']) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} def test_delete_exception(self): client = self.make_client([Exception('fail')]) def _delete(): client.delete(b'key', noreply=False) with pytest.raises(Exception): _delete() assert client.sock is None def test_flush_all(self): client = self.make_client([b'OK\r\n']) result = client.flush_all(noreply=False) assert result is True def test_incr_exception(self): client = self.make_client([Exception('fail')]) def _incr(): client.incr(b'key', 1) with pytest.raises(Exception): _incr() assert client.sock is None def test_get_error(self): client = self.make_client([b'ERROR\r\n']) def _get(): client.get(b'key') with pytest.raises(MemcacheUnknownCommandError): _get() def test_get_recv_chunks(self): client = self.make_client([b'VALUE key', b' 0 5\r', b'\nvalue', b'\r\n', b'END', b'\r', b'\n']) result = client.get(b'key') assert result == b'value' def test_get_unknown_error(self): client = self.make_client([b'foobarbaz\r\n']) def _get(): client.get(b'key') with pytest.raises(MemcacheUnknownError): _get() def test_gets_not_found(self): client = self.make_client([b'END\r\n']) result = client.gets(b'key') assert result == (None, None) def test_gets_not_found_defaults(self): client = self.make_client([b'END\r\n']) result = client.gets(b'key', default='foo', cas_default='bar') assert result == ('foo', 'bar') def test_gets_found(self): client = self.make_client([b'VALUE key 0 5 10\r\nvalue\r\nEND\r\n']) result = client.gets(b'key') assert result == (b'value', b'10') def test_gets_many_none_found(self): client = self.make_client([b'END\r\n']) result = client.gets_many([b'key1', b'key2']) assert result == {} def test_gets_many_some_found(self): client = self.make_client([b'VALUE key1 0 6 11\r\nvalue1\r\nEND\r\n']) result = client.gets_many([b'key1', b'key2']) assert result == {b'key1': (b'value1', b'11')} def test_touch_not_found(self): client = self.make_client([b'NOT_FOUND\r\n']) result = client.touch(b'key', noreply=False) assert result is False def test_touch_found(self): client = self.make_client([b'TOUCHED\r\n']) result = client.touch(b'key', noreply=False) assert result is True def test_quit(self): client = self.make_client([]) result = client.quit() assert result is None assert client.sock is None def test_shutdown(self): client = self.make_client([MemcacheUnexpectedCloseError('shutdown')]) result = client.shutdown() assert result is None def test_shutdown_disabled(self): def _shutdown(): client = self.make_client([b'ERROR: shutdown not enabled\r\n']) client.shutdown() with pytest.raises(MemcacheUnknownCommandError): _shutdown() def test_replace_stored(self): client = self.make_client([b'STORED\r\n']) result = client.replace(b'key', b'value', noreply=False) assert result is True # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.replace(b'key', b'value', noreply=False) assert result is True def test_replace_not_stored(self): client = self.make_client([b'NOT_STORED\r\n']) result = client.replace(b'key', b'value', noreply=False) assert result is False # unit test for encoding passed in __init__ client = self.make_client([b'NOT_STORED\r\n'], encoding='utf-8') result = client.replace(b'key', b'value', noreply=False) assert result is False def test_serialization(self): class JsonSerde: def serialize(self, key, value): return json.dumps(value).encode('ascii'), 0 def deserialize(self, key, value, flags): return json.loads(value.decode('ascii')) client = self.make_client([b'STORED\r\n'], serde=JsonSerde()) client.set('key', {'c': 'd'}) assert client.sock.send_bufs == [ b'set key 0 0 10 noreply\r\n{"c": "d"}\r\n' ] def test_serialization_flags(self): def _ser(key, value): return value, 1 if isinstance(value, int) else 0 client = self.make_client( [b'STORED\r\n', b'STORED\r\n'], serializer=_ser) client.set_many( collections.OrderedDict([(b'a', b's'), (b'b', 0)]), noreply=False) assert client.sock.send_bufs == [ b'set a 0 0 1\r\ns\r\nset b 1 0 1\r\n0\r\n' ] def test_serialization_overridden_flags(self): def _ser(key, value): return value, 1 if isinstance(value, int) else 0 client = self.make_client( [b'STORED\r\n', b'STORED\r\n'], serializer=_ser) client.set_many( collections.OrderedDict([(b'a', b's'), (b'b', 0)]), noreply=False, flags=5) assert client.sock.send_bufs == [ b'set a 5 0 1\r\ns\r\nset b 5 0 1\r\n0\r\n' ] def test_explicit_flags(self): client = self.make_client([b'STORED\r\n', b'STORED\r\n']) client.set_many( collections.OrderedDict([(b'a', b's'), (b'b', 0)]), noreply=False, flags=5) assert client.sock.send_bufs == [ b'set a 5 0 1\r\ns\r\nset b 5 0 1\r\n0\r\n' ] def test_set_socket_handling(self): client = self.make_client([b'STORED\r\n']) result = client.set(b'key', b'value', noreply=False) assert result is True assert client.sock.closed is False assert len(client.sock.send_bufs) == 1 def test_set_error(self): client = self.make_client([b'ERROR\r\n']) def _set(): client.set(b'key', b'value', noreply=False) with pytest.raises(MemcacheUnknownCommandError): _set() def test_set_exception(self): client = self.make_client([Exception('fail')]) def _set(): client.set(b'key', b'value', noreply=False) with pytest.raises(Exception): _set() assert client.sock is None def test_set_client_error(self): client = self.make_client([b'CLIENT_ERROR some message\r\n']) def _set(): client.set('key', 'value', noreply=False) with pytest.raises(MemcacheClientError): _set() def test_set_server_error(self): client = self.make_client([b'SERVER_ERROR some message\r\n']) def _set(): client.set(b'key', b'value', noreply=False) with pytest.raises(MemcacheServerError): _set() def test_closing_socket_on_unexpected_closed_error(self): client = self.make_client([ b'VALUE ', MemcacheUnexpectedCloseError("foo bar"), ]) def _set(): client.set(b'key', b'value', noreply=False) with pytest.raises(MemcacheUnexpectedCloseError): _set() assert client.sock is None def test_set_unknown_error(self): client = self.make_client([b'foobarbaz\r\n']) def _set(): client.set(b'key', b'value', noreply=False) with pytest.raises(MemcacheUnknownError): _set() def test_set_key_with_space(self): client = self.make_client([b'']) def _set(): client.set(b'key has space', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_key_with_newline(self): client = self.make_client([b'']) def _set(): client.set(b'key\n', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_key_with_carriage_return(self): client = self.make_client([b'']) def _set(): client.set(b'key\r', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_key_with_null_character(self): client = self.make_client([b'']) def _set(): client.set(b'key\00', b'value', noreply=False) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_key_with_noninteger_expire(self): client = self.make_client([b'']) class _OneLike: """object that looks similar to the int 1""" def __str__(self): return "1" for noreply in (True, False): for expire in (1.5, _OneLike(), "1"): def _set(): client.set(b'finekey', b'finevalue', noreply=noreply, expire=expire) with pytest.raises(MemcacheIllegalInputError): _set() def test_set_many_socket_handling(self): client = self.make_client([b'STORED\r\n']) result = client.set_many({b'key': b'value'}, noreply=False) assert result == [] assert client.sock.closed is False assert len(client.sock.send_bufs) == 1 # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n'], encoding='utf-8') result = client.set_many({b'key': b'value'}, noreply=False) assert result == [] assert client.sock.closed is False assert len(client.sock.send_bufs) == 1 def test_set_many_exception(self): client = self.make_client([b'STORED\r\n', Exception('fail')]) def _set(): client.set_many({b'key': b'value', b'other': b'value'}, noreply=False) with pytest.raises(Exception): _set() assert client.sock is None # unit test for encoding passed in __init__() client = self.make_client([b'STORED\r\n', Exception('fail')], encoding='utf-8') def _set(): client.set_many({b'key': b'value', b'other': b'value'}, noreply=False) with pytest.raises(Exception): _set() assert client.sock is None def test_stats(self): client = self.make_client([b'STAT fake_stats 1\r\n', b'END\r\n']) result = client.stats() assert client.sock.send_bufs == [ b'stats\r\n' ] assert result == {b'fake_stats': 1} def test_stats_with_args(self): client = self.make_client([b'STAT fake_stats 1\r\n', b'END\r\n']) result = client.stats('some_arg') assert client.sock.send_bufs == [ b'stats some_arg\r\n' ] assert result == {b'fake_stats': 1} def test_stats_conversions(self): client = self.make_client([ # Most stats are converted to int b'STAT cmd_get 2519\r\n', b'STAT cmd_set 3099\r\n', b'STAT evictions 939\r\n', # Unless they can't be, they remain str b'STAT libevent 2.0.19-stable\r\n', # Some named stats are explicitly converted b'STAT hash_is_expanding 0\r\n', b'STAT rusage_user 0.609165\r\n', b'STAT rusage_system 0.852791\r\n', b'STAT slab_reassign_running 1\r\n', b'STAT version 1.4.14\r\n', b'STAT umask 777\r\n', b'STAT auth_enabled_sasl yes\r\n', b'END\r\n', ]) result = client.stats() assert client.sock.send_bufs == [ b'stats\r\n' ] expected = { b'cmd_get': 2519, b'cmd_set': 3099, b'evictions': 939, b'libevent': b'2.0.19-stable', b'hash_is_expanding': False, b'rusage_user': 0.609165, b'rusage_system': 0.852791, b'slab_reassign_running': True, b'version': b'1.4.14', b'umask': 0o777, b'auth_enabled_sasl': True, } assert result == expected def test_stats_cachedump(self): client = self.make_client([b'ITEM bob [7 b; 0 s]\r\n', b'END\r\n']) result = client.stats('cachedump', '1', '1') assert client.sock.send_bufs == [ b'stats cachedump 1 1\r\n' ] assert result == {b'bob': b'[7 b; 0 s]'} def test_cache_memlimit(self): client = self.make_client([b'OK\r\n']) result = client.cache_memlimit(8) assert client.sock.send_bufs == [ b'cache_memlimit 8\r\n' ] assert result is True def test_python_dict_set_is_supported(self): client = self.make_client([b'STORED\r\n']) client[b'key'] = b'value' def test_python_dict_get_is_supported(self): client = self.make_client([b'VALUE key 0 5\r\nvalue\r\nEND\r\n']) assert client[b'key'] == b'value' def test_python_dict_get_not_found_is_supported(self): client = self.make_client([b'END\r\n']) def _get(): client[b'key'] with pytest.raises(KeyError): _get() def test_python_dict_del_is_supported(self): client = self.make_client([b'DELETED\r\n']) del client[b'key'] def test_too_long_key(self): client = self.make_client([b'END\r\n']) with pytest.raises(MemcacheClientError): client.get(b'x' * 251) def test_too_long_unicode_key(self): client = self.make_client([b'STORED\r\n'], allow_unicode_keys=True) with pytest.raises(MemcacheClientError): client.get('my☃'*150) with pytest.raises(MemcacheClientError): client.get('\u0FFF'*150) def test_key_contains_space(self): client = self.make_client([b'END\r\n']) with pytest.raises(MemcacheClientError): client.get(b'abc xyz') def test_key_contains_nonascii(self): client = self.make_client([b'END\r\n']) with pytest.raises(MemcacheClientError): client.get('\u3053\u3093\u306b\u3061\u306f') def _default_noreply_false(self, cmd, args, response): client = self.make_client(response, default_noreply=False) result = getattr(client, cmd)(*args) assert result is False def _default_noreply_true(self, cmd, args, response): client = self.make_client(response, default_noreply=True) result = getattr(client, cmd)(*args) assert result is True def _default_noreply_true_and_empty_list(self, cmd, args, response): client = self.make_client(response, default_noreply=True) result = getattr(client, cmd)(*args) assert result == [] def test_default_noreply_set(self): with pytest.raises(MemcacheUnknownError): self._default_noreply_false( 'set', (b'key', b'value'), [b'UNKNOWN\r\n']) self._default_noreply_false( 'set', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'set', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_set_many(self): with pytest.raises(MemcacheUnknownError): client = self.make_client([b'UNKNOWN\r\n'], default_noreply=False) result = client.set_many({b'key': b'value'}) assert result == [b'key'] self._default_noreply_true_and_empty_list( 'set_many', ({b'key': b'value'},), [b'NOT_STORED\r\n']) def test_default_noreply_add(self): self._default_noreply_false( 'add', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'add', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_replace(self): self._default_noreply_false( 'replace', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'replace', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_append(self): self._default_noreply_false( 'append', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'append', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_prepend(self): self._default_noreply_false( 'prepend', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'prepend', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_touch(self): self._default_noreply_false('touch', (b'key',), [b'NOT_FOUND\r\n']) self._default_noreply_true('touch', (b'key',), [b'NOT_FOUND\r\n']) def test_default_noreply_flush_all(self): self._default_noreply_false('flush_all', (), [b'__FAKE_RESPONSE__\r\n']) self._default_noreply_true('flush_all', (), [b'__FAKE_RESPONSE__\r\n']) def test_version_success(self): client = self.make_client([b'VERSION 1.2.3\r\n'], default_noreply=False) result = client.version() assert result == b'1.2.3' def test_version_exception(self): client = self.make_client([b'INVALID DATA\r\n'], default_noreply=False) with pytest.raises(MemcacheUnknownError): client.version() @pytest.mark.unit() class TestClientSocketConnect(unittest.TestCase): def test_socket_connect_ipv4(self): server = ('127.0.0.1', 11211) client = Client(server, socket_module=MockSocketModule()) client._connect() assert client.sock.connections == [server] assert client.sock.family == socket.AF_INET timeout = 2 connect_timeout = 3 client = Client( server, connect_timeout=connect_timeout, timeout=timeout, socket_module=MockSocketModule()) client._connect() assert client.sock.timeouts == [connect_timeout, timeout] client = Client(server, socket_module=MockSocketModule()) client._connect() assert client.sock.socket_options == [] client = Client( server, socket_module=MockSocketModule(), no_delay=True) client._connect() assert client.sock.socket_options == [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] def test_socket_connect_ipv6(self): server = ('::1', 11211) client = Client(server, socket_module=MockSocketModule()) client._connect() assert client.sock.connections == [server + (0, 0)] assert client.sock.family == socket.AF_INET6 timeout = 2 connect_timeout = 3 client = Client( server, connect_timeout=connect_timeout, timeout=timeout, socket_module=MockSocketModule()) client._connect() assert client.sock.timeouts == [connect_timeout, timeout] client = Client(server, socket_module=MockSocketModule()) client._connect() assert client.sock.socket_options == [] client = Client( server, socket_module=MockSocketModule(), no_delay=True) client._connect() assert client.sock.socket_options == [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] def test_socket_connect_unix(self): server = f'/tmp/pymemcache.{os.getpid()}' with MockUnixSocketServer(server): client = Client(server) client._connect() assert client.sock.family == socket.AF_UNIX @unittest.skipIf('Linux' != platform.system(), 'Socket keepalive only support Linux platforms.') def test_linux_socket_keepalive(self): server = ('::1', 11211) try: client = Client( server, socket_module=MockSocketModule(), socket_keepalive=KeepaliveOpts()) client._connect() except SystemError: self.fail("SystemError unexpectedly raised") with self.assertRaises(ValueError): # A KeepaliveOpts object is expected, a ValueError will be raised Client( server, socket_module=MockSocketModule(), socket_keepalive=True) @mock.patch('platform.system') def test_osx_socket_keepalive(self, platform_mock): platform_mock.return_value = 'Darwin' server = ('::1', 11211) # For the moment the socket keepalive is only implemented for Linux with self.assertRaises(SystemError): Client( server, socket_module=MockSocketModule(), socket_keepalive=KeepaliveOpts()) @mock.patch('platform.system') def test_windows_socket_keepalive(self, platform_mock): platform_mock.return_value = 'Windows' server = ('::1', 11211) # For the moment the socket keepalive is only implemented for Linux with self.assertRaises(SystemError): Client( server, socket_module=MockSocketModule(), socket_keepalive=KeepaliveOpts()) def test_socket_connect_closes_on_failure(self): server = ("example.com", 11211) socket_module = MockSocketModule(connect_failure=OSError()) client = Client(server, socket_module=socket_module) with pytest.raises(OSError): client._connect() assert len(socket_module.sockets) == 1 assert socket_module.sockets[0].connections == [] assert socket_module.sockets[0].closed def test_socket_close(self): server = ("example.com", 11211) client = Client(server, socket_module=MockSocketModule()) client._connect() assert client.sock is not None client.close() assert client.sock is None def test_socket_close_exception(self): server = ("example.com", 11211) socket_module = MockSocketModule(close_failure=OSError()) client = Client(server, socket_module=socket_module) client._connect() assert client.sock is not None client.close() assert client.sock is None class TestPooledClient(ClientTestMixin, unittest.TestCase): def make_client(self, mock_socket_values, **kwargs): mock_client = Client(None, **kwargs) mock_client.sock = MockSocket(list(mock_socket_values)) client = PooledClient(None, **kwargs) client.client_pool = pool.ObjectPool(lambda: mock_client) return client def _default_noreply_false(self, cmd, args, response): client = self.make_client(response, default_noreply=False) result = getattr(client, cmd)(*args) assert result is False def _default_noreply_true(self, cmd, args, response): client = self.make_client(response, default_noreply=True) result = getattr(client, cmd)(*args) assert result is True def _default_noreply_true_and_empty_list(self, cmd, args, response): client = self.make_client(response, default_noreply=True) result = getattr(client, cmd)(*args) assert result == [] def test_default_noreply_set(self): with pytest.raises(MemcacheUnknownError): self._default_noreply_false( 'set', (b'key', b'value'), [b'UNKNOWN\r\n']) self._default_noreply_false( 'set', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'set', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_set_many(self): with pytest.raises(MemcacheUnknownError): client = self.make_client([b'UNKNOWN\r\n'], default_noreply=False) client.set_many({b'key': b'value'}) self._default_noreply_true_and_empty_list( 'set_many', ({b'key': b'value'},), [b'NOT_STORED\r\n']) def test_default_noreply_add(self): self._default_noreply_false( 'add', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'add', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_replace(self): self._default_noreply_false( 'replace', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'replace', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_append(self): self._default_noreply_false( 'append', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'append', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_prepend(self): self._default_noreply_false( 'prepend', (b'key', b'value'), [b'NOT_STORED\r\n']) self._default_noreply_true( 'prepend', (b'key', b'value'), [b'NOT_STORED\r\n']) def test_default_noreply_touch(self): self._default_noreply_false('touch', (b'key',), [b'NOT_FOUND\r\n']) self._default_noreply_true('touch', (b'key',), [b'NOT_FOUND\r\n']) def test_default_noreply_flush_all(self): self._default_noreply_false('flush_all', (), [b'__FAKE_RESPONSE__\r\n']) self._default_noreply_true('flush_all', (), [b'__FAKE_RESPONSE__\r\n']) def test_custom_client(self): class MyClient(Client): pass client = PooledClient(('host', 11211)) client.client_class = MyClient assert isinstance(client.client_pool.get(), MyClient) class TestPooledClientIdleTimeout(ClientTestMixin, unittest.TestCase): def make_client(self, mock_socket_values, **kwargs): mock_client = Client(None, **kwargs) mock_client.sock = MockSocket(list(mock_socket_values)) client = PooledClient(None, pool_idle_timeout=60, **kwargs) client.client_pool = pool.ObjectPool(lambda: mock_client) return client def test_free_idle(self): class Counter: count = 0 def increment(self, obj): self.count += 1 removed = Counter() client = self.make_client([b'VALUE key 0 5\r\nvalue\r\nEND\r\n']*2) client.client_pool._after_remove = removed.increment client.client_pool._idle_clock = lambda: 0 client.set(b'key', b'value') assert removed.count == 0 client.get(b'key') assert removed.count == 0 # Advance clock to beyond the idle timeout. client.client_pool._idle_clock = lambda: 61 client.get(b'key') assert removed.count == 1 class TestMockClient(ClientTestMixin, unittest.TestCase): def make_client(self, mock_socket_values, **kwargs): client = MockMemcacheClient(None, **kwargs) client.sock = MockSocket(list(mock_socket_values)) return client def test_get_found(self): client = self.make_client([ b'STORED\r\n', b'VALUE key 0 5\r\nvalue\r\nEND\r\n', ]) result = client.set(b'key', b'value', noreply=False) result = client.get(b'key') assert result == b'value' def test_deserialization(self): class JsonSerde: def serialize(self, key, value): if isinstance(value, dict): return json.dumps(value).encode('UTF-8'), 1 return value, 0 def deserialize(self, key, value, flags): if flags == 1: return json.loads(value.decode('UTF-8')) return value client = self.make_client([ b'STORED\r\n', b'VALUE key1 0 5\r\nhello\r\nEND\r\n', b'STORED\r\n', b'VALUE key2 0 18\r\n{"hello": "world"}\r\nEND\r\n', ], serde=JsonSerde()) result = client.set(b'key1', b'hello', noreply=False) result = client.get(b'key1') assert result == b'hello' result = client.set(b'key2', dict(hello='world'), noreply=False) result = client.get(b'key2') assert result == dict(hello='world') class TestPrefixedClient(ClientTestMixin, unittest.TestCase): def make_client(self, mock_socket_values, **kwargs): client = Client(None, key_prefix=b'xyz:', **kwargs) client.sock = MockSocket(list(mock_socket_values)) return client def test_get_found(self): client = self.make_client([ b'STORED\r\n', b'VALUE xyz:key 0 5\r\nvalue\r\nEND\r\n', ]) result = client.set(b'key', b'value', noreply=False) result = client.get(b'key') assert result == b'value' def test_get_many_some_found(self): client = self.make_client([ b'STORED\r\n', b'VALUE xyz:key1 0 6\r\nvalue1\r\nEND\r\n', ]) result = client.set(b'key1', b'value1', noreply=False) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1'} def test_get_many_all_found(self): client = self.make_client([ b'STORED\r\n', b'STORED\r\n', b'VALUE xyz:key1 0 6\r\nvalue1\r\n', b'VALUE xyz:key2 0 6\r\nvalue2\r\nEND\r\n', ]) result = client.set(b'key1', b'value1', noreply=False) result = client.set(b'key2', b'value2', noreply=False) result = client.get_many([b'key1', b'key2']) assert result == {b'key1': b'value1', b'key2': b'value2'} def test_python_dict_get_is_supported(self): client = self.make_client([b'VALUE xyz:key 0 5\r\nvalue\r\nEND\r\n']) assert client[b'key'] == b'value' class TestPrefixedPooledClient(TestPrefixedClient): def make_client(self, mock_socket_values, **kwargs): mock_client = Client(None, key_prefix=b'xyz:', **kwargs) mock_client.sock = MockSocket(list(mock_socket_values)) client = PooledClient(None, key_prefix=b'xyz:', **kwargs) client.client_pool = pool.ObjectPool(lambda: mock_client) return client @pytest.mark.unit() class TestRetryOnEINTR(unittest.TestCase): def make_client(self, values): client = Client(None) client.sock = MockSocket(list(values)) return client def test_recv(self): client = self.make_client([ b'VALUE ', socket.error(errno.EINTR, "Interrupted system call"), b'key1 0 6\r\nval', socket.error(errno.EINTR, "Interrupted system call"), b'ue1\r\nEND\r\n', ]) assert client[b'key1'] == b'value1' @pytest.mark.unit() class TestNormalizeServerSpec(unittest.TestCase): def test_normalize_server_spec(self): f = normalize_server_spec assert f(None) is None assert f(('127.0.0.1', 12345)) == ('127.0.0.1', 12345) assert f(['127.0.0.1', 12345]) == ('127.0.0.1', 12345) assert f('unix:/run/memcached/socket') == '/run/memcached/socket' assert f('/run/memcached/socket') == '/run/memcached/socket' assert f('localhost') == ('localhost', 11211) assert f('localhost:12345') == ('localhost', 12345) assert f('[::1]') == ('::1', 11211) assert f('[::1]:12345') == ('::1', 12345) assert f('127.0.0.1') == ('127.0.0.1', 11211) assert f('127.0.0.1:12345') == ('127.0.0.1', 12345) with pytest.raises(ValueError) as excinfo: f({'host': 12345}) assert str(excinfo.value) == "Unknown server provided: {'host': 12345}" with pytest.raises(ValueError) as excinfo: f(12345) assert str(excinfo.value) == "Unknown server provided: 12345" @pytest.mark.unit() class TestKeepaliveopts(unittest.TestCase): def test_keepalive_opts(self): kao = KeepaliveOpts() assert (kao.idle == 1 and kao.intvl == 1 and kao.cnt == 5) kao = KeepaliveOpts(idle=1, intvl=4, cnt=2) assert (kao.idle == 1 and kao.intvl == 4 and kao.cnt == 2) kao = KeepaliveOpts(idle=8) assert (kao.idle == 8 and kao.intvl == 1 and kao.cnt == 5) kao = KeepaliveOpts(cnt=8) assert (kao.idle == 1 and kao.intvl == 1 and kao.cnt == 8) with self.assertRaises(ValueError): KeepaliveOpts(cnt=0) with self.assertRaises(ValueError): KeepaliveOpts(idle=-1)
# Copyright (c) 2002-2009 Tampere University. # # This file is part of TTA-Based Codesign Environment (TCE). # # 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. import os import sys import comtypes from .. import utils import comtypes.client import _winreg as win_registry from distutils import msvccompiler class binaries_searcher_t: def get_msbsc_path( self ): relative_path = os.path.dirname( sys.modules[__name__].__file__) absolute_path = os.path.abspath (relative_path) return os.path.join( absolute_path, 'msbsc70.dll' ) def get_msvcr70_path( self ): relative_path = os.path.dirname( sys.modules[__name__].__file__) absolute_path = os.path.abspath (relative_path) return os.path.join( absolute_path, 'msvcr70.dll' ) def get_msvcr_path( self ): vss_installed = self.__get_installed_vs_dirs() for f in utils.files_walker( vss_installed, ["*.dll"], ): f_path, f_name = os.path.split( f.upper() ) if f_name.startswith( 'MSVCR' ): return f else: raise RuntimeError( 'Unable to find msvcrXX.dll. Search path is: %s' % vss_installed ) def get_msdia_path( self ): vss_installed = self.__get_installed_vs_dirs() msdia_dlls = self.__get_msdia_dll_paths( vss_installed ) if 1 == len(msdia_dlls): return msdia_dlls[0] else: #TODO find the highest version and use it. pass def __get_msdia_dll_paths( self, vss_installed ): msdia_dlls = [] for vs in vss_installed: debug_dir = os.path.join( vs, 'Common7', 'Packages', 'Debugger' ) files = filter( lambda f: f.startswith( 'msdia' ) and f.endswith( '.dll' ) , os.listdir( debug_dir ) ) if not files: continue msdia_dlls.extend([ os.path.join( debug_dir, f ) for f in files ]) if not msdia_dlls: raise RuntimeError( 'pygccxml unable to find out msdiaXX.dll location' ) return msdia_dlls def __get_installed_vs_dirs( self ): vs_reg_path = 'Software\Microsoft\VisualStudio\SxS\VS7' values = self.read_values( win_registry.HKEY_LOCAL_MACHINE, vs_reg_path ) return [ values.values()[0] ] def read_keys(self, base, key): return msvccompiler.read_keys(base, key) def read_values(self, base, key): return msvccompiler.read_values(base, key) bs = binaries_searcher_t() msdia_path = bs.get_msdia_path() print 'msdia path: ', msdia_path msbsc_path = bs.get_msbsc_path() print 'msbsc path: ', msbsc_path msvcr_path = bs.get_msvcr_path() print 'msvcr path: ', msvcr_path
'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var React = _interopDefault(require('react')); var _ref = /*#__PURE__*/ React.createElement("path", { fill: "currentColor", d: "M15 1H5a4 4 0 0 0 0 8h2V7a2 2 0 0 1 4 0v2h4a4 4 0 0 0 0-8" }); var _ref2 = /*#__PURE__*/ React.createElement("path", { d: "M15.873 13.679l-.72 4.32H4.677l-1.431-3.576c.59-.177 1.628-.134 3.047 1.284A.999.999 0 1 0 8 15V7a1.001 1.001 0 0 1 2 0v4a1 1 0 0 0 .684.949l5.189 1.73zM5 7.999A3 3 0 0 1 2 5c0-1.653 1.346-3 3-3h10c1.654 0 3 1.347 3 3 0 1.656-1.346 3-3 3h-3V7c0-1.653-1.346-3-3-3S6 5.347 6 7v1H5zm10 2c2.757 0 5-2.242 5-5 0-2.756-2.243-5-5-5H5A5.008 5.008 0 0 0 0 5c0 2.758 2.243 5 5 5h1v2.972c-2.184-1.214-3.959-.426-4.707.322-.283.283-.37.707-.222 1.079l2 5c.153.379.52.628.929.628h12a.999.999 0 0 0 .986-.835l1-6a.999.999 0 0 0-.67-1.113L12 10.28V10h3z" }); var SvgBuyButtonMajorTwotone = function SvgBuyButtonMajorTwotone(props) { return React.createElement("svg", Object.assign({ viewBox: "0 0 20 20" }, props), _ref, _ref2); }; exports.SvgBuyButtonMajorTwotone = SvgBuyButtonMajorTwotone;
import React, { PropTypes, Component } from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import cx from 'classnames'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import Paper from 'material-ui/Paper'; import IconButton from 'material-ui/IconButton'; import ViewReportIcon from 'material-ui/svg-icons/editor/insert-chart'; import RemoveIcon from 'material-ui/svg-icons/action/delete'; import FbAccountIcon from 'material-ui/svg-icons/action/input'; import EditBotIcon from 'material-ui/svg-icons/image/edit'; import CreateBotIcon from 'material-ui/svg-icons/content/add-box'; import { blue500, red500, green500, indigo500, indigo900, purple500, blue900, green900, cyan600, brown500, blueGrey500 } from 'material-ui/styles/colors'; import ViewFlowsIcon from 'material-ui/svg-icons/action/view-list'; import BroadcastIcon from 'material-ui/svg-icons/communication/message'; import RefreshIcon from 'material-ui/svg-icons/navigation/refresh'; import Divider from 'material-ui/Divider'; import Snackbar from 'material-ui/Snackbar'; import UserIcon from 'material-ui/svg-icons/social/person'; import PollIcon from 'material-ui/svg-icons/action/question-answer'; import SubscriptionIcon from 'material-ui/svg-icons/action/assignment'; import NoDataFound from '../noDataFound/noDataFound' import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, } from 'material-ui/Table'; import Link from '../../components/Link'; import s from './ManageAccount.css'; import flexbox from '../../components/flexbox.css'; import DeleteIcon from '../../components/DeleteIcon/DeleteIcon'; const title = 'BotWorx.Ai - Manage Account'; class ManageAccount extends Component{ constructor(props) { super(props); this.state = { nextPropsArrived: false }; } componentWillReceiveProps(nextProps){ this.setState({nextPropsArrived: true}); } componentDidMount() { const { setCurrentAccountTimeZone, allAccounts, accountDetails } = this.props; if(allAccounts && accountDetails) { const tz = allAccounts[accountDetails.id].timezone; console.log(`tz is ${tz}`); setCurrentAccountTimeZone(tz); } } render() { if(!this.state.nextPropsArrived){ return(<div></div>) } const { accountDetails, unusedBots, flowList, botName, botId, userId, botDetail, onBotNameChange, selectedBot, selectedFlow, onBotSelect, onFlowSelect, accountBots, onRemoveBotClick, onCreateBotClick, dialogstate, onCloseBot, onSubmitBotClick, onBotDescriptionChange, onEditBotClick, onFbAccountClick, errorText, userRole, onRefreshBotClick, snackbarState, onSnackbarStateClose, botPerms, onAnalyticsClick } = this.props; document.title = title; const actions = [ <FlatButton label="Cancel" primary={true} onTouchTap={onCloseBot} />, <FlatButton label="Save" primary={true} keyboardFocused={true} onTouchTap={() => onSubmitBotClick(botId, botName, botDetail)} />, ]; return ( <div className={cx(s.root, flexbox.fullHeight, flexbox.column)}> <Paper className={cx(s.topSection, flexbox.columnItem)}> <h3>Account Details</h3> <Divider /><br /> <div className={s.accountDetails}> <div className={s.accountDetail}> <span className={s.detailLabel}>Account</span> <span>{accountDetails.name}</span> </div> <div className={s.accountDetail}> <span className={s.detailLabel}>Admin</span> <span>{accountDetails.adminEmail}</span> </div> </div> </Paper> <Paper className={cx(s.section)}> <div> <h2 className={cx(s.headerelem)}>Account Bots</h2> {(botPerms && botPerms.length && (botPerms.includes('createBot') || botPerms.includes('*'))) ? <CreateBotIcon onClick={() => onCreateBotClick(botId)} color={green500} hoverColor={blue500} style={{width: '86px', height: '86px', padding: '24px'}} className={cx(s.createBot)} title="Add New Bot" /> : null} <Dialog title="Create New Bot" actions={actions} modal={false} open={dialogstate} onRequestClose={onCloseBot} > <form className={cx(flexbox.column, flexbox.rowItem)}> <b>Bot Name:</b> <input className={cx(s.createForm)} type="text" required="true" placeholder="Bot Name" value={botName} onChange={onBotNameChange} /> <div className={cx(s.errotText)}>{errorText}</div> <br /> <b>Bot Description:</b> <input className={cx(s.createForm)} type="text" placeholder="Bot Description" value={botDetail} onChange={onBotDescriptionChange} /> </form> </Dialog> </div> <Table> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn>Bot Name</TableHeaderColumn> <TableHeaderColumn>Actions</TableHeaderColumn> </TableRow> </TableHeader> {(accountBots.length) ? <TableBody displayRowCheckbox={false}> {accountBots.map(b => ( <TableRow selectable={false} key={b.id}> <TableRowColumn>{b.name + ' (' + b.id + ')'}</TableRowColumn> <TableRowColumn className={cx(flexbox.row, s.actions)}> {((b.allows.indexOf('editBot') !== -1) || (b.allows.indexOf('*') !== -1)) ? <IconButton onClick={() => onEditBotClick(accountDetails.id, b.id, b.name)} title="Edit" className={cx(flexbox.rowItem, s.action)} > <EditBotIcon color={green500}/> </IconButton> : null} {((b.allows.indexOf('viewAnalytics') !== -1) || (b.allows.indexOf('*') !== -1)) ? <IconButton onClick={() => { onAnalyticsClick(accountDetails.id, b.id); }} title="View Reports" className={cx(flexbox.rowItem, s.action)} > <ViewReportIcon color={blue500} /> </IconButton> : null } {((b.allows.indexOf('viewUsers') !== -1) || (b.allows.indexOf('*') !== -1)) ? <Link to={`/accounts/${accountDetails.id}/bots/${b.id}/userlist`} title="View Bot Users" className={cx(flexbox.rowItem, s.action)} > <UserIcon color={green900}/> </Link> : null} <Dialog title="Edit Selected Bot" actions={actions} modal={false} open={dialogstate} onRequestClose={onCloseBot} > <form className={cx(flexbox.column, flexbox.rowItem)}> <b>Bot Name<span style={{color:'red'}}>*</span>:</b> <input className={cx(s.createForm)} type="text" placeholder="Bot Name" value={botName} onChange={onBotNameChange} /> <div className={cx(s.errotText)}>{errorText}</div> <br /> <b>Bot Description:</b> <input className={cx(s.createForm)} type="text" placeholder="Bot Description" value={botDetail} onChange={onBotDescriptionChange} /> </form> </Dialog> {((b.allows.indexOf('viewBroadcasts') !== -1) || (b.allows.indexOf('*') !== -1)) ? <Link to={`/accounts/${accountDetails.id}/bots/${b.id}/broadcast`} title="View Broadcasts" className={cx(flexbox.rowItem, s.action)} > <BroadcastIcon color={indigo500}/> </Link> : null} {((b.allows.indexOf('viewFlows') !== -1) || (b.allows.indexOf('*') !== -1)) ? <Link to={`/accounts/${accountDetails.id}/bots/${b.id}/flows`} title="View Flows" className={cx(flexbox.rowItem, s.action)} > <ViewFlowsIcon color={cyan600}/> </Link> : null} {((b.allows.indexOf('deployBot') !== -1) || (b.allows.indexOf('*') !== -1)) ? <IconButton onClick={() => onFbAccountClick(userId, b.id, b.name, accountDetails.id)} title="Deploy" className={cx(flexbox.rowItem, s.action)} style={{marginLeft: -10}} > <FbAccountIcon color={purple500}/> </IconButton> : null} {((b.allows.indexOf('viewPolls') !== -1) || (b.allows.indexOf('*') !== -1)) ? <Link to={`/accounts/${accountDetails.id}/bots/${b.id}/polls`} title="View Polls" className={cx(flexbox.rowItem, s.action)} > <PollIcon color={brown500}/> </Link> : null} {((b.allows.indexOf('initializeBot') !== -1) || (b.allows.indexOf('*') !== -1)) ? <IconButton onClick={() => onRefreshBotClick(b.id)} title="Refresh" style={{marginLeft: -12}} className={cx(flexbox.rowItem, s.action)} > <RefreshIcon color={blue900}/> </IconButton> : null} {((b.allows.indexOf('viewSubscription') !== -1) || (b.allows.indexOf('*') !== -1)) ? <Link to={`/accounts/${accountDetails.id}/bots/${b.id}/subscriptions`} title="View Subscriptions" className={cx(flexbox.rowItem, s.action)} > <SubscriptionIcon color={blueGrey500}/> </Link> : null} <Snackbar open={snackbarState} message="Bot Refreshed" autoHideDuration={4000} onRequestClose={onSnackbarStateClose} /> {((b.allows.indexOf('deleteBot') !== -1) || (b.allows.indexOf('*') !== -1)) ? <DeleteIcon onDelete={() => { return onRemoveBotClick(accountDetails.id, b.id); }} itemType='Bot' itemName={`${b.name} (${b.id})`} /> : null} </TableRowColumn> </TableRow> ))} </TableBody> : <TableBody displayRowCheckbox={false}> <NoDataFound> <div className={s.noresultmsg}>No Bot Found</div> </NoDataFound> </TableBody> } </Table><br /><Divider /> </Paper> </div> ) } } ManageAccount.propTypes = { accountDetails: PropTypes.shape({ bots: PropTypes.array }), unusedBots: PropTypes.array, flowList: PropTypes.array, userRole: PropTypes.string, botName: PropTypes.string, botId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), userId: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), botDetail: PropTypes.string, selectedBot: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), selectedFlow: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), onBotSelect: PropTypes.func, onFlowSelect: PropTypes.func, accountBots: PropTypes.array, onRemoveBotClick: PropTypes.func, onCreateBotClick: PropTypes.func, onBotNameChange: PropTypes.func, dialogstate: PropTypes.bool, onCloseBot: PropTypes.func, onSubmitBotClick: PropTypes.func, onBotDescriptionChange: PropTypes.func, onEditBotClick: PropTypes.func, onFbAccountClick: PropTypes.func, onCloseModal: PropTypes.func, errorText: PropTypes.string, snackbarState: PropTypes.bool }; ManageAccount.defaultProps = { accountDetails: { bots: [] }, unusedBots: [], flowList: [], botName: '', botDetail: '', selectedBot: null, selectedFlow: null, accountBots: [], dialogstate: false, snackbarState: false }; ManageAccount.contextTypes = { setTitle: PropTypes.func.isRequired }; export default withStyles(flexbox, s)(ManageAccount);
import CodeBlock from "./CodeBlock.vue"; export default ({ Vue }) => { Vue.component("CodeBlock", CodeBlock); };
import os from time import sleep from django.conf import settings from django.test import TestCase from kolibri.utils import cli class KolibriTimedRotatingFileHandlerTestCase(TestCase): def test_do_rollover(self): archive_dir = os.path.join(os.environ["KOLIBRI_HOME"], "logs", "archive") orig_value = settings.LOGGING["handlers"]["file"]["when"] # Temporarily set the rotation time of the log file to be every second settings.LOGGING["handlers"]["file"]["when"] = "s" # make sure that kolibri will be running for more than one second cli.main(["--skipupdate", "manage", "help"]) sleep(1) cli.main(["--skipupdate", "manage", "help"]) # change back to the original rotation time settings.LOGGING["handlers"]["file"]["when"] = orig_value self.assertNotEqual(os.listdir(archive_dir), [])
# import needed libraries import numpy as np import matplotlib.pyplot as plt import math # get input data from truss_data_input import * # this will load all variables from data_input file # get global stiffness matrix of truss structure from truss_global_stiffness import truss_global_stiffness glob_k_e = truss_global_stiffness(COORD, MPRP, EM, CP) # elastic behavior # this functions splits global stiffness matrix from truss_k_split import split_matrix kff_e, kcc_e, kfc_e, kcf_e, ff, cc = split_matrix(glob_k_e, MSUP) # get force and displacement vectors from truss_f_d import truss_f_d F, Uprev = truss_f_d(glob_k_e, kff_e, kcf_e, MSUP, PJ, ff, cc) tolerance = 1 while tolerance >= 0.01: # get new deformed coordinates of truss from truss_deformed import deformed_COORD COORD_new = deformed_COORD(COORD, Uprev) # start ietartions here ... # get global parameters from truss_global_stiffness_NL import truss_global_stiffness_NL glob_k, glob_f = truss_global_stiffness_NL(COORD_new, COORD, MPRP, EM, CP) # split matrix from truss_k_split import split_matrix kff, kcc, kfc, kcf, ff, cc = split_matrix(glob_k, MSUP) # split force vector f_ff = glob_f[ff] # split applied force vector fr = [] for row in PJ: for i in row: fr.append(i) fr = np.transpose(np.array([fr])) fr_ff = fr[ff] # subtract forces f = np.subtract(fr_ff,f_ff) delta_d = np.dot(np.linalg.inv(kff), f) u = Uprev[ff] u = np.transpose(u) u = np.reshape(u, (len(ff),1)) tolerance = math.sqrt( np.sum(delta_d*delta_d)/np.sum(u*u)) u_ = np.add(delta_d,u) uf_list = u_.tolist() U=[0] * (len(ff)+len(cc)) for x, y in zip(uf_list, ff): U[y]=x[0] Uprev=np.array(U)
import tests.periodicities.period_test as per per.buildModel((60 , 'M' , 400));
const space = []; const sizes = { actionButton: 48, }; const fonts = { medium: "Montserrat-Medium", regular: "Montserrat-Regular", semibold: "Montserrat-SemiBold", bold: "Montserrat-Bold", light: "Montserrat-Light", italic: "Montserrat-Italic", }; const colors = { mainColor: "#1C739A", secondColor: "#F8F8F8", thirdColor: "#E8EAED", textDark: "#0A151F", textMedium: "#48515B", textLight: "#758291", }; const radii = { normal: 8, full: 9999, }; export default { space, radii, colors, sizes, fonts, };
export default { unmute: "Act. sonido", mute: "Silenciar", keypad: "Teclado", hold: "En espera", onHold: "En espera", park: "Estacionar", stopRecord: "Parar", record: "Grabar", add: "Agregar", transfer: "Transferir", flip: "Volteo", more: "Acc. de llam.", mergeToConference: "Combinar", end: "Fin", completeTransfer: "Completar\ntransferencia" }; // @key: @#@"unmute"@#@ @source: @#@"Unmute"@#@ // @key: @#@"mute"@#@ @source: @#@"Mute"@#@ // @key: @#@"keypad"@#@ @source: @#@"Keypad"@#@ // @key: @#@"hold"@#@ @source: @#@"Hold"@#@ // @key: @#@"onHold"@#@ @source: @#@"On Hold"@#@ // @key: @#@"park"@#@ @source: @#@"Park"@#@ // @key: @#@"stopRecord"@#@ @source: @#@"Stop"@#@ // @key: @#@"record"@#@ @source: @#@"Record"@#@ // @key: @#@"add"@#@ @source: @#@"Add"@#@ // @key: @#@"transfer"@#@ @source: @#@"Transfer"@#@ // @key: @#@"flip"@#@ @source: @#@"Flip"@#@ // @key: @#@"more"@#@ @source: @#@"Call Actions"@#@ // @key: @#@"mergeToConference"@#@ @source: @#@"Merge"@#@ // @key: @#@"end"@#@ @source: @#@"End"@#@ // @key: @#@"completeTransfer"@#@ @source: @#@"Complete\nTransfer"@#@
module.exports = { "39.0.2171.65": [ "0.20.0", "0.20.1", "0.20.2", "0.20.3", "0.20.4", "0.20.5", "0.20.6", "0.20.7", "0.20.8" ], "40.0.2214.91": [ "0.21.0", "0.21.1", "0.21.2" ], "41.0.2272.76": [ "0.21.3", "0.22.1", "0.22.2", "0.22.3", "0.23.0", "0.24.0" ], "42.0.2311.107": [ "0.25.0", "0.25.1", "0.25.2", "0.25.3", "0.26.0", "0.26.1", "0.27.0", "0.27.1" ], "43.0.2357.65": [ "0.27.2", "0.27.3", "0.28.0", "0.28.1", "0.28.2", "0.28.3", "0.29.1", "0.29.2" ], "44.0.2403.125": [ "0.30.4", "0.31.0" ], "45.0.2454.85": [ "0.31.2", "0.32.2", "0.32.3", "0.33.0", "0.33.1", "0.33.2", "0.33.3", "0.33.4", "0.33.6", "0.33.7", "0.33.8", "0.33.9", "0.34.0", "0.34.1", "0.34.2", "0.34.3", "0.34.4", "0.35.1", "0.35.2", "0.35.3", "0.35.4", "0.35.5" ], "47.0.2526.73": [ "0.36.0", "0.36.2", "0.36.3", "0.36.4" ], "47.0.2526.110": [ "0.36.5", "0.36.6", "0.36.7", "0.36.8", "0.36.9", "0.36.10", "0.36.11", "0.36.12" ], "49.0.2623.75": [ "0.37.0", "0.37.1", "0.37.3", "0.37.4", "0.37.5", "0.37.6", "0.37.7", "0.37.8", "1.0.0", "1.0.1", "1.0.2" ], "50.0.2661.102": [ "1.1.0", "1.1.1", "1.1.2", "1.1.3" ], "51.0.2704.63": [ "1.2.0", "1.2.1" ], "51.0.2704.84": [ "1.2.2", "1.2.3" ], "51.0.2704.103": [ "1.2.4", "1.2.5" ], "51.0.2704.106": [ "1.2.6", "1.2.7", "1.2.8" ], "52.0.2743.82": [ "1.3.0", "1.3.1", "1.3.2", "1.3.3", "1.3.4", "1.3.5", "1.3.6", "1.3.7", "1.3.9", "1.3.10", "1.3.13", "1.3.14", "1.3.15" ], "53.0.2785.113": [ "1.4.0", "1.4.1", "1.4.2", "1.4.3", "1.4.4", "1.4.5" ], "53.0.2785.143": [ "1.4.6", "1.4.7", "1.4.8", "1.4.10", "1.4.11", "1.4.13", "1.4.14", "1.4.15", "1.4.16" ], "54.0.2840.51": [ "1.4.12" ], "54.0.2840.101": [ "1.5.0", "1.5.1" ], "56.0.2924.87": [ "1.6.0", "1.6.1", "1.6.2", "1.6.3", "1.6.4", "1.6.5", "1.6.6", "1.6.7", "1.6.8", "1.6.9", "1.6.10", "1.6.11", "1.6.12", "1.6.13", "1.6.14", "1.6.15", "1.6.16", "1.6.17", "1.6.18" ], "58.0.3029.110": [ "1.7.0", "1.7.1", "1.7.2", "1.7.3", "1.7.4", "1.7.5", "1.7.6", "1.7.7", "1.7.8", "1.7.9", "1.7.10", "1.7.11", "1.7.12", "1.7.13", "1.7.14", "1.7.15", "1.7.16" ], "59.0.3071.115": [ "1.8.0", "1.8.1", "1.8.2-beta.1", "1.8.2-beta.2", "1.8.2-beta.3", "1.8.2-beta.4", "1.8.2-beta.5", "1.8.2", "1.8.3", "1.8.4", "1.8.5", "1.8.6", "1.8.7", "1.8.8" ], "61.0.3163.100": [ "2.0.0-beta.1", "2.0.0-beta.2", "2.0.0-beta.3", "2.0.0-beta.4", "2.0.0-beta.5", "2.0.0-beta.6", "2.0.0-beta.7", "2.0.0-beta.8", "2.0.0", "2.0.1", "2.0.2", "2.0.3", "2.0.4", "2.0.5", "2.0.6", "2.0.7", "2.0.8-nightly.20180819", "2.0.8-nightly.20180820", "2.0.8", "2.0.9", "2.0.10", "2.0.11", "2.0.12", "2.0.13", "2.0.14", "2.0.15", "2.0.16", "2.0.17", "2.0.18", "2.1.0-unsupported.20180809" ], "66.0.3359.181": [ "3.0.0-beta.1", "3.0.0-beta.2", "3.0.0-beta.3", "3.0.0-beta.4", "3.0.0-beta.5", "3.0.0-beta.6", "3.0.0-beta.7", "3.0.0-beta.8", "3.0.0-beta.9", "3.0.0-beta.10", "3.0.0-beta.11", "3.0.0-beta.12", "3.0.0-beta.13", "3.0.0-nightly.20180818", "3.0.0-nightly.20180821", "3.0.0-nightly.20180823", "3.0.0-nightly.20180904", "3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4", "3.0.5", "3.0.6", "3.0.7", "3.0.8", "3.0.9", "3.0.10", "3.0.11", "3.0.12", "3.0.13", "3.0.14", "3.0.15", "3.0.16", "3.1.0-beta.1", "3.1.0-beta.2", "3.1.0-beta.3", "3.1.0-beta.4", "3.1.0-beta.5", "3.1.0", "3.1.1", "3.1.2", "3.1.3", "3.1.4", "3.1.5", "3.1.6", "3.1.7", "3.1.8", "3.1.9", "3.1.10", "3.1.11", "3.1.12", "3.1.13", "4.0.0-nightly.20180817", "4.0.0-nightly.20180819", "4.0.0-nightly.20180821" ], "69.0.3497.106": [ "4.0.0-beta.1", "4.0.0-beta.2", "4.0.0-beta.3", "4.0.0-beta.4", "4.0.0-beta.5", "4.0.0-beta.6", "4.0.0-beta.7", "4.0.0-beta.8", "4.0.0-beta.9", "4.0.0-beta.10", "4.0.0-beta.11", "4.0.0-nightly.20181010", "4.0.0", "4.0.1", "4.0.2", "4.0.3", "4.0.4", "4.0.5", "4.0.6" ], "67.0.3396.99": [ "4.0.0-nightly.20180929" ], "68.0.3440.128": [ "4.0.0-nightly.20181006" ], "69.0.3497.128": [ "4.0.7", "4.0.8", "4.1.0", "4.1.1", "4.1.2", "4.1.3", "4.1.4", "4.1.5", "4.2.0", "4.2.1", "4.2.2", "4.2.3", "4.2.4", "4.2.5", "4.2.6", "4.2.7", "4.2.8", "4.2.9", "4.2.10", "4.2.11", "4.2.12" ], "72.0.3626.52": [ "5.0.0-beta.1", "5.0.0-beta.2" ], "73.0.3683.27": [ "5.0.0-beta.3" ], "73.0.3683.54": [ "5.0.0-beta.4" ], "73.0.3683.61": [ "5.0.0-beta.5" ], "73.0.3683.84": [ "5.0.0-beta.6" ], "73.0.3683.94": [ "5.0.0-beta.7" ], "73.0.3683.104": [ "5.0.0-beta.8" ], "73.0.3683.117": [ "5.0.0-beta.9" ], "70.0.3538.110": [ "5.0.0-nightly.20190107" ], "71.0.3578.98": [ "5.0.0-nightly.20190121", "5.0.0-nightly.20190122" ], "73.0.3683.119": [ "5.0.0" ], "73.0.3683.121": [ "5.0.1", "5.0.2", "5.0.3", "5.0.4", "5.0.5", "5.0.6", "5.0.7", "5.0.8", "5.0.9", "5.0.10", "5.0.11", "5.0.12", "5.0.13" ], "76.0.3774.1": [ "6.0.0-beta.1" ], "76.0.3783.1": [ "6.0.0-beta.2", "6.0.0-beta.3", "6.0.0-beta.4" ], "76.0.3805.4": [ "6.0.0-beta.5" ], "76.0.3809.3": [ "6.0.0-beta.6" ], "76.0.3809.22": [ "6.0.0-beta.7" ], "76.0.3809.26": [ "6.0.0-beta.8", "6.0.0-beta.9" ], "76.0.3809.37": [ "6.0.0-beta.10" ], "76.0.3809.42": [ "6.0.0-beta.11" ], "76.0.3809.54": [ "6.0.0-beta.12" ], "76.0.3809.60": [ "6.0.0-beta.13" ], "76.0.3809.68": [ "6.0.0-beta.14" ], "76.0.3809.74": [ "6.0.0-beta.15" ], "72.0.3626.107": [ "6.0.0-nightly.20190212" ], "72.0.3626.110": [ "6.0.0-nightly.20190213" ], "74.0.3724.8": [ "6.0.0-nightly.20190311" ], "76.0.3809.88": [ "6.0.0" ], "76.0.3809.102": [ "6.0.1" ], "76.0.3809.110": [ "6.0.2" ], "76.0.3809.126": [ "6.0.3" ], "76.0.3809.131": [ "6.0.4" ], "76.0.3809.136": [ "6.0.5" ], "76.0.3809.138": [ "6.0.6" ], "76.0.3809.139": [ "6.0.7" ], "76.0.3809.146": [ "6.0.8", "6.0.9", "6.0.10", "6.0.11", "6.0.12", "6.1.0", "6.1.1", "6.1.2", "6.1.3", "6.1.4", "6.1.5", "6.1.6", "6.1.7", "6.1.8", "6.1.9", "6.1.10", "6.1.11", "6.1.12" ], "78.0.3866.0": [ "7.0.0-beta.1", "7.0.0-beta.2", "7.0.0-beta.3", "7.0.0-nightly.20190727", "7.0.0-nightly.20190728", "7.0.0-nightly.20190729", "7.0.0-nightly.20190730", "7.0.0-nightly.20190731", "8.0.0-nightly.20190801", "8.0.0-nightly.20190802" ], "78.0.3896.6": [ "7.0.0-beta.4" ], "78.0.3905.1": [ "7.0.0-beta.5", "7.0.0-beta.6", "7.0.0-beta.7", "7.0.0" ], "76.0.3784.0": [ "7.0.0-nightly.20190521" ], "76.0.3806.0": [ "7.0.0-nightly.20190529", "7.0.0-nightly.20190530", "7.0.0-nightly.20190531", "7.0.0-nightly.20190602", "7.0.0-nightly.20190603" ], "77.0.3814.0": [ "7.0.0-nightly.20190604" ], "77.0.3815.0": [ "7.0.0-nightly.20190605", "7.0.0-nightly.20190606", "7.0.0-nightly.20190607", "7.0.0-nightly.20190608", "7.0.0-nightly.20190609", "7.0.0-nightly.20190611", "7.0.0-nightly.20190612", "7.0.0-nightly.20190613", "7.0.0-nightly.20190615", "7.0.0-nightly.20190616", "7.0.0-nightly.20190618", "7.0.0-nightly.20190619", "7.0.0-nightly.20190622", "7.0.0-nightly.20190623", "7.0.0-nightly.20190624", "7.0.0-nightly.20190627", "7.0.0-nightly.20190629", "7.0.0-nightly.20190630", "7.0.0-nightly.20190701", "7.0.0-nightly.20190702" ], "77.0.3843.0": [ "7.0.0-nightly.20190704", "7.0.0-nightly.20190705" ], "77.0.3848.0": [ "7.0.0-nightly.20190719", "7.0.0-nightly.20190720", "7.0.0-nightly.20190721" ], "77.0.3864.0": [ "7.0.0-nightly.20190726" ], "78.0.3904.92": [ "7.0.1" ], "78.0.3904.94": [ "7.1.0" ], "78.0.3904.99": [ "7.1.1" ], "78.0.3904.113": [ "7.1.2" ], "78.0.3904.126": [ "7.1.3" ], "78.0.3904.130": [ "7.1.4", "7.1.5", "7.1.6", "7.1.7", "7.1.8", "7.1.9", "7.1.10", "7.1.11", "7.1.12", "7.1.13", "7.1.14", "7.2.0", "7.2.1", "7.2.2", "7.2.3", "7.2.4", "7.3.0", "7.3.1", "7.3.2", "7.3.3" ], "79.0.3931.0": [ "8.0.0-beta.1", "8.0.0-beta.2", "8.0.0-nightly.20191019", "8.0.0-nightly.20191020", "8.0.0-nightly.20191021", "8.0.0-nightly.20191023" ], "80.0.3955.0": [ "8.0.0-beta.3", "8.0.0-beta.4" ], "80.0.3987.14": [ "8.0.0-beta.5" ], "80.0.3987.51": [ "8.0.0-beta.6" ], "80.0.3987.59": [ "8.0.0-beta.7" ], "80.0.3987.75": [ "8.0.0-beta.8", "8.0.0-beta.9" ], "78.0.3871.0": [ "8.0.0-nightly.20190803", "8.0.0-nightly.20190806", "8.0.0-nightly.20190807", "8.0.0-nightly.20190808", "8.0.0-nightly.20190809", "8.0.0-nightly.20190810", "8.0.0-nightly.20190811", "8.0.0-nightly.20190812", "8.0.0-nightly.20190813", "8.0.0-nightly.20190814", "8.0.0-nightly.20190815" ], "78.0.3881.0": [ "8.0.0-nightly.20190816", "8.0.0-nightly.20190817", "8.0.0-nightly.20190818", "8.0.0-nightly.20190819", "8.0.0-nightly.20190820" ], "78.0.3892.0": [ "8.0.0-nightly.20190824", "8.0.0-nightly.20190825", "8.0.0-nightly.20190827", "8.0.0-nightly.20190828", "8.0.0-nightly.20190830", "8.0.0-nightly.20190901", "8.0.0-nightly.20190902", "8.0.0-nightly.20190907", "8.0.0-nightly.20190909", "8.0.0-nightly.20190910", "8.0.0-nightly.20190911", "8.0.0-nightly.20190913", "8.0.0-nightly.20190914", "8.0.0-nightly.20190915", "8.0.0-nightly.20190917" ], "79.0.3915.0": [ "8.0.0-nightly.20190919", "8.0.0-nightly.20190920" ], "79.0.3919.0": [ "8.0.0-nightly.20190923", "8.0.0-nightly.20190924", "8.0.0-nightly.20190926", "8.0.0-nightly.20190929", "8.0.0-nightly.20190930", "8.0.0-nightly.20191001", "8.0.0-nightly.20191004", "8.0.0-nightly.20191005", "8.0.0-nightly.20191006", "8.0.0-nightly.20191009", "8.0.0-nightly.20191011", "8.0.0-nightly.20191012", "8.0.0-nightly.20191017" ], "80.0.3952.0": [ "8.0.0-nightly.20191101", "8.0.0-nightly.20191105" ], "80.0.3987.86": [ "8.0.0", "8.0.1", "8.0.2" ], "80.0.3987.134": [ "8.0.3" ], "80.0.3987.137": [ "8.1.0" ], "80.0.3987.141": [ "8.1.1" ], "80.0.3987.158": [ "8.2.0" ], "80.0.3987.163": [ "8.2.1", "8.2.2", "8.2.3", "8.5.3", "8.5.4", "8.5.5" ], "80.0.3987.165": [ "8.2.4", "8.2.5", "8.3.0", "8.3.1", "8.3.2", "8.3.3", "8.3.4", "8.4.0", "8.4.1", "8.5.0", "8.5.1", "8.5.2" ], "82.0.4048.0": [ "9.0.0-beta.1", "9.0.0-beta.2", "9.0.0-beta.3", "9.0.0-beta.4", "9.0.0-beta.5" ], "82.0.4058.2": [ "9.0.0-beta.6", "9.0.0-beta.7", "9.0.0-beta.9" ], "82.0.4085.10": [ "9.0.0-beta.10" ], "82.0.4085.14": [ "9.0.0-beta.12", "9.0.0-beta.13" ], "82.0.4085.27": [ "9.0.0-beta.14" ], "83.0.4102.3": [ "9.0.0-beta.15", "9.0.0-beta.16" ], "83.0.4103.14": [ "9.0.0-beta.17" ], "83.0.4103.16": [ "9.0.0-beta.18" ], "83.0.4103.24": [ "9.0.0-beta.19" ], "83.0.4103.26": [ "9.0.0-beta.20", "9.0.0-beta.21" ], "83.0.4103.34": [ "9.0.0-beta.22" ], "83.0.4103.44": [ "9.0.0-beta.23" ], "83.0.4103.45": [ "9.0.0-beta.24" ], "80.0.3954.0": [ "9.0.0-nightly.20191121", "9.0.0-nightly.20191122", "9.0.0-nightly.20191123", "9.0.0-nightly.20191124", "9.0.0-nightly.20191129", "9.0.0-nightly.20191130", "9.0.0-nightly.20191201", "9.0.0-nightly.20191202", "9.0.0-nightly.20191203", "9.0.0-nightly.20191204", "9.0.0-nightly.20191210" ], "81.0.3994.0": [ "9.0.0-nightly.20191220", "9.0.0-nightly.20191221", "9.0.0-nightly.20191222", "9.0.0-nightly.20191223", "9.0.0-nightly.20191224", "9.0.0-nightly.20191225", "9.0.0-nightly.20191226", "9.0.0-nightly.20191228", "9.0.0-nightly.20191229", "9.0.0-nightly.20191230", "9.0.0-nightly.20191231", "9.0.0-nightly.20200101", "9.0.0-nightly.20200103", "9.0.0-nightly.20200104", "9.0.0-nightly.20200105", "9.0.0-nightly.20200106", "9.0.0-nightly.20200108", "9.0.0-nightly.20200109", "9.0.0-nightly.20200110", "9.0.0-nightly.20200111", "9.0.0-nightly.20200113", "9.0.0-nightly.20200115", "9.0.0-nightly.20200116", "9.0.0-nightly.20200117" ], "81.0.4030.0": [ "9.0.0-nightly.20200119", "9.0.0-nightly.20200121" ], "83.0.4103.64": [ "9.0.0" ], "83.0.4103.94": [ "9.0.1", "9.0.2" ], "83.0.4103.100": [ "9.0.3" ], "83.0.4103.104": [ "9.0.4" ], "83.0.4103.119": [ "9.0.5" ], "83.0.4103.122": [ "9.1.0", "9.1.1", "9.1.2", "9.2.0", "9.2.1", "9.3.0", "9.3.1", "9.3.2", "9.3.3", "9.3.4", "9.3.5", "9.4.0", "9.4.1", "9.4.2", "9.4.3", "9.4.4" ], "84.0.4129.0": [ "10.0.0-beta.1", "10.0.0-beta.2", "10.0.0-nightly.20200501", "10.0.0-nightly.20200504", "10.0.0-nightly.20200505", "10.0.0-nightly.20200506", "10.0.0-nightly.20200507", "10.0.0-nightly.20200508", "10.0.0-nightly.20200511", "10.0.0-nightly.20200512", "10.0.0-nightly.20200513", "10.0.0-nightly.20200514", "10.0.0-nightly.20200515", "10.0.0-nightly.20200518", "10.0.0-nightly.20200519", "10.0.0-nightly.20200520", "10.0.0-nightly.20200521", "11.0.0-nightly.20200525", "11.0.0-nightly.20200526" ], "85.0.4161.2": [ "10.0.0-beta.3", "10.0.0-beta.4" ], "85.0.4181.1": [ "10.0.0-beta.8", "10.0.0-beta.9" ], "85.0.4183.19": [ "10.0.0-beta.10" ], "85.0.4183.20": [ "10.0.0-beta.11" ], "85.0.4183.26": [ "10.0.0-beta.12" ], "85.0.4183.39": [ "10.0.0-beta.13", "10.0.0-beta.14", "10.0.0-beta.15", "10.0.0-beta.17", "10.0.0-beta.19", "10.0.0-beta.20", "10.0.0-beta.21" ], "85.0.4183.70": [ "10.0.0-beta.23" ], "85.0.4183.78": [ "10.0.0-beta.24" ], "85.0.4183.80": [ "10.0.0-beta.25" ], "82.0.4050.0": [ "10.0.0-nightly.20200209", "10.0.0-nightly.20200210", "10.0.0-nightly.20200211", "10.0.0-nightly.20200216", "10.0.0-nightly.20200217", "10.0.0-nightly.20200218", "10.0.0-nightly.20200221", "10.0.0-nightly.20200222", "10.0.0-nightly.20200223", "10.0.0-nightly.20200226", "10.0.0-nightly.20200303" ], "82.0.4076.0": [ "10.0.0-nightly.20200304", "10.0.0-nightly.20200305", "10.0.0-nightly.20200306", "10.0.0-nightly.20200309", "10.0.0-nightly.20200310" ], "82.0.4083.0": [ "10.0.0-nightly.20200311" ], "83.0.4086.0": [ "10.0.0-nightly.20200316" ], "83.0.4087.0": [ "10.0.0-nightly.20200317", "10.0.0-nightly.20200318", "10.0.0-nightly.20200320", "10.0.0-nightly.20200323", "10.0.0-nightly.20200324", "10.0.0-nightly.20200325", "10.0.0-nightly.20200326", "10.0.0-nightly.20200327", "10.0.0-nightly.20200330", "10.0.0-nightly.20200331", "10.0.0-nightly.20200401", "10.0.0-nightly.20200402", "10.0.0-nightly.20200403", "10.0.0-nightly.20200406" ], "83.0.4095.0": [ "10.0.0-nightly.20200408", "10.0.0-nightly.20200410", "10.0.0-nightly.20200413" ], "84.0.4114.0": [ "10.0.0-nightly.20200414" ], "84.0.4115.0": [ "10.0.0-nightly.20200415", "10.0.0-nightly.20200416", "10.0.0-nightly.20200417" ], "84.0.4121.0": [ "10.0.0-nightly.20200422", "10.0.0-nightly.20200423" ], "84.0.4125.0": [ "10.0.0-nightly.20200427", "10.0.0-nightly.20200428", "10.0.0-nightly.20200429", "10.0.0-nightly.20200430" ], "85.0.4183.84": [ "10.0.0" ], "85.0.4183.86": [ "10.0.1" ], "85.0.4183.87": [ "10.1.0" ], "85.0.4183.93": [ "10.1.1" ], "85.0.4183.98": [ "10.1.2" ], "85.0.4183.121": [ "10.1.3", "10.1.4", "10.1.5", "10.1.6", "10.1.7", "10.2.0", "10.3.0", "10.3.1", "10.3.2", "10.4.0", "10.4.1", "10.4.2", "10.4.3", "10.4.4" ], "86.0.4234.0": [ "11.0.0-beta.1", "11.0.0-beta.3", "11.0.0-beta.4", "11.0.0-beta.5", "11.0.0-beta.6", "11.0.0-beta.7", "11.0.0-nightly.20200822", "11.0.0-nightly.20200824", "11.0.0-nightly.20200825", "11.0.0-nightly.20200826", "12.0.0-nightly.20200827", "12.0.0-nightly.20200831", "12.0.0-nightly.20200902", "12.0.0-nightly.20200903", "12.0.0-nightly.20200907", "12.0.0-nightly.20200910", "12.0.0-nightly.20200911", "12.0.0-nightly.20200914" ], "87.0.4251.1": [ "11.0.0-beta.8", "11.0.0-beta.9", "11.0.0-beta.11" ], "87.0.4280.11": [ "11.0.0-beta.12", "11.0.0-beta.13" ], "87.0.4280.27": [ "11.0.0-beta.16", "11.0.0-beta.17", "11.0.0-beta.18", "11.0.0-beta.19" ], "87.0.4280.40": [ "11.0.0-beta.20" ], "87.0.4280.47": [ "11.0.0-beta.22", "11.0.0-beta.23" ], "85.0.4156.0": [ "11.0.0-nightly.20200529" ], "85.0.4162.0": [ "11.0.0-nightly.20200602", "11.0.0-nightly.20200603", "11.0.0-nightly.20200604", "11.0.0-nightly.20200609", "11.0.0-nightly.20200610", "11.0.0-nightly.20200611", "11.0.0-nightly.20200615", "11.0.0-nightly.20200616", "11.0.0-nightly.20200617", "11.0.0-nightly.20200618", "11.0.0-nightly.20200619" ], "85.0.4179.0": [ "11.0.0-nightly.20200701", "11.0.0-nightly.20200702", "11.0.0-nightly.20200703", "11.0.0-nightly.20200706", "11.0.0-nightly.20200707", "11.0.0-nightly.20200708", "11.0.0-nightly.20200709" ], "86.0.4203.0": [ "11.0.0-nightly.20200716", "11.0.0-nightly.20200717", "11.0.0-nightly.20200720", "11.0.0-nightly.20200721" ], "86.0.4209.0": [ "11.0.0-nightly.20200723", "11.0.0-nightly.20200724", "11.0.0-nightly.20200729", "11.0.0-nightly.20200730", "11.0.0-nightly.20200731", "11.0.0-nightly.20200803", "11.0.0-nightly.20200804", "11.0.0-nightly.20200805", "11.0.0-nightly.20200811", "11.0.0-nightly.20200812" ], "87.0.4280.60": [ "11.0.0", "11.0.1" ], "87.0.4280.67": [ "11.0.2", "11.0.3", "11.0.4" ], "87.0.4280.88": [ "11.0.5", "11.1.0", "11.1.1" ], "87.0.4280.141": [ "11.2.0", "11.2.1", "11.2.2", "11.2.3", "11.3.0", "11.4.0", "11.4.1", "11.4.2", "11.4.3", "11.4.4" ], "89.0.4328.0": [ "12.0.0-beta.1", "12.0.0-beta.3", "12.0.0-beta.4", "12.0.0-beta.5", "12.0.0-beta.6", "12.0.0-beta.7", "12.0.0-beta.8", "12.0.0-beta.9", "12.0.0-beta.10", "12.0.0-beta.11", "12.0.0-beta.12", "12.0.0-beta.14", "13.0.0-nightly.20201119", "13.0.0-nightly.20201123", "13.0.0-nightly.20201124", "13.0.0-nightly.20201126", "13.0.0-nightly.20201127", "13.0.0-nightly.20201130", "13.0.0-nightly.20201201", "13.0.0-nightly.20201202", "13.0.0-nightly.20201203", "13.0.0-nightly.20201204", "13.0.0-nightly.20201207", "13.0.0-nightly.20201208", "13.0.0-nightly.20201209", "13.0.0-nightly.20201210", "13.0.0-nightly.20201211", "13.0.0-nightly.20201214" ], "89.0.4348.1": [ "12.0.0-beta.16", "12.0.0-beta.18", "12.0.0-beta.19", "12.0.0-beta.20" ], "89.0.4388.2": [ "12.0.0-beta.21", "12.0.0-beta.22", "12.0.0-beta.23", "12.0.0-beta.24", "12.0.0-beta.25", "12.0.0-beta.26" ], "89.0.4389.23": [ "12.0.0-beta.27", "12.0.0-beta.28", "12.0.0-beta.29" ], "89.0.4389.58": [ "12.0.0-beta.30", "12.0.0-beta.31" ], "87.0.4268.0": [ "12.0.0-nightly.20201013", "12.0.0-nightly.20201014", "12.0.0-nightly.20201015" ], "88.0.4292.0": [ "12.0.0-nightly.20201023", "12.0.0-nightly.20201026" ], "88.0.4306.0": [ "12.0.0-nightly.20201030", "12.0.0-nightly.20201102", "12.0.0-nightly.20201103", "12.0.0-nightly.20201104", "12.0.0-nightly.20201105", "12.0.0-nightly.20201106", "12.0.0-nightly.20201111", "12.0.0-nightly.20201112" ], "88.0.4324.0": [ "12.0.0-nightly.20201116" ], "89.0.4389.69": [ "12.0.0" ], "89.0.4389.82": [ "12.0.1" ], "89.0.4389.90": [ "12.0.2" ], "89.0.4389.114": [ "12.0.3", "12.0.4" ], "89.0.4389.128": [ "12.0.5" ], "90.0.4402.0": [ "13.0.0-beta.2", "13.0.0-beta.3", "13.0.0-nightly.20210210", "13.0.0-nightly.20210211", "13.0.0-nightly.20210212", "13.0.0-nightly.20210216", "13.0.0-nightly.20210217", "13.0.0-nightly.20210218", "13.0.0-nightly.20210219", "13.0.0-nightly.20210222", "13.0.0-nightly.20210225", "13.0.0-nightly.20210226", "13.0.0-nightly.20210301", "13.0.0-nightly.20210302", "13.0.0-nightly.20210303", "14.0.0-nightly.20210304" ], "90.0.4415.0": [ "13.0.0-beta.4", "13.0.0-beta.5", "13.0.0-beta.6", "13.0.0-beta.7", "13.0.0-beta.8", "13.0.0-beta.9", "13.0.0-beta.11", "13.0.0-beta.12", "13.0.0-beta.13", "14.0.0-nightly.20210305", "14.0.0-nightly.20210308", "14.0.0-nightly.20210309", "14.0.0-nightly.20210311", "14.0.0-nightly.20210315", "14.0.0-nightly.20210316", "14.0.0-nightly.20210317", "14.0.0-nightly.20210318", "14.0.0-nightly.20210319", "14.0.0-nightly.20210323", "14.0.0-nightly.20210324", "14.0.0-nightly.20210325", "14.0.0-nightly.20210326", "14.0.0-nightly.20210329", "14.0.0-nightly.20210330" ], "91.0.4448.0": [ "13.0.0-beta.14", "13.0.0-beta.16", "13.0.0-beta.17", "13.0.0-beta.18", "14.0.0-nightly.20210331", "14.0.0-nightly.20210401", "14.0.0-nightly.20210402", "14.0.0-nightly.20210406", "14.0.0-nightly.20210407", "14.0.0-nightly.20210408", "14.0.0-nightly.20210409", "14.0.0-nightly.20210413" ], "89.0.4349.0": [ "13.0.0-nightly.20201215", "13.0.0-nightly.20201216", "13.0.0-nightly.20201221", "13.0.0-nightly.20201222" ], "89.0.4359.0": [ "13.0.0-nightly.20201223", "13.0.0-nightly.20210104", "13.0.0-nightly.20210108", "13.0.0-nightly.20210111" ], "89.0.4386.0": [ "13.0.0-nightly.20210113", "13.0.0-nightly.20210114", "13.0.0-nightly.20210118", "13.0.0-nightly.20210122", "13.0.0-nightly.20210125" ], "89.0.4389.0": [ "13.0.0-nightly.20210127", "13.0.0-nightly.20210128", "13.0.0-nightly.20210129", "13.0.0-nightly.20210201", "13.0.0-nightly.20210202", "13.0.0-nightly.20210203", "13.0.0-nightly.20210205", "13.0.0-nightly.20210208", "13.0.0-nightly.20210209" ], "92.0.4475.0": [ "14.0.0-nightly.20210426", "14.0.0-nightly.20210427" ], "92.0.4488.0": [ "14.0.0-nightly.20210430" ] };
// 模块设计模式5 ,把所有要暴露的属性和方法都放到一个对象中,然后把这个对象赋值给exports const greeting = 'SPDB'; function greet() { console.log(greeting); } module.exports = { greet: greet };
/** * @file * CKEditor button and group configuration user interface. */ (function ($, Drupal, drupalSettings, _) { Drupal.ckeditor = Drupal.ckeditor || {}; /** * Sets config behavior and creates config views for the CKEditor toolbar. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches admin behavior to the CKEditor buttons. * @prop {Drupal~behaviorDetach} detach * Detaches admin behavior from the CKEditor buttons on 'unload'. */ Drupal.behaviors.ckeditorAdmin = { attach(context) { // Process the CKEditor configuration fragment once. const $configurationForm = $(context) .find('.ckeditor-toolbar-configuration') .once('ckeditor-configuration'); if ($configurationForm.length) { const $textarea = $configurationForm // Hide the textarea that contains the serialized representation of the // CKEditor configuration. .find('.js-form-item-editor-settings-toolbar-button-groups') .hide() // Return the textarea child node from this expression. .find('textarea'); // The HTML for the CKEditor configuration is assembled on the server // and sent to the client as a serialized DOM fragment. $configurationForm.append(drupalSettings.ckeditor.toolbarAdmin); // Create a configuration model. Drupal.ckeditor.models.Model = new Drupal.ckeditor.Model({ $textarea, activeEditorConfig: JSON.parse($textarea.val()), hiddenEditorConfig: drupalSettings.ckeditor.hiddenCKEditorConfig, }); // Create the configuration Views. const viewDefaults = { model: Drupal.ckeditor.models.Model, el: $('.ckeditor-toolbar-configuration'), }; Drupal.ckeditor.views = { controller: new Drupal.ckeditor.ControllerView(viewDefaults), visualView: new Drupal.ckeditor.VisualView(viewDefaults), keyboardView: new Drupal.ckeditor.KeyboardView(viewDefaults), auralView: new Drupal.ckeditor.AuralView(viewDefaults), }; } }, detach(context, settings, trigger) { // Early-return if the trigger for detachment is something else than // unload. if (trigger !== 'unload') { return; } // We're detaching because CKEditor as text editor has been disabled; this // really means that all CKEditor toolbar buttons have been removed. // Hence,all editor features will be removed, so any reactions from // filters will be undone. const $configurationForm = $(context) .find('.ckeditor-toolbar-configuration') .findOnce('ckeditor-configuration'); if ( $configurationForm.length && Drupal.ckeditor.models && Drupal.ckeditor.models.Model ) { const config = Drupal.ckeditor.models.Model.toJSON().activeEditorConfig; const buttons = Drupal.ckeditor.views.controller.getButtonList(config); const $activeToolbar = $('.ckeditor-toolbar-configuration').find( '.ckeditor-toolbar-active', ); for (let i = 0; i < buttons.length; i++) { $activeToolbar.trigger('CKEditorToolbarChanged', [ 'removed', buttons[i], ]); } } }, }; /** * CKEditor configuration UI methods of Backbone objects. * * @namespace */ Drupal.ckeditor = { /** * A hash of View instances. * * @type {object} */ views: {}, /** * A hash of Model instances. * * @type {object} */ models: {}, /** * Translates changes in CKEditor config DOM structure to the config model. * * If the button is moved within an existing group, the DOM structure is * simply translated to a configuration model. If the button is moved into a * new group placeholder, then a process is launched to name that group * before the button move is translated into configuration. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $button * A jQuery set that contains an li element that wraps a button element. * @param {function} callback * A callback to invoke after the button group naming modal dialog has * been closed. * */ registerButtonMove(view, $button, callback) { const $group = $button.closest('.ckeditor-toolbar-group'); // If dropped in a placeholder button group, the user must name it. if ($group.hasClass('placeholder')) { if (view.isProcessing) { return; } view.isProcessing = true; Drupal.ckeditor.openGroupNameDialog(view, $group, callback); } else { view.model.set('isDirty', true); callback(true); } }, /** * Translates changes in CKEditor config DOM structure to the config model. * * Each row has a placeholder group at the end of the row. A user may not * move an existing button group past the placeholder group at the end of a * row. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of buttons. */ registerGroupMove(view, $group) { // Remove placeholder classes if necessary. let $row = $group.closest('.ckeditor-row'); if ($row.hasClass('placeholder')) { $row.removeClass('placeholder'); } // If there are any rows with just a placeholder group, mark the row as a // placeholder. $row .parent() .children() .each(function () { $row = $(this); if ( $row.find('.ckeditor-toolbar-group').not('.placeholder').length === 0 ) { $row.addClass('placeholder'); } }); view.model.set('isDirty', true); }, /** * Opens a dialog with a form for changing the title of a button group. * * @param {Backbone.View} view * The Backbone View that invoked this function. * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of buttons. * @param {function} callback * A callback to invoke after the button group naming modal dialog has * been closed. */ openGroupNameDialog(view, $group, callback) { callback = callback || function () {}; /** * Validates the string provided as a button group title. * * @param {HTMLElement} form * The form DOM element that contains the input with the new button * group title string. * * @return {bool} * Returns true when an error exists, otherwise returns false. */ function validateForm(form) { if (form.elements[0].value.length === 0) { const $form = $(form); if (!$form.hasClass('errors')) { $form .addClass('errors') .find('input') .addClass('error') .attr('aria-invalid', 'true'); $( `<div class="description" >${Drupal.t( 'Please provide a name for the button group.', )}</div>`, ).insertAfter(form.elements[0]); } return true; } return false; } /** * Attempts to close the dialog; Validates user input. * * @param {string} action * The dialog action chosen by the user: 'apply' or 'cancel'. * @param {HTMLElement} form * The form DOM element that contains the input with the new button * group title string. */ function closeDialog(action, form) { /** * Closes the dialog when the user cancels or supplies valid data. */ function shutdown() { // eslint-disable-next-line no-use-before-define dialog.close(action); // The processing marker can be deleted since the dialog has been // closed. delete view.isProcessing; } /** * Applies a string as the name of a CKEditor button group. * * @param {jQuery} $group * A jQuery set that contains an li element that wraps a group of * buttons. * @param {string} name * The new name of the CKEditor button group. */ function namePlaceholderGroup($group, name) { // If it's currently still a placeholder, then that means we're // creating a new group, and we must do some extra work. if ($group.hasClass('placeholder')) { // Remove all whitespace from the name, lowercase it and ensure // HTML-safe encoding, then use this as the group ID for CKEditor // configuration UI accessibility purposes only. const groupID = `ckeditor-toolbar-group-aria-label-for-${Drupal.checkPlain( name.toLowerCase().replace(/\s/g, '-'), )}`; $group // Update the group container. .removeAttr('aria-label') .attr('data-drupal-ckeditor-type', 'group') .attr('tabindex', 0) // Update the group heading. .children('.ckeditor-toolbar-group-name') .attr('id', groupID) .end() // Update the group items. .children('.ckeditor-toolbar-group-buttons') .attr('aria-labelledby', groupID); } $group .attr('data-drupal-ckeditor-toolbar-group-name', name) .children('.ckeditor-toolbar-group-name') .text(name); } // Invoke a user-provided callback and indicate failure. if (action === 'cancel') { shutdown(); callback(false, $group); return; } // Validate that a group name was provided. if (form && validateForm(form)) { return; } // React to application of a valid group name. if (action === 'apply') { shutdown(); // Apply the provided name to the button group label. namePlaceholderGroup( $group, Drupal.checkPlain(form.elements[0].value), ); // Remove placeholder classes so that new placeholders will be // inserted. $group .closest('.ckeditor-row.placeholder') .addBack() .removeClass('placeholder'); // Invoke a user-provided callback and indicate success. callback(true, $group); // Signal that the active toolbar DOM structure has changed. view.model.set('isDirty', true); } } // Create a Drupal dialog that will get a button group name from the user. const $ckeditorButtonGroupNameForm = $( Drupal.theme('ckeditorButtonGroupNameForm'), ); const dialog = Drupal.dialog($ckeditorButtonGroupNameForm.get(0), { title: Drupal.t('Button group name'), dialogClass: 'ckeditor-name-toolbar-group', resizable: false, buttons: [ { text: Drupal.t('Apply'), click() { closeDialog('apply', this); }, primary: true, }, { text: Drupal.t('Cancel'), click() { closeDialog('cancel'); }, }, ], open() { const form = this; const $form = $(this); const $widget = $form.parent(); $widget.find('.ui-dialog-titlebar-close').remove(); // Set a click handler on the input and button in the form. $widget.on('keypress.ckeditor', 'input, button', (event) => { // React to enter key press. if (event.keyCode === 13) { const $target = $(event.currentTarget); const data = $target.data('ui-button'); let action = 'apply'; // Assume 'apply', but take into account that the user might have // pressed the enter key on the dialog buttons. if (data && data.options && data.options.label) { action = data.options.label.toLowerCase(); } closeDialog(action, form); event.stopPropagation(); event.stopImmediatePropagation(); event.preventDefault(); } }); // Announce to the user that a modal dialog is open. let text = Drupal.t( 'Editing the name of the new button group in a dialog.', ); if ( typeof $group.attr('data-drupal-ckeditor-toolbar-group-name') !== 'undefined' ) { text = Drupal.t( 'Editing the name of the "@groupName" button group in a dialog.', { '@groupName': $group.attr( 'data-drupal-ckeditor-toolbar-group-name', ), }, ); } Drupal.announce(text); }, close(event) { // Automatically destroy the DOM element that was used for the dialog. $(event.target).remove(); }, }); // A modal dialog is used because the user must provide a button group // name or cancel the button placement before taking any other action. dialog.showModal(); $( document .querySelector('.ckeditor-name-toolbar-group') .querySelector('input'), ) // When editing, set the "group name" input in the form to the current // value. .attr('value', $group.attr('data-drupal-ckeditor-toolbar-group-name')) // Focus on the "group name" input in the form. .trigger('focus'); }, }; /** * Automatically shows/hides settings of buttons-only CKEditor plugins. * * @type {Drupal~behavior} * * @prop {Drupal~behaviorAttach} attach * Attaches show/hide behavior to Plugin Settings buttons. */ Drupal.behaviors.ckeditorAdminButtonPluginSettings = { attach(context) { const $context = $(context); const $ckeditorPluginSettings = $context .find('#ckeditor-plugin-settings') .once('ckeditor-plugin-settings'); if ($ckeditorPluginSettings.length) { // Hide all button-dependent plugin settings initially. $ckeditorPluginSettings .find('[data-ckeditor-buttons]') .each(function () { const $this = $(this); if ($this.data('verticalTab')) { $this.data('verticalTab').tabHide(); } else { // On very narrow viewports, Vertical Tabs are disabled. $this.hide(); } $this.data('ckeditorButtonPluginSettingsActiveButtons', []); }); // Whenever a button is added or removed, check if we should show or // hide the corresponding plugin settings. (Note that upon // initialization, each button that already is part of the toolbar still // is considered "added", hence it also works correctly for buttons that // were added previously.) $context .find('.ckeditor-toolbar-active') .off('CKEditorToolbarChanged.ckeditorAdminPluginSettings') .on( 'CKEditorToolbarChanged.ckeditorAdminPluginSettings', (event, action, button) => { const $pluginSettings = $ckeditorPluginSettings.find( `[data-ckeditor-buttons~=${button}]`, ); // No settings for this button. if ($pluginSettings.length === 0) { return; } const verticalTab = $pluginSettings.data('verticalTab'); const activeButtons = $pluginSettings.data( 'ckeditorButtonPluginSettingsActiveButtons', ); if (action === 'added') { activeButtons.push(button); // Show this plugin's settings if >=1 of its buttons are active. if (verticalTab) { verticalTab.tabShow(); } else { // On very narrow viewports, Vertical Tabs remain fieldsets. $pluginSettings.show(); } } else { // Remove this button from the list of active buttons. activeButtons.splice(activeButtons.indexOf(button), 1); // Show this plugin's settings 0 of its buttons are active. if (activeButtons.length === 0) { if (verticalTab) { verticalTab.tabHide(); } else { // On very narrow viewports, Vertical Tabs are disabled. $pluginSettings.hide(); } } } $pluginSettings.data( 'ckeditorButtonPluginSettingsActiveButtons', activeButtons, ); }, ); } }, }; /** * Themes a blank CKEditor row. * * @return {string} * A HTML string for a CKEditor row. */ Drupal.theme.ckeditorRow = function () { return '<li class="ckeditor-row placeholder" role="group"><ul class="ckeditor-toolbar-groups clearfix"></ul></li>'; }; /** * Themes a blank CKEditor button group. * * @return {string} * A HTML string for a CKEditor button group. */ Drupal.theme.ckeditorToolbarGroup = function () { let group = ''; group += `<li class="ckeditor-toolbar-group placeholder" role="presentation" aria-label="${Drupal.t( 'Place a button to create a new button group.', )}">`; group += `<h3 class="ckeditor-toolbar-group-name">${Drupal.t( 'New group', )}</h3>`; group += '<ul class="ckeditor-buttons ckeditor-toolbar-group-buttons" role="toolbar" data-drupal-ckeditor-button-sorting="target"></ul>'; group += '</li>'; return group; }; /** * Themes a form for changing the title of a CKEditor button group. * * @return {string} * A HTML string for the form for the title of a CKEditor button group. */ Drupal.theme.ckeditorButtonGroupNameForm = function () { return '<form><input name="group-name" required="required"></form>'; }; /** * Themes a button that will toggle the button group names in active config. * * @return {string} * A HTML string for the button to toggle group names. */ Drupal.theme.ckeditorButtonGroupNamesToggle = function () { return '<button class="link ckeditor-groupnames-toggle" aria-pressed="false"></button>'; }; /** * Themes a button that will prompt the user to name a new button group. * * @return {string} * A HTML string for the button to create a name for a new button group. */ Drupal.theme.ckeditorNewButtonGroup = function () { return `<li class="ckeditor-add-new-group"><button aria-label="${Drupal.t( 'Add a CKEditor button group to the end of this row.', )}">${Drupal.t('Add group')}</button></li>`; }; })(jQuery, Drupal, drupalSettings, _);
/** @jsx React.DOM */ define([ 'underscore', 'jquery', 'react', 'kendo', '../util/util', '../ControlCommon', '../ImmutableOptimizations' ], function (_, $, React, kendo, util, ControlCommon, ImmutableOptimizations) { 'use strict'; var KendoDate = React.createClass({ mixins: [ImmutableOptimizations(['onChange'])], statics: { fieldClass: function () { return 'formFieldDatepicker'; } }, getDefaultProps: function () { return { format: 'dd-MMM-yyyy', value: undefined, id: undefined, onChange: function () {}, disabled: false, isValid: [true, ''], readonly: false, noControl: false }; }, /*jshint ignore:start */ render: function () { return (this.props.noControl ? (<span>{this.props.value ? kendo.toString(util.parseISODate(this.props.value), this.props.format) : ''}</span>) : (<input id={this.props.id} type="text" />)); }, /*jshint ignore:end */ componentDidMount: function () { if (this.props.noControl) { // Everything was done in JSX. return; } var $el = $(this.getDOMNode()); console.assert($el); $el.kendoDatePicker({ change: this.onChange, format: this.props.format }); ControlCommon.setKendoDateState( $el.data('kendoDatePicker'), util.parseISODate(this.props.value), this.props.disabled, this.props.readonly, this.props.max, this.props.min); }, componentDidUpdate: function (prevProps, prevState) { if (this.props.noControl) { // Everything was done in JSX. return; } var $el = $(this.getDOMNode()); console.assert($el); ControlCommon.setKendoDateState( $el.data('kendoDatePicker'), util.parseISODate(this.props.value), this.props.disabled, this.props.readonly, this.props.max, this.props.min); }, onChange: function (event) { var kendoWidget = event.sender; var val = util.formatISODate(kendoWidget.value()); this.props.onChange(val); } }); return KendoDate; });
# -*- coding: utf-8 -*- """This module defines base class for trajectory handling.""" from numbers import Integral from numpy import ndarray, unique from caviar.prody_parser.ensemble import Ensemble from caviar.prody_parser.utilities import checkCoords, checkWeights from .frame import Frame __all__ = ['TrajBase'] class TrajBase(object): """Base class for :class:`.Trajectory` and :class:`.TrajFile`. Derived classes must implement functions described in this class.""" def __init__(self, title='Unknown'): self._title = str(title).strip() self._coords = None # reference self._n_atoms = 0 self._n_csets = 0 # number of conformations/frames/coordinate sets self._weights = None self._ag = None self._atoms = None self._indices = None # indices of selected atoms self._frame = None # if atoms are set, always return the same frame self._nfi = 0 self._closed = False def __iter__(self): if self._closed: raise ValueError('I/O operation on closed file') while self._nfi < self._n_csets: yield next(self) def __str__(self): return '{0} {1}'.format(self.__class__.__name__, self._title) def __getitem__(self, index): if self._closed: raise ValueError('I/O operation on closed file') if isinstance(index, Integral): return self.getFrame(index) elif isinstance(index, (slice, list, ndarray)): if isinstance(index, slice): ens = Ensemble('{0} ({1[0]}:{1[1]}:{1[2]})'.format( self._title, index.indices(len(self)))) else: ens = Ensemble('{0} slice'.format(self._title)) ens.setCoords(self.getCoords()) if self._weights is not None: ens.setWeights(self._weights.copy()) ens.addCoordset(self.getCoordsets(index)) ens.setAtoms(self._atoms) return ens else: raise IndexError('invalid index') def __len__(self): return self._n_csets def __enter__(self): return self def __exit__(self, type, value, tb): self.close() def getTitle(self): """Returns title of the ensemble.""" return self._title def setTitle(self, title): """Set title of the ensemble.""" self._title = str(title) def numAtoms(self): """Returns number of atoms.""" return self._n_atoms def numFrames(self): """Returns number of frames.""" return self._n_csets numCoordsets = numFrames def numSelected(self): """Returns number of selected atoms. A subset of atoms can be selected by passing a selection to :meth:`setAtoms`.""" return self._n_atoms if self._indices is None else len(self._indices) def getAtoms(self): """Returns associated/selected atoms.""" return self._atoms def setAtoms(self, atoms): """Set *atoms* or specify a selection of atoms to be considered in calculations and coordinate requests. When a selection is set, corresponding subset of coordinates will be considered in, for example, alignments and RMSD calculations. Setting atoms also allows some functions to access atomic data when needed. For example, :class:`.Trajectory` and :class:`.Frame` instances become suitable arguments for :func:`.writePDB`. Passing **None** as *atoms* argument will deselect atoms. Note that setting atoms does not change the reference coordinates of the trajectory. To change the reference, use :meth:`.setCoords` method.""" if atoms is None: self._atoms = self._indices = None return try: atoms.getACSIndex() except AttributeError: raise TypeError('atoms must be an Atomic instance') n_atoms = self._n_atoms if n_atoms: if atoms.numAtoms() > n_atoms: raise ValueError('atoms must be same size or smaller than ' 'the trajectory') try: dummies = atoms.numDummies() except AttributeError: pass else: if dummies: raise ValueError('atoms must not have any dummies') else: indices = atoms._getIndices() if indices != unique(indices): raise ValueError('atoms must be ordered by indices') if atoms.numAtoms() == n_atoms: self._atoms = atoms self._indices = None else: try: ag = atoms.getAtomGroup() except AttributeError: raise ValueError('atoms must indicate a subset or must ' 'match the trajectory size') else: if ag.numAtoms() != n_atoms: raise ValueError('atoms must point to an AtomGroup ' 'of the same size as the trajectory') self._atoms = atoms self._indices = atoms.getIndices() else: self._n_atoms = atoms.numAtoms() self._atoms = atoms def link(self, *ag): """Link, return, or unlink an :class:`.AtomGroup` instance. When a link to *ag* is established, coordinates of new frames parsed from the trajectory file will be set as the coordinates of *ag* and this will update coordinates of all selections and atom subsets pointing to it. At link time, if *ag* does not have any coordinate sets and reference coordinates of the trajectory is set, reference coordinates of the trajectory will be passed to *ag*. To break an established link, pass **None** argument, or to return the linked atom group instance, call with no arguments. .. warning:: Every time a frame is parsed from the trajectory, all coordinate sets present in the linked :class:`.AtomGroup` will be overwritten. """ if not ag: return self._ag else: if len(ag) > 1: raise TypeError('link() takes at most 1 argument ({0} given)' .format(len(ag))) ag = ag[0] try: ag.getACSIndex() except AttributeError: raise TypeError('ag must be an AtomGroup instance') try: ag.getAtomGroup() except AttributeError: pass else: raise TypeError('ag must be an AtomGroup instance') if self.numAtoms() != ag.numAtoms(): raise ValueError('atom group and trajectory must ' 'have same number of atoms') self._ag = ag if ag._getCoords() is None and self._coords is not None: self._ag._setCoords(self._coords) self._frame = Frame(None, None, None) self._atoms = self._atoms or ag def getLinked(self): """Returns linked :class:`.AtomGroup` instance, or **None** if a link is not established.""" return self._ag def isLinked(self): """Returns **True** if trajectory is linked to an :class:`.AtomGroup` instance.""" return self._ag is not None def getCoords(self): """Returns a copy of reference coordinates for (selected) atoms.""" if self._coords is None: return None if self._indices is None: return self._coords.copy() return self._coords[self._indices] def _getCoords(self): """Returns a view of reference coordinates for (selected) atoms.""" if self._coords is None: return None if self._indices is None: return self._coords return self._coords[self._indices] def setCoords(self, coords): """Set *coords* as the trajectory reference coordinate set. *coords* must be an object with :meth:`getCoords` method, or a Numpy array with suitable data type, shape, and dimensionality.""" atoms = coords try: coords = atoms.getCoords() except AttributeError: pass else: if coords is None: raise ValueError('coordinates of {0} are not set' .format(str(atoms))) try: checkCoords(coords, natoms=self._n_atoms) except TypeError: raise TypeError('coords must be a numpy array or an object ' 'with `getCoords` method') self._coords = coords def setWeights(self, weights): """Set atomic weights.""" if self._n_atoms == 0: raise AttributeError('coordinates must be set first') self._weights = checkWeights(weights, self._n_atoms, None) def getWeights(self): """Returns a copy of weights of (selected) atoms.""" if self._weights is not None: if self._indices is None: return self._weights.copy() else: return self._weights[self._indices] def _getWeights(self): if self._weights is not None: if self._indices is None: return self._weights else: return self._weights[self._indices] def nextIndex(self): """Returns the index of the next frame.""" return self._nfi def iterCoordsets(self): """Yield coordinate sets for (selected) atoms. Reference coordinates are not included. Iteration starts from the next frame in line.""" if self._closed: raise ValueError('I/O operation on closed file') while self._nfi < self._n_csets: yield self.nextCoordset() def getCoordsets(self, indices=None): """Returns coordinate sets at given *indices*. *indices* may be an integer, a list of ordered integers or **None**. **None** returns all coordinate sets. If a list of indices is given, unique numbers will be selected and sorted. That is, this method will always return unique coordinate sets in the order they appear in the trajectory file. Shape of the coordinate set array is (n_sets, n_atoms, 3).""" pass def getFrame(self, index): """Returns frame at given *index*.""" pass def nextCoordset(self): """Returns next coordinate set.""" pass def __next__(self): """Returns next coordinate set in a :class:`.Frame` instance. Note that when atoms are set for the trajectory, this method will return the same frame instance after updating its coordinates.""" pass next = __next__ def goto(self, n): """Go to the frame at index *n*. ``n=0`` will rewind the trajectory to the beginning, same as calling :meth:`reset` method. ``n=-1`` will go to the last frame. Frame *n* will not be parsed until one of :meth:`next` or :meth:`nextCoordset` methods is called.""" pass def skip(self, n): """Skip *n* frames. *n* must be a positive integer. Skipping some frames will only change the next frame index (:meth:`nextIndex`) Next frame will not be parsed until one of :meth:`next` or :meth:`nextCoordset` methods is called.""" pass def reset(self): """Go to first frame at index 0. First frame will not be parsed until one of :meth:`next` or :meth:`nextCoordset` methods is called.""" pass def close(self): """Close trajectory file.""" pass def hasUnitcell(self): """Returns **True** if trajectory has unitcell data.""" pass
import React, { Component } from 'react'; import { connect } from 'react-redux' import { Typography } from '@material-ui/core'; import { withStyles } from '@material-ui/core/styles'; import Button from '@material-ui/core/Button'; import Box from '@material-ui/core/Box'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableContainer from '@material-ui/core/TableContainer'; import TableRow from '@material-ui/core/TableRow'; import Paper from '@material-ui/core/Paper'; import theme from '../../Theme/ThemeProvider'; import AddMenu from '../AddMenu/AddMenu' import menus from '../../../actions/menus'; import dish from '../../../actions/dishes' import dishcat from '../../../actions/dishcat' const style = { button_accent: { color: "#FE6726", borderColor: "#FE6726", '&:hover': { backgroundColor: "#FE6726", color: "#fff" } }, button: { marginRight: "15px", }, input_box: { marginRight: "15px", marginBottom: "15px" }, headline: { marginBottom: "15px", fontSize: "20px", }, col_s: { paddingLeft: "15px", }, list_box: { backgroundColor: theme.palette.background.paper, }, align_fomr: { paddingTop: "5px", paddingBottom: "5px", } } class ShowMenu extends Component { componentDidMount() { const { dispatch } = this.props; dispatch(dish.loadDishes()); dispatch(dishcat.getDishCat()); } constructor(props) { super(props); this.state = { monMenu: [], tueMenu: [], wedMenu: [], thuMenu: [], firMenu: [], satMenu: [], sunMenu: [], } this.updateData = this.updateData.bind(this); this.saveMenu = this.saveMenu.bind(this); this.loadMenu = this.loadMenu.bind(this); this.resetMenu = this.resetMenu.bind(this); } // AddMenuのから更新 updateData(data, day) { let target = ""; if (day === "月") { target = "monMenu"; } else if (day === "火") { target = "tueMenu"; } else if (day === "水") { target = "wedMenu"; } else if (day === "木") { target = "thuMenu"; } else if (day === "金") { target = "firMenu"; } else if (day === "土") { target = "satMenu"; } else if (day === "日") { target = "sunMenu"; } this.setState({ [target]: data }) } // テーブル内のコンテンツの設定 setTable() { let result = []; let rows = [ this.createData('月', this.state.monMenu), this.createData('火', this.state.tueMenu), this.createData('水', this.state.wedMenu), this.createData('木', this.state.thuMenu), this.createData('金', this.state.firMenu), this.createData('土', this.state.satMenu), this.createData('日', this.state.sunMenu), ]; rows.map(row => ( result.push( <TableRow key={row.day.toString()}> <TableCell padding="checkbox" className={this.props.classes.col_s}>{row.day}</TableCell> <TableCell padding="checkbox"> <AddMenu menuData={row.menuData} day={row.day} updateData={this.updateData} /> </TableCell> <TableCell className={this.props.classes.col_s}>{row.result}</TableCell> </TableRow> ))) return result; } // setTableから曜日と曜日ごとの料理情報を受け取って整形 createData(day, menu) { let result = []; let menuData = []; let newData = []; menuData = menu.slice(); newData = menu.slice(); if (newData.length === 0 || newData === "") { result.push("登録がありません"); } else { for (let i = 0; i < newData.length; i++) { for (let key in newData[i]) { result.push(<p key={newData[i][key] + i}>{newData[i][key]}</p>); } } } // resulet:表示されるテキスト menuData:更新用のデータ return { day, result, menuData }; } loadMenu() { this.setState({ monMenu: this.props.mon, tueMenu: this.props.tue, wedMenu: this.props.wed, thuMenu: this.props.thu, firMenu: this.props.fri, satMenu: this.props.sat, sunMenu: this.props.sun, }) } saveMenu() { let data = {}; data = { monday: this.state.monMenu, tuesday: this.state.tueMenu, wednesday: this.state.wedMenu, thursday: this.state.thuMenu, friday: this.state.firMenu, saturday: this.state.satMenu, sunday: this.state.sunMenu, } const { dispatch } = this.props; dispatch(menus.addMenu(data)); alert("献立を保存しました") } resetMenu() { this.setState({ monMenu: [], tueMenu: [], wedMenu: [], thuMenu: [], firMenu: [], satMenu: [], sunMenu: [], }) } render() { return ( <> <Typography className={this.props.classes.headline}>献立登録</Typography> <div className={this.props.classes.input_box}> <Box display="flex" component="section" alignItems="center" flexWrap="wrap" alignContent="flex-start"> <Box className={this.props.classes.align_fomr}> <Button onClick={this.loadMenu} className={this.props.classes.button} size="large" variant="outlined" color="secondary">保存済の献立</Button> </Box> <Box className={this.props.classes.align_fomr}> <Button onClick={this.resetMenu} className={this.props.classes.button} size="large" variant="outlined" color="secondary">リセット</Button> </Box> <Box className={this.props.classes.align_fomr}> <Button onClick={this.saveMenu} size="large" variant="outlined" className={this.props.classes.button_accent}>保存</Button> </Box> </Box> </div> <TableContainer component={Paper}> <Table> <TableBody> {this.setTable()} </TableBody> </Table> </TableContainer> </> ); } } export default withStyles(style)( connect((state => state))(ShowMenu) );
'use strict'; angular.module('fenixApp') .controller('BandejaCtrl', function ($scope, $log) { $scope.navbarBrand = { text: 'Fenix-navigation', state: 'incidents' }; $scope.showDate = function () { $scope.date = 0; $scope.date = Date.now(); return $scope.date; }; $scope.tab = 1; $scope.selectTab = function(tab){ this.tab = tab; }; angular.forEach($scope.awesomeThings, function(awesomeThing) { awesomeThing.rank = Math.random(); }); $scope.bandeja = { incidents: [{ id: 1, agency: "policial", type: "Robo", priorida: "alta", address: "Lorem Ipsun", date: "2:30pm" }, { id: 2, agency: "bomberil", type: "Incendio", priorida: "alta", address: "Lorem Ipsun", date: "2:30pm" }, { id: 3, agency: "salud", type: "Herido", priorida: "media", address: "Lorem Ipsun", date: "2:30pm" }, { id: 4, agency: "transito", type: "Accidente de Transito", priorida: "baja", address: "Lorem Ipsun", date: "2:30pm" }] } });
import React from 'react'; import { connect } from 'react-redux'; import { hasAllRequiredProperties } from './../shared/requiredPropertyUtil'; const mapStateToProps = (state) => { return { microservices: state.microservices, hiddenMicroServices: state.hiddenMicroServices }; }; export class MicroserviceCountLabel extends React.Component { render() { const externalCount = this.props.microservices.filter((microservice) => microservice.external).length; const internalCount = this.props.microservices.length - externalCount; const internalLabel = (internalCount === 1 ? "microservice" : "microservices"); const servicesMissingReqPropsCount = this.props.microservices.filter((microservice) => !hasAllRequiredProperties(microservice, this.props.serviceRequiredProperties)).length; const servicesMissingReqPropsLabel = (servicesMissingReqPropsCount === 1 ? "service" : "services") + " missing req. props"; const hiddenServicesLabel = this.props.hiddenMicroServices.length > 0 ? " | " + this.props.hiddenMicroServices.length + " services hidden" : ""; return ( <span style={{ color: "rgba(0, 0, 0, 0.4)", zIndex: 999, position: 'absolute', left: '0.5em', bottom: '0.5em' }}> {internalCount} {internalLabel} <span style={{ color: "#19c786" }}>&#x0272A;</span> | {externalCount} external <span style={{ color: "#f69805" }}>&#x0272A;</span> {servicesMissingReqPropsCount > 0 && <span> | <span style={{ textShadow: "0 0 4px #e50f03" }}>{servicesMissingReqPropsCount} {servicesMissingReqPropsLabel}</span></span>} {hiddenServicesLabel} </span> ); } } export default connect(mapStateToProps)(MicroserviceCountLabel);
# -*- coding: utf-8 -*- import numpy as np class LinearRegression(object): def __init__(self, lr): np.random.seed(1) # 调试阶段请勿删去该条语句 self.k = np.random.normal(0, 0.01) self.b = 0 self.lr = lr # 学习率(learning rate) # 利用数组记录训练过程中的有价值数据 self.trainloss = [] self.testloss = [] self.snapshot = [] def predict(self, X): # 任务1 # 该方法返回模型的预测值 return self.k * X + self.b def get_loss(self, X, y): # 任务2 # 先调用 predict 方法计算模型的预测值 # 再计算均方误差 return np.mean((self.predict(X) - y)**2) / 2 # L = 0 # for i in range(len(y)): # err = (self.predict(X[i]) - y[i]) ** 2 # L += err # return L/2/len(y) def get_grad(self, X, y): # pass # 任务3 # 计算 k 和 b 的梯度 dk, db # return dk, db dk = np.mean((self.predict(X) - y) * X) db = np.mean((self.predict(X) - y)) return dk, db def check_grad(self, X, y): eps = 1e-4 dk, db = self.get_grad(X, y) Jk_p = (((self.k + eps) * X + self.b - y) ** 2).mean() / 2 Jk_n = (((self.k - eps) * X + self.b - y) ** 2).mean() / 2 dk_ = (Jk_p - Jk_n) / 2 / eps Jb_p = ((self.k * X + self.b + eps - y) ** 2).mean() / 2 Jb_n = ((self.k * X + self.b - eps - y) ** 2).mean() / 2 db_ = (Jb_p - Jb_n) / 2 / eps return np.sqrt((dk - dk_)**2 + (db - db_)**2) def update(self, X, y): # 任务4 # 先调用 get_grad 方法计算 k 和 b 的梯度 # 然后用梯度下降算法更新 k 和 b # pass dk, db = self.get_grad(X, y) self.k = self.k - self.lr * dk self.b = self.b - self.lr * db # 以下语句记录训练过程中的 trainloss 和模型参数的 “快照” loss = self.get_loss(X, y) self.trainloss.append(loss) self.snapshot.append((self.k, self.b)) def evaluate(self, X, y): # 建立时刻测试(评估)模型的习惯很重要。 # 记住:我们训练模型的目的是让模型在测试数据上在某种指标衡量下最优, # 因此记录模型训练过程中的训练误差、测试误差等数据有助于我们诊断和调试模型。 loss = self.get_loss(X, y) self.testloss.append(loss)
#!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shop_app.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main()
export { default } from './WalletHomeCollectible'
/*! * phone-codes/phone-nl.min.js * https://github.com/GlauberF/inputmask * Copyright (c) 2010 - 2018 Robin Herbots * Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php) * Version: 4.0.1-beta.12 */ !function(c){"function"==typeof define&&define.amd?define(["../inputmask"],c):"object"==typeof exports?module.exports=c(require("../inputmask")):c(window.Inputmask)}(function(c){return c.extendAliases({phonenl:{alias:"abstractphone",countrycode:"31",phoneCodes:[{mask:"+31-10-###-####",cc:"NL",cd:"Netherlands",city:"Rotterdam"},{mask:"+31-111-###-###",cc:"NL",cd:"Netherlands",city:"Zierikzee"},{mask:"+31-113-###-###",cc:"NL",cd:"Netherlands",city:"Goes"},{mask:"+31-114-###-###",cc:"NL",cd:"Netherlands",city:"Hulst"},{mask:"+31-115-###-###",cc:"NL",cd:"Netherlands",city:"Terneuzen"},{mask:"+31-117-###-###",cc:"NL",cd:"Netherlands",city:"Oostburg"},{mask:"+31-118-###-###",cc:"NL",cd:"Netherlands",city:"Middelburg"},{mask:"+31-13-###-####",cc:"NL",cd:"Netherlands",city:"Tilburg"},{mask:"+31-14-###-####",cc:"NL",cd:"Netherlands",city:"Intern gebruik door KPN"},{mask:"+31-15-###-####",cc:"NL",cd:"Netherlands",city:"Delft"},{mask:"+31-161-###-###",cc:"NL",cd:"Netherlands",city:"Rijen"},{mask:"+31-162-###-###",cc:"NL",cd:"Netherlands",city:"Oosterhout"},{mask:"+31-164-###-###",cc:"NL",cd:"Netherlands",city:"Bergen op Zoom"},{mask:"+31-165-###-###",cc:"NL",cd:"Netherlands",city:"Roosendaal"},{mask:"+31-166-###-###",cc:"NL",cd:"Netherlands",city:"Tholen"},{mask:"+31-167-###-###",cc:"NL",cd:"Netherlands",city:"Steenbergen"},{mask:"+31-168-###-###",cc:"NL",cd:"Netherlands",city:"Zevenbergen"},{mask:"+31-172-###-###",cc:"NL",cd:"Netherlands",city:"Alphen aan den Rijn"},{mask:"+31-174-###-###",cc:"NL",cd:"Netherlands",city:"Naaldwijk"},{mask:"+31-180-###-###",cc:"NL",cd:"Netherlands",city:"Krimpen aan den IJsel"},{mask:"+31-181-###-###",cc:"NL",cd:"Netherlands",city:"Spijkenisse"},{mask:"+31-182-###-###",cc:"NL",cd:"Netherlands",city:"Gouda"},{mask:"+31-183-###-###",cc:"NL",cd:"Netherlands",city:"Gorinchem"},{mask:"+31-184-###-###",cc:"NL",cd:"Netherlands",city:"Sliedrecht"},{mask:"+31-186-###-###",cc:"NL",cd:"Netherlands",city:"Oud-Beijerland"},{mask:"+31-187-###-###",cc:"NL",cd:"Netherlands",city:"Middelharnis"},{mask:"+31-20-###-####",cc:"NL",cd:"Netherlands",city:"Amsterdam"},{mask:"+31-222-###-###",cc:"NL",cd:"Netherlands",city:"Den Burg"},{mask:"+31-223-###-###",cc:"NL",cd:"Netherlands",city:"Den Helder"},{mask:"+31-224-###-###",cc:"NL",cd:"Netherlands",city:"Schagen"},{mask:"+31-226-###-###",cc:"NL",cd:"Netherlands",city:"Noord-Scharwoude"},{mask:"+31-227-###-###",cc:"NL",cd:"Netherlands",city:"Middenmeer"},{mask:"+31-228-###-###",cc:"NL",cd:"Netherlands",city:"Enkhuizen"},{mask:"+31-229-###-###",cc:"NL",cd:"Netherlands",city:"Hoorn"},{mask:"+31-23-###-####",cc:"NL",cd:"Netherlands",city:"Haarlem"},{mask:"+31-24-###-####",cc:"NL",cd:"Netherlands",city:"Nijmegen"},{mask:"+31-251-###-###",cc:"NL",cd:"Netherlands",city:"Beverwijk"},{mask:"+31-252-###-###",cc:"NL",cd:"Netherlands",city:"Hillegom"},{mask:"+31-255-###-###",cc:"NL",cd:"Netherlands",city:"IJmuiden"},{mask:"+31-26-###-####",cc:"NL",cd:"Netherlands",city:"Arnhem"},{mask:"+31-294-###-###",cc:"NL",cd:"Netherlands",city:"Weesp"},{mask:"+31-297-###-###",cc:"NL",cd:"Netherlands",city:"Uithoorn"},{mask:"+31-299-###-###",cc:"NL",cd:"Netherlands",city:"Purmerend"},{mask:"+31-30-###-####",cc:"NL",cd:"Netherlands",city:"Utrecht"},{mask:"+31-313-###-###",cc:"NL",cd:"Netherlands",city:"Dieren"},{mask:"+31-314-###-###",cc:"NL",cd:"Netherlands",city:"Doetinchem"},{mask:"+31-315-###-###",cc:"NL",cd:"Netherlands",city:"Terborg"},{mask:"+31-316-###-###",cc:"NL",cd:"Netherlands",city:"Zevenaar"},{mask:"+31-317-###-###",cc:"NL",cd:"Netherlands",city:"Wageningen"},{mask:"+31-318-###-###",cc:"NL",cd:"Netherlands",city:"Ede"},{mask:"+31-320-###-###",cc:"NL",cd:"Netherlands",city:"Lelystad"},{mask:"+31-321-###-###",cc:"NL",cd:"Netherlands",city:"Dronten"},{mask:"+31-33-###-####",cc:"NL",cd:"Netherlands",city:"Amersfoort"},{mask:"+31-341-###-###",cc:"NL",cd:"Netherlands",city:"Harderwijk"},{mask:"+31-342-###-###",cc:"NL",cd:"Netherlands",city:"Barneveld"},{mask:"+31-343-###-###",cc:"NL",cd:"Netherlands",city:"Doorn"},{mask:"+31-344-###-###",cc:"NL",cd:"Netherlands",city:"Tiel"},{mask:"+31-294-###-###",cc:"NL",cd:"Netherlands",city:"Weesp"},{mask:"+31-297-###-###",cc:"NL",cd:"Netherlands",city:"Uithoorn"},{mask:"+31-299-###-###",cc:"NL",cd:"Netherlands",city:"Purmerend"},{mask:"+31-30-###-####",cc:"NL",cd:"Netherlands",city:"Utrecht"},{mask:"+31-313-###-###",cc:"NL",cd:"Netherlands",city:"Dieren"},{mask:"+31-314-###-###",cc:"NL",cd:"Netherlands",city:"Doetinchem"},{mask:"+31-315-###-###",cc:"NL",cd:"Netherlands",city:"Terborg"},{mask:"+31-316-###-###",cc:"NL",cd:"Netherlands",city:"Zevenaar"},{mask:"+31-317-###-###",cc:"NL",cd:"Netherlands",city:"Wageningen"},{mask:"+31-318-###-###",cc:"NL",cd:"Netherlands",city:"Ede"},{mask:"+31-320-###-###",cc:"NL",cd:"Netherlands",city:"Lelystad"},{mask:"+31-321-###-###",cc:"NL",cd:"Netherlands",city:"Dronten"},{mask:"+31-33-###-####",cc:"NL",cd:"Netherlands",city:"Amersfoort"},{mask:"+31-341-###-###",cc:"NL",cd:"Netherlands",city:"Harderwijk"},{mask:"+31-342-###-###",cc:"NL",cd:"Netherlands",city:"Barneveld"},{mask:"+31-343-###-###",cc:"NL",cd:"Netherlands",city:"Doorn"},{mask:"+31-344-###-###",cc:"NL",cd:"Netherlands",city:"Tiel"},{mask:"+31-345-###-###",cc:"NL",cd:"Netherlands",city:"Culemborg"},{mask:"+31-346-###-###",cc:"NL",cd:"Netherlands",city:"Maarssen"},{mask:"+31-347-###-###",cc:"NL",cd:"Netherlands",city:"Vianen"},{mask:"+31-348-###-###",cc:"NL",cd:"Netherlands",city:"Woerden"},{mask:"+31-35-###-####",cc:"NL",cd:"Netherlands",city:"Hilversum"},{mask:"+31-36-###-####",cc:"NL",cd:"Netherlands",city:"Almere"},{mask:"+31-38-###-####",cc:"NL",cd:"Netherlands",city:"Zwolle"},{mask:"+31-40-###-####",cc:"NL",cd:"Netherlands",city:"Eindhoven"},{mask:"+31-411-###-###",cc:"NL",cd:"Netherlands",city:"Boxtel"},{mask:"+31-412-###-###",cc:"NL",cd:"Netherlands",city:"Oss"},{mask:"+31-413-###-###",cc:"NL",cd:"Netherlands",city:"Veghel"},{mask:"+31-416-###-###",cc:"NL",cd:"Netherlands",city:"Waalwijk"},{mask:"+31-418-###-###",cc:"NL",cd:"Netherlands",city:"Zaltbommel"},{mask:"+31-43-###-####",cc:"NL",cd:"Netherlands",city:"Maastricht"},{mask:"+31-45-###-####",cc:"NL",cd:"Netherlands",city:"Heerlen"},{mask:"+31-46-###-####",cc:"NL",cd:"Netherlands",city:"Sittard"},{mask:"+31-475-###-###",cc:"NL",cd:"Netherlands",city:"Roermond"},{mask:"+31-478-###-###",cc:"NL",cd:"Netherlands",city:"Venray"},{mask:"+31-481-###-###",cc:"NL",cd:"Netherlands",city:"Bemmel"},{mask:"+31-485-###-###",cc:"NL",cd:"Netherlands",city:"Cuijk"},{mask:"+31-486-###-###",cc:"NL",cd:"Netherlands",city:"Grave"},{mask:"+31-487-###-###",cc:"NL",cd:"Netherlands",city:"Druten"},{mask:"+31-488-###-###",cc:"NL",cd:"Netherlands",city:"Zetten"},{mask:"+31-492-###-###",cc:"NL",cd:"Netherlands",city:"Helmond"},{mask:"+31-493-###-###",cc:"NL",cd:"Netherlands",city:"Deurne"},{mask:"+31-495-###-###",cc:"NL",cd:"Netherlands",city:"Weert"},{mask:"+31-497-###-###",cc:"NL",cd:"Netherlands",city:"Eersel"},{mask:"+31-499-###-###",cc:"NL",cd:"Netherlands",city:"Best"},{mask:"+31-50-###-####",cc:"NL",cd:"Netherlands",city:"Groningen"},{mask:"+31-511-###-###",cc:"NL",cd:"Netherlands",city:"Feanw�lden"},{mask:"+31-512-###-###",cc:"NL",cd:"Netherlands",city:"Drachten"},{mask:"+31-513-###-###",cc:"NL",cd:"Netherlands",city:"Heerenveen"},{mask:"+31-514-###-###",cc:"NL",cd:"Netherlands",city:"Balk"},{mask:"+31-515-###-###",cc:"NL",cd:"Netherlands",city:"Sneek"},{mask:"+31-516-###-###",cc:"NL",cd:"Netherlands",city:"Oosterwolde"},{mask:"+31-517-###-###",cc:"NL",cd:"Netherlands",city:"Franeker"},{mask:"+31-518-###-###",cc:"NL",cd:"Netherlands",city:"St Annaparochie"},{mask:"+31-519-###-###",cc:"NL",cd:"Netherlands",city:"Dokkum"},{mask:"+31-521-###-###",cc:"NL",cd:"Netherlands",city:"Steenwijk"},{mask:"+31-522-###-###",cc:"NL",cd:"Netherlands",city:"Meppel"},{mask:"+31-523-###-###",cc:"NL",cd:"Netherlands",city:"Dedemsvaart"},{mask:"+31-524-###-###",cc:"NL",cd:"Netherlands",city:"Coevorden"},{mask:"+31-525-###-###",cc:"NL",cd:"Netherlands",city:"Elburg"},{mask:"+31-527-###-###",cc:"NL",cd:"Netherlands",city:"Emmeloord"},{mask:"+31-528-###-###",cc:"NL",cd:"Netherlands",city:"Hoogeveen"},{mask:"+31-529-###-###",cc:"NL",cd:"Netherlands",city:"Ommen"},{mask:"+31-53-###-####",cc:"NL",cd:"Netherlands",city:"Enschede"},{mask:"+31-541-###-###",cc:"NL",cd:"Netherlands",city:"Oldenzaal"},{mask:"+31-543-###-###",cc:"NL",cd:"Netherlands",city:"Winterswijk"},{mask:"+31-544-###-###",cc:"NL",cd:"Netherlands",city:"Groenlo"},{mask:"+31-545-###-###",cc:"NL",cd:"Netherlands",city:"Neede"},{mask:"+31-546-###-###",cc:"NL",cd:"Netherlands",city:"Almelo"},{mask:"+31-547-###-###",cc:"NL",cd:"Netherlands",city:"Goor"},{mask:"+31-548-###-###",cc:"NL",cd:"Netherlands",city:"Rijssen"},{mask:"+31-55-###-####",cc:"NL",cd:"Netherlands",city:"Apeldoorn"},{mask:"+31-561-###-###",cc:"NL",cd:"Netherlands",city:"Wolvega"},{mask:"+31-562-###-###",cc:"NL",cd:"Netherlands",city:"West-Terschelling"},{mask:"+31-566-###-###",cc:"NL",cd:"Netherlands",city:"Jirnsum"},{mask:"+31-570-###-###",cc:"NL",cd:"Netherlands",city:"Deventer"},{mask:"+31-571-###-###",cc:"NL",cd:"Netherlands",city:"Twello"},{mask:"+31-572-###-###",cc:"NL",cd:"Netherlands",city:"Raalte"},{mask:"+31-573-###-###",cc:"NL",cd:"Netherlands",city:"Lochem"},{mask:"+31-575-###-###",cc:"NL",cd:"Netherlands",city:"Zutphen"},{mask:"+31-577-###-###",cc:"NL",cd:"Netherlands",city:"Uddel"},{mask:"+31-578-###-###",cc:"NL",cd:"Netherlands",city:"Epe"},{mask:"+31-58-###-####",cc:"NL",cd:"Netherlands",city:"Leeuwarden"},{mask:"+31-591-###-###",cc:"NL",cd:"Netherlands",city:"Emmen"},{mask:"+31-592-###-###",cc:"NL",cd:"Netherlands",city:"Assen"},{mask:"+31-593-###-###",cc:"NL",cd:"Netherlands",city:"Beilen"},{mask:"+31-594-###-###",cc:"NL",cd:"Netherlands",city:"Zuidhorn"},{mask:"+31-595-###-###",cc:"NL",cd:"Netherlands",city:"Warffum"},{mask:"+31-596-###-###",cc:"NL",cd:"Netherlands",city:"Appingedam"},{mask:"+31-597-###-###",cc:"NL",cd:"Netherlands",city:"Winschoten"},{mask:"+31-598-###-###",cc:"NL",cd:"Netherlands",city:"Hoogezand"},{mask:"+31-599-###-###",cc:"NL",cd:"Netherlands",city:"Stadskanaal"},{mask:"+31-70-###-####",cc:"NL",cd:"Netherlands",city:"Den Haag"},{mask:"+31-71-###-####",cc:"NL",cd:"Netherlands",city:"Leiden"},{mask:"+31-72-###-####",cc:"NL",cd:"Netherlands",city:"Alkmaar"},{mask:"+31-73-###-####",cc:"NL",cd:"Netherlands",city:"'s-Hertogenbosch"},{mask:"+31-74-###-####",cc:"NL",cd:"Netherlands",city:"Hengelo"},{mask:"+31-75-###-####",cc:"NL",cd:"Netherlands",city:"Zaandam"},{mask:"+31-76-###-####",cc:"NL",cd:"Netherlands",city:"Breda"},{mask:"+31-77-###-####",cc:"NL",cd:"Netherlands",city:"Venlo"},{mask:"+31-78-###-####",cc:"NL",cd:"Netherlands",city:"Dordrecht"},{mask:"+31-79-###-####",cc:"NL",cd:"Netherlands",city:"Zoetermeer"},{mask:"+31-61-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-62-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-63-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-64-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-65-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-68-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-69-###-####",cc:"NL",cd:"Netherlands",city:"Mobiele nummers"},{mask:"+31-66-###-####",cc:"NL",cd:"Netherlands",city:"Semafonie"},{mask:"+31-670-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-671-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-672-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-673-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-674-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-675-###-###",cc:"NL",cd:"Netherlands",city:"Videotex"},{mask:"+31-676-###-###",cc:"NL",cd:"Netherlands",city:"Inbelnummers van internetproviders"},{mask:"+31-800-###-###",cc:"NL",cd:"Netherlands",city:"Gratis informatienummers"},{mask:"+31-82-###-####",cc:"NL",cd:"Netherlands",city:"Virtual Private Network"},{mask:"+31-88-###-####",cc:"NL",cd:"Netherlands",city:"Bedrijfsnummers"},{mask:"+31-900-###-###",cc:"NL",cd:"Netherlands",city:"Betaalde informatienummers"},{mask:"+31-906-###-###",cc:"NL",cd:"Netherlands",city:"Betaalde informatienummers"},{mask:"+31-909-###-###",cc:"NL",cd:"Netherlands",city:"Betaalde informatienummers"},{mask:"+31-91-###-####",cc:"NL",cd:"Netherlands",city:"Plaatsonafhankelijk netnummer, geschikt voor beeldtelefonie of lijnen met verhoogde kwaliteit"}]}}),c});
var Account = require('ethereumjs-account'); var Block = require('ethereumjs-block'); var VM = require('ethereumjs-vm'); var RuntimeError = require('./utils/runtimeerror'); var Trie = require('merkle-patricia-tree'); var FakeTransaction = require('ethereumjs-tx/fake.js'); var utils = require('ethereumjs-util'); var seedrandom = require('seedrandom'); var bip39 = require('bip39'); var wallet = require('ethereumjs-wallet'); var hdkey = require('ethereumjs-wallet/hdkey'); var async = require("async"); var BlockchainDouble = require("./blockchain_double.js"); var ForkedBlockchain = require("./utils/forkedblockchain.js"); var Web3 = require('web3'); var util = require("util"); var _ = require("lodash"); var to = require('./utils/to'); var random = require('./utils/random'); var txhelper = require('./utils/txhelper'); var TXRejectedError = require('./utils/txrejectederror'); StateManager = function(options, provider) { var self = this; this.options = options = this._applyDefaultOptions(options || {}) if (options.fork) { this.blockchain = new ForkedBlockchain(options); } else { this.blockchain = new BlockchainDouble(options); } this.vm = this.blockchain.vm; this.stateTrie = this.blockchain.stateTrie; this.accounts = {}; this.secure = !!options.secure; this.account_passwords = {} this.personal_accounts = {} this.total_accounts = options.total_accounts; this.coinbase = null; this.latest_filter_id = 1; // This queue manages actions that shouldn't be run in parallel. // The action_processing flag ensures new actions are queued instead of // run immediately. this.action_queue = []; this.action_processing == false; this.snapshots = []; this.logger = options.logger; this.net_version = options.network_id; this.mnemonic = options.mnemonic; this.wallet = hdkey.fromMasterSeed(bip39.mnemonicToSeed(this.mnemonic)); this.wallet_hdpath = options.hdPath; this.gasPriceVal = to.hex(options.gasPrice); this.is_mining = true; this.blocktime = options.blocktime; this.is_mining_on_interval = !!options.blocktime; this.mining_interval_timeout = null; this._provider = provider; } const defaultOptions = { total_accounts: 10, gasPrice: '0x4A817C800', default_balance_ether: 100, unlocked_accounts: [], hdPath: "m/44'/60'/0'/0/" } StateManager.prototype._applyDefaultOptions = function(options) { // do this so that we can use the same seed on our next run and get the same // results without explicitly setting a seed up front if (!options.seed) { options.seed = random.randomAlphaNumericString(10, seedrandom()) } // generate a randomized default mnemonic if (!options.mnemonic) { let randomBytes = random.randomBytes(16, seedrandom(options.seed)) options.mnemonic = bip39.entropyToMnemonic(randomBytes.toString("hex")) } if (!options.fork && !options.network_id) { options.network_id = (new Date()).getTime(); } // We want this function to mutate the options object so that we can report // our settings back to our consumer application (e.g., ganache) return _.merge(options, defaultOptions, Object.assign({}, options)); } StateManager.prototype.initialize = function(callback) { var self = this; var accounts = []; let defaultBalanceWei = to.hex(Web3.utils.toWei(self.options.default_balance_ether.toString(), 'ether')); if (self.options.accounts) { accounts = self.options.accounts.map(self.createAccount.bind(self)); } else { if (!self.total_accounts) { return callback(new Error('Cannot initialize chain: either options.accounts or options.total_accounts must be specified')) } for (var i = 0; i < self.total_accounts; i++) { accounts.push(self.createAccount({ index: i, balance: defaultBalanceWei })); } } self.coinbase = to.hex(accounts[0].address); self.accounts = {}; accounts.forEach(function(data) { self.accounts[data.address] = data; self.personal_accounts[data.address.toLowerCase()] = true; }); // Turn array into object, mostly for speed purposes. // No need for caller to specify private keys. self.unlocked_accounts = self.options.unlocked_accounts.reduce(function(obj, address) { // If it doesn't have a hex prefix, must be a number (either a string or number type). if ((address + "").indexOf("0x") != 0) { let idx = parseInt(address) let account = accounts[idx] if (!account) { throw new Error(`Account at index ${idx} not found. Max index available is ${accounts.length - 1}.`) } address = account.address.toLowerCase(); } obj[address.toLowerCase()] = true; // can be any value return obj; }, {}); if (!self.secure) { accounts.forEach(function(data) { self.unlocked_accounts[data.address.toLowerCase()] = data; }); } self.blockchain.initialize(accounts, function(err) { if (err) return callback(err); // If the user didn't pass a specific version id in, then use the // forked blockchain's version (if it exists) or create our own. if (!self.net_version) { self.net_version = self.blockchain.fork_version } if (self.is_mining_on_interval) { self.mineOnInterval(); } callback(); }); }; StateManager.prototype.mineOnInterval = function() { var self = this; // For good measure. clearTimeout(self.mining_interval_timeout); self.mining_interval_timeout = null; self.mining_interval_timeout = setTimeout(function() { self._provider.send({ method: 'evm_mine' }, self.mineOnInterval.bind(self) ); }, this.blocktime * 1000); // Ensure this won't keep a node process open. if (this.mining_interval_timeout.unref) { this.mining_interval_timeout.unref(); } }; StateManager.prototype.createAccount = function(opts, i) { var secretKey; var balance; if (opts.generate) { secretKey = wallet.generate().getPrivateKey(); } else if (opts.secretKey) { secretKey = utils.toBuffer(to.hex(opts.secretKey)); } else { var index = (typeof(opts.index) === 'undefined') ? i : opts.index; var acct = this.wallet.derivePath(this.wallet_hdpath + index) // index is a number secretKey = acct.getWallet().getPrivateKey() // Buffer } var publicKey = utils.privateToPublic(secretKey); var address = utils.publicToAddress(publicKey); var account = new Account(); account.balance = to.hex(opts.balance) var data = { secretKey: secretKey, publicKey: publicKey, address: to.hex(address).toLowerCase(), account: account }; return data; }; StateManager.prototype.blockNumber = function(callback) { return this.blockchain.getHeight(callback); }; StateManager.prototype.gasPrice = function() { return this.gasPriceVal; } StateManager.prototype.getBalance = function(address, number, callback) { this.blockchain.getBalance(address, number, function(err, balance) { if (balance) { balance = to.rpcQuantityHexString(balance); } callback(err, balance); }); } StateManager.prototype.getTransactionCount = function(address, number, callback) { this.blockchain.getNonce(address, number, function(err, nonce) { if (nonce) { nonce = to.rpcQuantityHexString(nonce); } callback(err, nonce); }); } StateManager.prototype.getCode = function(address, number, callback) { this.blockchain.getCode(address, number, function(err, code) { if (code) { code = to.hex(code); } callback(err, code); }); } StateManager.prototype.queueRawTransaction = function(rawTx, callback) { var data = new Buffer(utils.stripHexPrefix(rawTx), 'hex'); var tx = new FakeTransaction(data); var txParams = { from: tx.from.toString('hex'), to: tx.to.toString('hex'), gas: tx.gasLimit.toString('hex'), gasPrice: tx.gasPrice.toString('hex'), value: tx.value.toString('hex'), data: tx.data.toString('hex'), nonce: tx.nonce.toString('hex'), } if (tx.v && tx.v.length > 0 && tx.r && tx.r.length > 0 && tx.s && tx.s.length > 0) { txParams.v = tx.v.toString('hex'); txParams.r = tx.r.toString('hex'); txParams.s = tx.s.toString('hex'); } this.queueTransaction("eth_sendRawTransaction", txParams, null, callback); }; StateManager.prototype.queueStorage = function(address, position, block, callback) { this.action_queue.push({ method: "eth_getStorageAt", address: utils.addHexPrefix(address), position: utils.addHexPrefix(position), block: block, callback: callback }); // We know there's work, so get started. this.processNextAction(); } StateManager.prototype.queueTransaction = function(method, tx_params, block_number, callback) { if (tx_params.from == null) { callback(new TXRejectedError("from not found; is required")); return; } // use toLowerCase() to properly handle from addresses meant to be validated. tx_params.from = utils.addHexPrefix(tx_params.from).toLowerCase(); if (method == "eth_sendTransaction" && this.accounts[tx_params.from] == null && this.unlocked_accounts[tx_params.from] == null) { return callback(new TXRejectedError("sender account not recognized")); } if (method == "eth_sendTransaction" && this.unlocked_accounts[tx_params.from] == null) { return callback(new TXRejectedError("signer account is locked")); } var rawTx = { gasPrice: "0x1", gasLimit: to.hex(this.blockchain.defaultTransactionGasLimit), value: '0x0', }; if (tx_params.gas != null) { rawTx.gasLimit = utils.addHexPrefix(tx_params.gas); } if (tx_params.gasPrice != null) { rawTx.gasPrice = utils.addHexPrefix(tx_params.gasPrice); } if (tx_params.to != null) { rawTx.to = utils.addHexPrefix(tx_params.to); } if (tx_params.value != null) { rawTx.value = utils.addHexPrefix(tx_params.value); } if (tx_params.data != null) { rawTx.data = utils.addHexPrefix(tx_params.data); } if (tx_params.nonce != null) { rawTx.nonce = utils.addHexPrefix(tx_params.nonce); } if (tx_params.v != null && tx_params.s != null && tx_params.v != null) { rawTx.v = utils.addHexPrefix(tx_params.v); rawTx.r = utils.addHexPrefix(tx_params.r); rawTx.s = utils.addHexPrefix(tx_params.s); } // some tools use a null or empty `to` field when doing contract deployments if (rawTx.to == '0x0' || rawTx.to == '') { delete rawTx.to } // Error checks if (rawTx.to && typeof rawTx.to != "string") { return callback(new TXRejectedError("Invalid to address")); } // If the transaction has a higher gas limit than the block gas limit, error. if (to.number(rawTx.gasLimit) > to.number(this.blockchain.blockGasLimit)) { return callback(new TXRejectedError("Exceeds block gas limit")); } // Get the nonce for this address, taking account any transactions already queued. var self = this; var address = utils.toBuffer(tx_params.from); // we don't call createFakeTransactionWithCorrectNonce here because then we'd need to worry // about nonce calculation for the items pending in the action_queue. // Instead, we simply create a `FakeTransaction` and bail on validation // errors so that we fail fast when we have bad tx input try { let tx = new FakeTransaction(rawTx); tx.from = address; } catch (err) { return callback(err); } self.action_queue.push({ method: method, from: tx_params.from, tx: rawTx, callback: callback, blockNumber: block_number, }); // We know there's work, so get started. self.processNextAction(); }; StateManager.prototype.queueTransactionTrace = function(tx_hash, params, callback) { this.action_queue.push({ method: "debug_traceTransaction", hash: to.hex(tx_hash), params: params, callback: callback }); // We know there's work, so get started. this.processNextAction(); }; StateManager.prototype.processNextAction = function(override) { var self = this; if (override != true) { if (this.action_processing == true || this.action_queue.length == 0) { return; } } var queued = this.action_queue.shift(); // Set the flag that we're currently processing something. this.action_processing = true; var intermediary = function(err, result) { queued.callback(err, result); if (self.action_queue.length > 0) { self.processNextAction(true); } else { self.action_processing = false; } }; if (typeof queued.method == "function") { var result = queued.method(); return intermediary(null, result); } else if (queued.method == "eth_getStorageAt") { this.blockchain.getStorage(queued.address, queued.position, queued.block, function(err, result) { if (err) return intermediary(err); if (result) { result = utils.rlp.decode(result); } result = to.hex(result || 0); intermediary(null, result); }); } else if (queued.method == "debug_traceTransaction") { this.blockchain.processTransactionTrace(queued.hash, queued.params, intermediary); } else if (queued.method == "eth_sendTransaction" || queued.method == "eth_sendRawTransaction") { this.processTransaction(queued.from, queued.tx, intermediary); } else if (queued.method == "eth_call") { this.processCall(queued.from, queued.tx, queued.blockNumber, intermediary); } else if (queued.method == "eth_estimateGas") { this.processGasEstimate(queued.from, queued.tx, queued.blockNumber, intermediary); } }; StateManager.prototype.sign = function(address, dataToSign) { var account = this.accounts[to.hex(address).toLowerCase()]; if (!account) { throw new Error("cannot sign data; no private key"); } var secretKey = account.secretKey; var msg = new Buffer(dataToSign.replace('0x',''), 'hex'); var msgHash = utils.hashPersonalMessage(msg); var sgn = utils.ecsign(msgHash, new Buffer(secretKey)); return utils.toRpcSig(sgn.v, sgn.r, sgn.s); }; StateManager.prototype.printTransactionReceipt = function(tx_hash, error, callback){ var self = this; self.blockchain.getTransactionReceipt(tx_hash, function(err, receipt) { if (err) return callback(err); self.blockchain.latestBlock(function(err, block) { if (err) return callback(err); receipt = receipt.toJSON(); self.logger.log(""); self.logger.log(" Transaction: " + tx_hash); if (receipt.contractAddress != null) { self.logger.log(" Contract created: " + receipt.contractAddress); } self.logger.log(" Gas usage: " + parseInt(receipt.gasUsed, 16)); self.logger.log(" Block Number: " + parseInt(receipt.blockNumber, 16)); self.logger.log(" Block Time: " + new Date(to.number(block.header.timestamp) * 1000).toString()); if (error) { self.logger.log(" Runtime Error: " + error.error); } self.logger.log(""); callback(null, tx_hash); }); }); } StateManager.prototype.processBlocks = function(total_blocks, callback) { var self = this; if (typeof total_blocks == "function") { callback = total_blocks; total_blocks = null; } // Note: VM errors (errors that the VM directly returns) trump all runtime errors. var runtime_error = null; var amount_processed = 0; async.whilst(function() { var shouldContinue; if (total_blocks == null) { shouldContinue = self.blockchain.pending_transactions.length > 0; } else { shouldContinue = amount_processed < total_blocks; } return shouldContinue; }, function(done) { self.blockchain.processNextBlock(function(err, transactions, vm_output) { amount_processed += 1; if (err) { if (err instanceof RuntimeError == false) { // This is bad. Get out. return done(err); } // We must have a RuntimeError. Merge results if we've found // other runtime errors during this execution. if (runtime_error == null) { runtime_error = err; } else { runtime_error.combine(err); } } // Note we don't quit on runtime errors. We keep processing transactions. // Print the transaction receipts then move onto the next one. // TODO: Can we refactor printTransactionReceipt so it's synchronous? // We technically have the raw vm receipts (though they're not full receipts here...). var receipts = vm_output.receipts; async.eachSeries(transactions, function(tx, finished_printing) { var hash = to.hex(tx.hash()); var error = runtime_error == null ? {results: {}} : runtime_error; self.printTransactionReceipt(hash, error.results[hash], finished_printing); }, done); }); }, function(err) { // Remember: vm errors trump runtime errors callback(err || runtime_error); }); }; StateManager.prototype.processCall = function (from, rawTx, blockNumber, callback) { var self = this; self.createFakeTransactionWithCorrectNonce(rawTx, from, function(err, tx) { if (err) return callback(err); self.blockchain.processCall(tx, blockNumber, function (err, results) { if (err) { return callback(err); } var result = '0x0' if (!results.error && results.vm.return) { result = to.hex(results.vm.return); } else if (results.error) { self.logger.log(`Error processing call: ${results.error}`) } return callback(null, result); }); }); }; StateManager.prototype.processGasEstimate = function (from, rawTx, blockNumber, callback) { var self = this; self.createFakeTransactionWithCorrectNonce(rawTx, from, function(err, tx) { if (err) return callback(err); self.blockchain.processCall(tx, blockNumber, function (err, results) { if (err) { return callback(err); } var result = '0x0' if (!results.error) { result = to.hex(results.gasUsed) } else { self.logger.log(`Error calculating gas estimate: ${results.error}`) } return callback(null, result); }); }); } StateManager.prototype.processTransaction = function(from, rawTx, callback) { var self = this; self.createFakeTransactionWithCorrectNonce(rawTx, from, function(err, tx) { if (err) return callback(err); self.blockchain.queueTransaction(tx); var tx_hash = to.hex(tx.hash()); // If we're not currently mining or we're mining on an interval, // only queue the transaction, don't process it. if (self.is_mining == false || self.is_mining_on_interval) { return callback(null, tx_hash); } self.processBlocks(function (err) { if (err) return callback(err); callback(null, tx_hash); }); }); }; StateManager.prototype.getTransactionReceipt = function(hash, callback) { this.blockchain.getTransactionReceipt(hash, function(err, receipt) { if (err && err.notFound) { // Return null if the receipt's not found. return callback(null, null); } callback(err, receipt); }); }; StateManager.prototype.getBlock = function(hash_or_number, callback) { this.blockchain.getBlock(hash_or_number, callback); }; StateManager.prototype.getLogs = function(filter, callback) { var self = this; var expectedAddress = filter.address; var expectedTopics = filter.topics || []; async.parallel({ fromBlock: this.blockchain.getEffectiveBlockNumber.bind(this.blockchain, filter.fromBlock || "latest"), toBlock: this.blockchain.getEffectiveBlockNumber.bind(this.blockchain, filter.toBlock || "latest"), latestBlock: this.blockchain.getEffectiveBlockNumber.bind(this.blockchain, "latest") }, function(err, results) { var fromBlock = results.fromBlock; var toBlock = results.toBlock; var latestBlock = results.latestBlock; if (toBlock > latestBlock) { toBlock = latestBlock; } var logs = []; var current = fromBlock; async.whilst(function() { return current <= toBlock; }, function(finished) { self.blockchain.getBlockLogs(current, function(err, blockLogs) { if (err) return finished(err); // Filter logs that match the address var filtered = blockLogs.filter(function(log) { return (expectedAddress == null || log.address == expectedAddress); }); // Now filter based on topics. filtered = filtered.filter(function(log) { var keep = true; for (var i = 0; i < expectedTopics.length; i++) { var expectedTopic = expectedTopics[i]; var logTopic = log.topics[i]; if (expectedTopic == null) continue; var isMatch = Array.isArray(expectedTopic) ? expectedTopic.includes(logTopic) : expectedTopic === logTopic; if (i >= log.topics.length || !isMatch) { keep = false; break; } } return keep; }); logs.push.apply(logs, filtered); current += 1; finished(); }); }, function(err) { if (err) return callback(err); logs = logs.map(function(log) { return log.toJSON(); }); callback(err, logs); }); }); }; // Note: Snapshots have 1-based ids. StateManager.prototype.snapshot = function(callback) { var self = this; this.blockchain.getHeight(function(err, blockNumber) { if (err) return callback(err); self.snapshots.push({ blockNumber: blockNumber }); self.logger.log("Saved snapshot #" + self.snapshots.length); callback(null, to.hex(self.snapshots.length)); }); }; StateManager.prototype.revert = function(snapshot_id, callback) { var self = this; // Convert from hex. snapshot_id = utils.bufferToInt(snapshot_id); this.logger.log("Reverting to snapshot #" + snapshot_id); if (snapshot_id > this.snapshots.length) { return false; } // Convert to zero based. snapshot_id = snapshot_id - 1; // Loop through each snapshot with a higher id than the current one. async.whilst(function() { return self.snapshots.length > snapshot_id }, function(nextSnapshot) { var snapshot = self.snapshots.pop(); // For each snapshot, asynchronously pop off the blocks it represents. async.during(function(doneWithTest) { self.blockchain.getHeight(function(err, blockNumber) { if (err) return doneWithTest(err); doneWithTest(null, blockNumber > snapshot.blockNumber) }); }, function(nextBlock) { self.blockchain.popBlock(function(err) { if (err) return nextBlock(err); nextBlock(); }); }, nextSnapshot); }, function(err) { if (err) return callback(err); // Pending transactions are removed when you revert. self.blockchain.clearPendingTransactions(); callback(null, true); }); }; StateManager.prototype.hasContractCode = function(address, callback) { this.vm.stateManager.getContractCode( address, function( err, result ) { if( err != null ) { callback( err, false ); } else { callback( null, true ); } }); } StateManager.prototype.startMining = function(callback) { this.is_mining = true; if (this.is_mining_on_interval) { this.mineOnInterval(); callback(); } else { this.processBlocks(callback); } }; StateManager.prototype.stopMining = function(callback) { this.is_mining = false; clearTimeout(this.mining_interval_timeout); this.mining_interval_timeout = null; callback(); }; StateManager.prototype.isUnlocked = function(address) { return this.unlocked_accounts[address.toLowerCase()] != null; }; StateManager.prototype.createFakeTransactionWithCorrectNonce = function(rawTx, from, callback) { const self = this; self.blockchain.getQueuedNonce(from, (err, expectedNonce) => { if (err) return callback(err); var tx = new FakeTransaction(rawTx); tx.from = from; // If the user specified a nonce, use that instead. if (rawTx.nonce == null) { // account for transactions waiting in the tx queue tx.nonce = to.hex(expectedNonce); } else { if (to.number(rawTx.nonce) !== to.number(expectedNonce)) { return callback(new TXRejectedError(`the tx doesn't have the correct nonce. ` + `account has nonce of: ${to.number(expectedNonce)} ` + `tx has nonce of: ${to.number(tx.nonce)}`)) } } // If we're calling a contract, check to make sure the address specified is a contract address if (_transactionIsContractCall(rawTx)) { self.getCode(to.hex(rawTx.to), 'latest', function(err, code) { if (err) { callback(err); } else if (code === '0x0') { callback(new TXRejectedError(`Attempting to run transaction which calls a contract function, but recipient address ${to.hex(rawTx.to)} is not a contract address`)) } else { callback(null, tx) } }); } else { callback(null, tx) } }); } // returns true when transaction has a non-null, non-empty to and data field var _transactionIsContractCall = function(rawTx) { let recipient = to.hex(rawTx.to || '0x0') let data = to.hex(rawTx.data || '0x0') return recipient !== '0x0' && data !== '0x0' } module.exports = StateManager;
(self.webpackChunkpythonbible_docs=self.webpackChunkpythonbible_docs||[]).push([[2611],{4478:function(e,t,n){"use strict";var r=n(2122),a=n(9756),l=n(7294);t.Z=function(e){var t=e.width,n=void 0===t?30:t,o=e.height,c=void 0===o?30:o,i=e.className,s=(0,a.Z)(e,["width","height","className"]);return l.createElement("svg",(0,r.Z)({"aria-label":"Menu",className:i,width:n,height:c,viewBox:"0 0 30 30",role:"img",focusable:"false"},s),l.createElement("title",null,"Menu"),l.createElement("path",{stroke:"currentColor",strokeLinecap:"round",strokeMiterlimit:"10",strokeWidth:"2",d:"M4 7h22M4 15h22M4 23h22"}))}},2611:function(e,t,n){"use strict";n.d(t,{Z:function(){return Ne}});var r=n(7294),a=n(6010),l=n(4973),o=n(5977),c="skipToContent_1oUP";function i(e){e.setAttribute("tabindex","-1"),e.focus(),e.removeAttribute("tabindex")}var s=function(){var e=(0,r.useRef)(null),t=(0,o.TH)();return(0,r.useEffect)((function(){!t.hash&&e.current&&i(e.current)}),[t.pathname]),r.createElement("div",{ref:e},r.createElement("a",{href:"#main",className:c,onClick:function(e){e.preventDefault();var t=document.querySelector("main:first-of-type")||document.querySelector(".main-wrapper");t&&i(t)}},r.createElement(l.Z,{id:"theme.common.skipToMainContent",description:"The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation"},"Skip to main content")))},u=n(6700),m=n(944),d="announcementBar_3WsW",f="announcementBarClose_38nx",v="announcementBarContent_3EUC",h="announcementBarCloseable_3myR";var b=function(){var e,t=(0,m.Z)(),n=t.isAnnouncementBarClosed,o=t.closeAnnouncementBar,c=(0,u.LU)().announcementBar;if(!c)return null;var i=c.content,s=c.backgroundColor,b=c.textColor,g=c.isCloseable;return!i||g&&n?null:r.createElement("div",{className:d,style:{backgroundColor:s,color:b},role:"banner"},r.createElement("div",{className:(0,a.Z)(v,(e={},e[h]=g,e)),dangerouslySetInnerHTML:{__html:i}}),g?r.createElement("button",{type:"button",className:f,onClick:o,"aria-label":(0,l.I)({id:"theme.AnnouncementBar.closeButtonAriaLabel",message:"Close",description:"The ARIA label for close button of announcement bar"})},r.createElement("span",{"aria-hidden":"true"},"\xd7")):null)},g=n(2122),E=function(){return null},p=n(2263),k={toggle:"toggle_71bT"},Z=function(e){var t=e.icon,n=e.style;return r.createElement("span",{className:(0,a.Z)(k.toggle,k.dark),style:n},t)},_=function(e){var t=e.icon,n=e.style;return r.createElement("span",{className:(0,a.Z)(k.toggle,k.light),style:n},t)},y=(0,r.memo)((function(e){var t=e.className,n=e.icons,l=e.checked,o=e.disabled,c=e.onChange,i=(0,r.useState)(l),s=i[0],u=i[1],m=(0,r.useState)(!1),d=m[0],f=m[1],v=(0,r.useRef)(null);return r.createElement("div",{className:(0,a.Z)("react-toggle",t,{"react-toggle--checked":s,"react-toggle--focus":d,"react-toggle--disabled":o}),role:"button",tabIndex:-1,onClick:function(e){var t=v.current;if(t)return e.target!==t?(e.preventDefault(),t.focus(),void t.click()):void u(null==t?void 0:t.checked)}},r.createElement("div",{className:"react-toggle-track"},r.createElement("div",{className:"react-toggle-track-check"},n.checked),r.createElement("div",{className:"react-toggle-track-x"},n.unchecked)),r.createElement("div",{className:"react-toggle-thumb"}),r.createElement("input",{ref:v,checked:s,type:"checkbox",className:"react-toggle-screenreader-only","aria-label":"Switch between dark and light mode",onChange:c,onFocus:function(){return f(!0)},onBlur:function(){return f(!1)}}))}));function N(e){var t=(0,u.LU)().colorMode.switchConfig,n=t.darkIcon,a=t.darkIconStyle,l=t.lightIcon,o=t.lightIconStyle,c=(0,p.default)().isClient;return r.createElement(y,(0,g.Z)({disabled:!c,icons:{checked:r.createElement(Z,{icon:n,style:a}),unchecked:r.createElement(_,{icon:l,style:o})}},e))}var w=n(5350),C=n(7898),L=function(e){var t=(0,o.TH)(),n=(0,r.useState)(e),a=n[0],l=n[1],c=(0,r.useRef)(!1),i=(0,r.useState)(0),s=i[0],u=i[1],m=(0,r.useCallback)((function(e){null!==e&&u(e.getBoundingClientRect().height)}),[]);return(0,C.Z)((function(t,n){var r=t.scrollY,a=n.scrollY;if(e)if(r<s)l(!0);else{if(c.current)return c.current=!1,void l(!1);a&&0===r&&l(!0);var o=document.documentElement.scrollHeight-s,i=window.innerHeight;a&&r>=a?l(!1):r+i<o&&l(!0)}}),[s,c]),(0,r.useEffect)((function(){e&&l(!0)}),[t.pathname]),(0,r.useEffect)((function(){e&&t.hash&&(c.current=!0)}),[t.hash]),{navbarRef:m,isNavbarVisible:a}},I=n(1839),A=n(3783),D=n(9756),T=n(5525),B=function(e){var t=e.width,n=void 0===t?20:t,a=e.height,l=void 0===a?20:a,o=(0,D.Z)(e,["width","height"]);return r.createElement("svg",(0,g.Z)({xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",width:n,height:l},o),r.createElement("path",{fill:"currentColor",d:"M19.753 10.909c-.624-1.707-2.366-2.726-4.661-2.726-.09 0-.176.002-.262.006l-.016-2.063 3.525-.607c.115-.019.133-.119.109-.231-.023-.111-.167-.883-.188-.976-.027-.131-.102-.127-.207-.109-.104.018-3.25.461-3.25.461l-.013-2.078c-.001-.125-.069-.158-.194-.156l-1.025.016c-.105.002-.164.049-.162.148l.033 2.307s-3.061.527-3.144.543c-.084.014-.17.053-.151.143.019.09.19 1.094.208 1.172.018.08.072.129.188.107l2.924-.504.035 2.018c-1.077.281-1.801.824-2.256 1.303-.768.807-1.207 1.887-1.207 2.963 0 1.586.971 2.529 2.328 2.695 3.162.387 5.119-3.06 5.769-4.715 1.097 1.506.256 4.354-2.094 5.98-.043.029-.098.129-.033.207l.619.756c.08.096.206.059.256.023 2.51-1.73 3.661-4.515 2.869-6.683zm-7.386 3.188c-.966-.121-.944-.914-.944-1.453 0-.773.327-1.58.876-2.156a3.21 3.21 0 011.229-.799l.082 4.277a2.773 2.773 0 01-1.243.131zm2.427-.553l.046-4.109c.084-.004.166-.01.252-.01.773 0 1.494.145 1.885.361.391.217-1.023 2.713-2.183 3.758zm-8.95-7.668a.196.196 0 00-.196-.145h-1.95a.194.194 0 00-.194.144L.008 16.916c-.017.051-.011.076.062.076h1.733c.075 0 .099-.023.114-.072l1.008-3.318h3.496l1.008 3.318c.016.049.039.072.113.072h1.734c.072 0 .078-.025.062-.076-.014-.05-3.083-9.741-3.494-11.04zm-2.618 6.318l1.447-5.25 1.447 5.25H3.226z"}))};function S(e){var t=e.mobile,n=e.dropdownItemsBefore,a=e.dropdownItemsAfter,l=(0,D.Z)(e,["mobile","dropdownItemsBefore","dropdownItemsAfter"]),o=(0,p.default)().i18n,c=o.currentLocale,i=o.locales,s=o.localeConfigs,m=(0,u.l5)();function d(e){return s[e].label}var f=i.map((function(e){var t="pathname://"+m.createUrl({locale:e,fullyQualified:!1});return{isNavLink:!0,label:d(e),to:t,target:"_self",autoAddBaseUrl:!1,className:e===c?"dropdown__link--active":"",style:{textTransform:"capitalize"}}})),v=[].concat(n,f,a),h=t?"Languages":d(c);return r.createElement(T.Z,(0,g.Z)({},l,{href:"#",mobile:t,label:r.createElement("span",null,r.createElement(B,{style:{verticalAlign:"text-bottom",marginRight:5}}),r.createElement("span",null,h)),items:v}))}var x="searchWrapper_3rmH";function U(e){return e.mobile?null:r.createElement("div",{className:x},r.createElement(E,null))}var M={default:function(){return T.Z},localeDropdown:function(){return S},search:function(){return U},docsVersion:function(){return n(7250).Z},docsVersionDropdown:function(){return n(9308).Z},doc:function(){return n(6400).Z}};function H(e){var t=e.type,n=(0,D.Z)(e,["type"]),a=function(e){void 0===e&&(e="default");var t=M[e];if(!t)throw new Error("No NavbarItem component found for type="+e+".");return t()}(t);return r.createElement(a,n)}var V=n(5537),P=n(4478),R="displayOnlyInLargeViewport_GrZ2",W="navbarHideable_2qcr",O="navbarHidden_3yey",z="right";var G=function(){var e,t=(0,u.LU)(),n=t.navbar,l=n.items,o=n.hideOnScroll,c=n.style,i=t.colorMode.disableSwitch,s=(0,r.useState)(!1),m=s[0],d=s[1],f=(0,w.Z)(),v=f.isDarkTheme,h=f.setLightTheme,b=f.setDarkTheme,p=L(o),k=p.navbarRef,Z=p.isNavbarVisible;(0,I.Z)(m);var _=(0,r.useCallback)((function(){d(!0)}),[d]),y=(0,r.useCallback)((function(){d(!1)}),[d]),C=(0,r.useCallback)((function(e){return e.target.checked?b():h()}),[h,b]),D=(0,A.Z)();(0,r.useEffect)((function(){D===A.D.desktop&&d(!1)}),[D]);var T=l.some((function(e){return"search"===e.type})),B=function(e){return{leftItems:e.filter((function(e){var t;return"left"===(null!=(t=e.position)?t:z)})),rightItems:e.filter((function(e){var t;return"right"===(null!=(t=e.position)?t:z)}))}}(l),S=B.leftItems,x=B.rightItems;return r.createElement("nav",{ref:k,className:(0,a.Z)("navbar","navbar--fixed-top",(e={"navbar--dark":"dark"===c,"navbar--primary":"primary"===c,"navbar-sidebar--show":m},e[W]=o,e[O]=o&&!Z,e))},r.createElement("div",{className:"navbar__inner"},r.createElement("div",{className:"navbar__items"},null!=l&&0!==l.length&&r.createElement("button",{"aria-label":"Navigation bar toggle",className:"navbar__toggle",type:"button",tabIndex:0,onClick:_,onKeyDown:_},r.createElement(P.Z,null)),r.createElement(V.Z,{className:"navbar__brand",imageClassName:"navbar__logo",titleClassName:(0,a.Z)("navbar__title")}),S.map((function(e,t){return r.createElement(H,(0,g.Z)({},e,{key:t}))}))),r.createElement("div",{className:"navbar__items navbar__items--right"},x.map((function(e,t){return r.createElement(H,(0,g.Z)({},e,{key:t}))})),!i&&r.createElement(N,{className:R,checked:v,onChange:C}),!T&&r.createElement(E,null))),r.createElement("div",{role:"presentation",className:"navbar-sidebar__backdrop",onClick:y}),r.createElement("div",{className:"navbar-sidebar"},r.createElement("div",{className:"navbar-sidebar__brand"},r.createElement(V.Z,{className:"navbar__brand",imageClassName:"navbar__logo",titleClassName:"navbar__title",onClick:y}),!i&&m&&r.createElement(N,{checked:v,onChange:C})),r.createElement("div",{className:"navbar-sidebar__items"},r.createElement("div",{className:"menu"},r.createElement("ul",{className:"menu__list"},l.map((function(e,t){return r.createElement(H,(0,g.Z)({mobile:!0},e,{onClick:y,key:t}))})))))))},j=n(6742),F=n(4996),q="footerLogoLink_MyFc",Q=n(8465);function Y(e){var t=e.to,n=e.href,a=e.label,l=e.prependBaseUrlToHref,o=(0,D.Z)(e,["to","href","label","prependBaseUrlToHref"]),c=(0,F.Z)(t),i=(0,F.Z)(n,{forcePrependBaseUrl:!0});return r.createElement(j.Z,(0,g.Z)({className:"footer__link-item"},n?{href:l?i:n}:{to:c},o),a)}var J=function(e){var t=e.sources,n=e.alt;return r.createElement(Q.Z,{className:"footer__logo",alt:n,sources:t})};var K=function(){var e=(0,u.LU)().footer,t=e||{},n=t.copyright,l=t.links,o=void 0===l?[]:l,c=t.logo,i=void 0===c?{}:c,s={light:(0,F.Z)(i.src),dark:(0,F.Z)(i.srcDark||i.src)};return e?r.createElement("footer",{className:(0,a.Z)("footer",{"footer--dark":"dark"===e.style})},r.createElement("div",{className:"container"},o&&o.length>0&&r.createElement("div",{className:"row footer__links"},o.map((function(e,t){return r.createElement("div",{key:t,className:"col footer__col"},null!=e.title?r.createElement("h4",{className:"footer__title"},e.title):null,null!=e.items&&Array.isArray(e.items)&&e.items.length>0?r.createElement("ul",{className:"footer__items"},e.items.map((function(e,t){return e.html?r.createElement("li",{key:t,className:"footer__item",dangerouslySetInnerHTML:{__html:e.html}}):r.createElement("li",{key:e.href||e.to,className:"footer__item"},r.createElement(Y,e))}))):null)}))),(i||n)&&r.createElement("div",{className:"footer__bottom text--center"},i&&(i.src||i.srcDark)&&r.createElement("div",{className:"margin-bottom--sm"},i.href?r.createElement(j.Z,{href:i.href,className:q},r.createElement(J,{alt:i.alt,sources:s})):r.createElement(J,{alt:i.alt,sources:s})),n?r.createElement("div",{className:"footer__copyright",dangerouslySetInnerHTML:{__html:n}}):null))):null},X=n(412),$=(0,u.WA)("theme"),ee="light",te="dark",ne=function(e){return e===te?te:ee},re=function(e){(0,u.WA)("theme").set(ne(e))},ae=function(){var e=(0,u.LU)().colorMode,t=e.defaultMode,n=e.disableSwitch,a=e.respectPrefersColorScheme,l=(0,r.useState)(function(e){return X.Z.canUseDOM?ne(document.documentElement.getAttribute("data-theme")):ne(e)}(t)),o=l[0],c=l[1],i=(0,r.useCallback)((function(){c(ee),re(ee)}),[]),s=(0,r.useCallback)((function(){c(te),re(te)}),[]);return(0,r.useEffect)((function(){document.documentElement.setAttribute("data-theme",ne(o))}),[o]),(0,r.useEffect)((function(){if(!n)try{var e=$.get();null!==e&&c(ne(e))}catch(t){console.error(t)}}),[c]),(0,r.useEffect)((function(){n&&!a||window.matchMedia("(prefers-color-scheme: dark)").addListener((function(e){var t=e.matches;c(t?te:ee)}))}),[]),{isDarkTheme:o===te,setLightTheme:i,setDarkTheme:s}},le=n(2924);var oe=function(e){var t=ae(),n=t.isDarkTheme,a=t.setLightTheme,l=t.setDarkTheme;return r.createElement(le.Z.Provider,{value:{isDarkTheme:n,setLightTheme:a,setDarkTheme:l}},e.children)};function ce(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function ie(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return ce(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?ce(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0;return function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var se="docusaurus.tab.",ue=function(){var e=(0,r.useState)({}),t=e[0],n=e[1],a=(0,r.useCallback)((function(e,t){(0,u.WA)("docusaurus.tab."+e).set(t)}),[]);return(0,r.useEffect)((function(){try{for(var e,t={},r=ie((0,u._f)());!(e=r()).done;){var a=e.value;if(a.startsWith(se))t[a.substring(se.length)]=(0,u.WA)(a).get()}n(t)}catch(l){console.error(l)}}),[]),{tabGroupChoices:t,setTabGroupChoices:function(e,t){n((function(n){var r;return Object.assign({},n,((r={})[e]=t,r))})),a(e,t)}}},me=(0,u.WA)("docusaurus.announcement.dismiss"),de=(0,u.WA)("docusaurus.announcement.id"),fe=function(){var e=(0,u.LU)().announcementBar,t=(0,r.useState)(!0),n=t[0],a=t[1],l=(0,r.useCallback)((function(){me.set("true"),a(!0)}),[]);return(0,r.useEffect)((function(){if(e){var t=e.id,n=de.get();"annoucement-bar"===n&&(n="announcement-bar");var r=t!==n;de.set(t),r&&me.set("false"),(r||"false"===me.get())&&a(!1)}}),[]),{isAnnouncementBarClosed:n,closeAnnouncementBar:l}},ve=n(9443);var he=function(e){var t=ue(),n=t.tabGroupChoices,a=t.setTabGroupChoices,l=fe(),o=l.isAnnouncementBarClosed,c=l.closeAnnouncementBar;return r.createElement(ve.Z.Provider,{value:{tabGroupChoices:n,setTabGroupChoices:a,isAnnouncementBarClosed:o,closeAnnouncementBar:c}},e.children)};function be(e){var t=e.children;return r.createElement(oe,null,r.createElement(he,null,r.createElement(u.L5,null,t)))}var ge=n(9105);function Ee(e){var t=e.locale,n=e.version,a=e.tag;return r.createElement(ge.Z,null,t&&r.createElement("meta",{name:"docusaurus_locale",content:""+t}),n&&r.createElement("meta",{name:"docusaurus_version",content:n}),a&&r.createElement("meta",{name:"docusaurus_tag",content:a}))}var pe=n(1217);function ke(){var e=(0,p.default)().i18n,t=e.defaultLocale,n=e.locales,a=(0,u.l5)();return r.createElement(ge.Z,null,n.map((function(e){return r.createElement("link",{key:e,rel:"alternate",href:a.createUrl({locale:e,fullyQualified:!0}),hrefLang:e})})),r.createElement("link",{rel:"alternate",href:a.createUrl({locale:t,fullyQualified:!0}),hrefLang:"x-default"}))}function Ze(e){var t=e.permalink,n=(0,p.default)().siteConfig.url,a=function(){var e=(0,p.default)().siteConfig.url,t=(0,o.TH)().pathname;return e+(0,F.Z)(t)}(),l=t?""+n+t:a;return r.createElement(ge.Z,null,r.createElement("meta",{property:"og:url",content:l}),r.createElement("link",{rel:"canonical",href:l}))}function _e(e){var t=(0,p.default)(),n=t.siteConfig,a=n.favicon,l=n.themeConfig.metadatas,o=t.i18n,c=o.currentLocale,i=o.localeConfigs,s=e.title,m=e.description,d=e.image,f=e.keywords,v=e.searchMetadatas,h=(0,F.Z)(a),b=(0,u.pe)(s),E=c,k=i[c].direction;return r.createElement(r.Fragment,null,r.createElement(ge.Z,null,r.createElement("html",{lang:E,dir:k}),a&&r.createElement("link",{rel:"shortcut icon",href:h}),r.createElement("title",null,b),r.createElement("meta",{property:"og:title",content:b})),r.createElement(pe.Z,{description:m,keywords:f,image:d}),r.createElement(Ze,null),r.createElement(ke,null),r.createElement(Ee,(0,g.Z)({tag:u.HX,locale:c},v)),r.createElement(ge.Z,null,l.map((function(e,t){return r.createElement("meta",(0,g.Z)({key:"metadata_"+t},e))}))))}var ye=function(){(0,r.useEffect)((function(){var e="navigation-with-keyboard";function t(t){"keydown"===t.type&&"Tab"===t.key&&document.body.classList.add(e),"mousedown"===t.type&&document.body.classList.remove(e)}return document.addEventListener("keydown",t),document.addEventListener("mousedown",t),function(){document.body.classList.remove(e),document.removeEventListener("keydown",t),document.removeEventListener("mousedown",t)}}),[])};var Ne=function(e){var t=e.children,n=e.noFooter,l=e.wrapperClassName,o=e.pageClassName;return ye(),r.createElement(be,null,r.createElement(_e,e),r.createElement(s,null),r.createElement(b,null),r.createElement(G,null),r.createElement("div",{className:(0,a.Z)(u.kM.wrapper.main,l,o)},t),!n&&r.createElement(K,null))}},5537:function(e,t,n){"use strict";var r=n(2122),a=n(9756),l=n(7294),o=n(6742),c=n(8465),i=n(4996),s=n(2263),u=n(6700);t.Z=function(e){var t=(0,s.default)().isClient,n=(0,u.LU)().navbar,m=n.title,d=n.logo,f=void 0===d?{src:""}:d,v=e.imageClassName,h=e.titleClassName,b=(0,a.Z)(e,["imageClassName","titleClassName"]),g=(0,i.Z)(f.href||"/"),E={light:(0,i.Z)(f.src),dark:(0,i.Z)(f.srcDark||f.src)};return l.createElement(o.Z,(0,r.Z)({to:g},b,f.target&&{target:f.target}),f.src&&l.createElement(c.Z,{key:t,className:v,sources:E,alt:f.alt||m||"Logo"}),null!=m&&l.createElement("strong",{className:h},m))}},5525:function(e,t,n){"use strict";var r=n(2122),a=n(9756),l=n(7294),o=n(6010),c=n(6742),i=n(4996),s=n(5977),u=n(6700);function m(e){var t=e.activeBasePath,n=e.activeBaseRegex,o=e.to,s=e.href,u=e.label,m=e.activeClassName,d=void 0===m?"navbar__link--active":m,f=e.prependBaseUrlToHref,v=(0,a.Z)(e,["activeBasePath","activeBaseRegex","to","href","label","activeClassName","prependBaseUrlToHref"]),h=(0,i.Z)(o),b=(0,i.Z)(t),g=(0,i.Z)(s,{forcePrependBaseUrl:!0});return l.createElement(c.Z,(0,r.Z)({},s?{href:f?g:s}:Object.assign({isNavLink:!0,activeClassName:d,to:h},t||n?{isActive:function(e,t){return n?new RegExp(n).test(t.pathname):t.pathname.startsWith(b)}}:null),v),u)}function d(e){var t,n=e.items,c=e.position,i=e.className,s=(0,a.Z)(e,["items","position","className"]),u=(0,l.useRef)(null),d=(0,l.useRef)(null),f=(0,l.useState)(!1),v=f[0],h=f[1];(0,l.useEffect)((function(){var e=function(e){u.current&&!u.current.contains(e.target)&&h(!1)};return document.addEventListener("mousedown",e),document.addEventListener("touchstart",e),function(){document.removeEventListener("mousedown",e),document.removeEventListener("touchstart",e)}}),[u]);var b=function(e,t){return void 0===t&&(t=!1),(0,o.Z)({"navbar__item navbar__link":!t,dropdown__link:t},e)};return n?l.createElement("div",{ref:u,className:(0,o.Z)("navbar__item","dropdown","dropdown--hoverable",{"dropdown--left":"left"===c,"dropdown--right":"right"===c,"dropdown--show":v})},l.createElement(m,(0,r.Z)({className:b(i)},s,{onClick:s.to?void 0:function(e){return e.preventDefault()},onKeyDown:function(e){"Enter"===e.key&&(e.preventDefault(),h(!v))}}),null!=(t=s.children)?t:s.label),l.createElement("ul",{ref:d,className:"dropdown__menu"},n.map((function(e,t){var o=e.className,c=(0,a.Z)(e,["className"]);return l.createElement("li",{key:t},l.createElement(m,(0,r.Z)({onKeyDown:function(e){if(t===n.length-1&&"Tab"===e.key){e.preventDefault(),h(!1);var r=u.current.nextElementSibling;r&&r.focus()}},activeClassName:"dropdown__link--active",className:b(o,!0)},c)))})))):l.createElement(m,(0,r.Z)({className:b(i)},s))}function f(e){var t,n,c,i=e.items,d=e.className,f=(e.position,(0,a.Z)(e,["items","className","position"])),v=(0,l.useRef)(null),h=(0,s.TH)().pathname,b=(0,l.useState)((function(){var e;return null==(e=!(null!=i&&i.some((function(e){return(0,u.Mg)(e.to,h)}))))||e})),g=b[0],E=b[1],p=function(e,t){return void 0===t&&(t=!1),(0,o.Z)("menu__link",{"menu__link--sublist":t},e)};if(!i)return l.createElement("li",{className:"menu__list-item"},l.createElement(m,(0,r.Z)({className:p(d)},f)));var k=null!=(t=v.current)&&t.scrollHeight?(null==(n=v.current)?void 0:n.scrollHeight)+"px":void 0;return l.createElement("li",{className:(0,o.Z)("menu__list-item",{"menu__list-item--collapsed":g})},l.createElement(m,(0,r.Z)({role:"button",className:p(d,!0)},f,{onClick:function(e){e.preventDefault(),E((function(e){return!e}))}}),null!=(c=f.children)?c:f.label),l.createElement("ul",{className:"menu__list",ref:v,style:{height:g?void 0:k}},i.map((function(e,t){var n=e.className,o=(0,a.Z)(e,["className"]);return l.createElement("li",{className:"menu__list-item",key:t},l.createElement(m,(0,r.Z)({activeClassName:"menu__link--active",className:p(n)},o,{onClick:f.onClick})))}))))}t.Z=function(e){var t=e.mobile,n=void 0!==t&&t,r=(0,a.Z)(e,["mobile"]),o=n?f:d;return l.createElement(o,r)}},6400:function(e,t,n){"use strict";n.d(t,{Z:function(){return u}});var r=n(2122),a=n(9756),l=n(7294),o=n(5525),c=n(907),i=n(6010),s=n(6700);function u(e){var t,n,u=e.docId,m=e.activeSidebarClassName,d=e.label,f=e.docsPluginId,v=(0,a.Z)(e,["docId","activeSidebarClassName","label","docsPluginId"]),h=(0,c.useActiveDocContext)(f),b=h.activeVersion,g=h.activeDoc,E=(0,s.J)(f).preferredVersion,p=(0,c.useLatestVersion)(f),k=null!=(t=null!=b?b:E)?t:p,Z=k.docs.find((function(e){return e.id===u}));if(!Z){var _=k.docs.map((function(e){return e.id})).join("\n- ");throw new Error("DocNavbarItem: couldn't find any doc with id="+u+" in version "+k.name+".\nAvailable docIds=\n- "+_)}return l.createElement(o.Z,(0,r.Z)({exact:!0},v,{className:(0,i.Z)(v.className,(n={},n[m]=g&&g.sidebar===Z.sidebar,n)),label:null!=d?d:Z.id,to:Z.path}))}},9308:function(e,t,n){"use strict";n.d(t,{Z:function(){return u}});var r=n(2122),a=n(9756),l=n(7294),o=n(5525),c=n(907),i=n(6700),s=function(e){return e.docs.find((function(t){return t.id===e.mainDocId}))};function u(e){var t,n,u=e.mobile,m=e.docsPluginId,d=e.dropdownActiveClassDisabled,f=e.dropdownItemsBefore,v=e.dropdownItemsAfter,h=(0,a.Z)(e,["mobile","docsPluginId","dropdownActiveClassDisabled","dropdownItemsBefore","dropdownItemsAfter"]),b=(0,c.useActiveDocContext)(m),g=(0,c.useVersions)(m),E=(0,c.useLatestVersion)(m),p=(0,i.J)(m),k=p.preferredVersion,Z=p.savePreferredVersionName;var _=null!=(t=null!=(n=b.activeVersion)?n:k)?t:E,y=u?"Versions":_.label,N=u?void 0:s(_).path;return l.createElement(o.Z,(0,r.Z)({},h,{mobile:u,label:y,to:N,items:function(){var e=g.map((function(e){var t=(null==b?void 0:b.alternateDocVersions[e.name])||s(e);return{isNavLink:!0,label:e.label,to:t.path,isActive:function(){return e===(null==b?void 0:b.activeVersion)},onClick:function(){Z(e.name)}}})),t=[].concat(f,e,v);if(!(t.length<=1))return t}(),isActive:d?function(){return!1}:void 0}))}},7250:function(e,t,n){"use strict";n.d(t,{Z:function(){return s}});var r=n(2122),a=n(9756),l=n(7294),o=n(5525),c=n(907),i=n(6700);function s(e){var t,n=e.label,s=e.to,u=e.docsPluginId,m=(0,a.Z)(e,["label","to","docsPluginId"]),d=(0,c.useActiveVersion)(u),f=(0,i.J)(u).preferredVersion,v=(0,c.useLatestVersion)(u),h=null!=(t=null!=d?d:f)?t:v,b=null!=n?n:h.label,g=null!=s?s:function(e){return e.docs.find((function(t){return t.id===e.mainDocId}))}(h).path;return l.createElement(o.Z,(0,r.Z)({},m,{label:b,to:g}))}},2924:function(e,t,n){"use strict";var r=n(7294).createContext(void 0);t.Z=r},8465:function(e,t,n){"use strict";n.d(t,{Z:function(){return u}});var r=n(2122),a=n(9756),l=n(7294),o=n(6010),c=n(2263),i=n(5350),s={themedImage:"themedImage_1VuW","themedImage--light":"themedImage--light_3UqQ","themedImage--dark":"themedImage--dark_hz6m"},u=function(e){var t=(0,c.default)().isClient,n=(0,i.Z)().isDarkTheme,u=e.sources,m=e.className,d=e.alt,f=void 0===d?"":d,v=(0,a.Z)(e,["sources","className","alt"]),h=t?n?["dark"]:["light"]:["light","dark"];return l.createElement(l.Fragment,null,h.map((function(e){return l.createElement("img",(0,r.Z)({key:e,src:u[e],alt:f,className:(0,o.Z)(s.themedImage,s["themedImage--"+e],m)},v))})))}},9443:function(e,t,n){"use strict";var r=(0,n(7294).createContext)(void 0);t.Z=r},1839:function(e,t,n){"use strict";var r=n(7294);t.Z=function(e){void 0===e&&(e=!0),(0,r.useEffect)((function(){return document.body.style.overflow=e?"hidden":"visible",function(){document.body.style.overflow="visible"}}),[e])}},7898:function(e,t,n){"use strict";var r=n(7294),a=n(412),l=function(){return{scrollX:a.Z.canUseDOM?window.pageXOffset:0,scrollY:a.Z.canUseDOM?window.pageYOffset:0}};t.Z=function(e,t){void 0===t&&(t=[]);var n=(0,r.useRef)(l()),a=function(){var t=l();e&&e(t,n.current),n.current=t};(0,r.useEffect)((function(){var e={passive:!0};return a(),window.addEventListener("scroll",a,e),function(){return window.removeEventListener("scroll",a,e)}}),t)}},5350:function(e,t,n){"use strict";var r=n(7294),a=n(2924);t.Z=function(){var e=(0,r.useContext)(a.Z);if(null==e)throw new Error("`useThemeContext` is used outside of `Layout` Component. See https://docusaurus.io/docs/api/themes/configuration#usethemecontext.");return e}},944:function(e,t,n){"use strict";var r=n(7294),a=n(9443);t.Z=function(){var e=(0,r.useContext)(a.Z);if(null==e)throw new Error("`useUserPreferencesContext` is used outside of `Layout` Component.");return e}},3783:function(e,t,n){"use strict";n.d(t,{D:function(){return l}});var r=n(7294),a=n(412),l={desktop:"desktop",mobile:"mobile"};t.Z=function(){var e=a.Z.canUseDOM;function t(){if(e)return window.innerWidth>996?l.desktop:l.mobile}var n=(0,r.useState)(t),o=n[0],c=n[1];return(0,r.useEffect)((function(){if(e)return window.addEventListener("resize",n),function(){return window.removeEventListener("resize",n)};function n(){c(t())}}),[]),o}}}]);
module.exports = new Date(2005, 5, 22)
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[28],{ /***/ "./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&": /*!*************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib??ref--4-0!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js& ***! \*************************************************************************************************************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var vuex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vuex */ \"./node_modules/vuex/dist/vuex.esm.js\");\n/* harmony import */ var vue_star_rating__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! vue-star-rating */ \"./node_modules/vue-star-rating/dist/VueStarRating.common.js\");\n/* harmony import */ var vue_star_rating__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(vue_star_rating__WEBPACK_IMPORTED_MODULE_1__);\n/* harmony import */ var _helpers__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../helpers */ \"./resources/js/helpers/index.js\");\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n//\n\n\n\n\nvar moment = __webpack_require__(/*! moment */ \"./node_modules/moment/moment.js\");\n\nvar axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n\nvar _ = __webpack_require__(/*! lodash */ \"./node_modules/lodash/lodash.js\");\n\n/* harmony default export */ __webpack_exports__[\"default\"] = ({\n name: 'VideoChat',\n components: {\n StarRating: vue_star_rating__WEBPACK_IMPORTED_MODULE_1___default.a\n },\n data: function data() {\n return {\n tc: {\n accessManager: null,\n messagingClient: null,\n channel: [],\n username: '',\n channelArray: [],\n currentChannel: null,\n generalChannel: null,\n activeChannelIndex: null,\n messagesArray: []\n },\n username: '',\n connected: false,\n selected: false,\n showMessages: false,\n moment: moment,\n message: null,\n userNotJoined: true,\n newChannel: '',\n showAddChannelInput: false,\n notification: false,\n notificationMsg: '',\n accessToken: '',\n roomSid: '',\n dataSid: '',\n name: this.$route.params.roomName,\n currentStatus: 'not-started',\n videoRoom: [],\n viewerCount: 0,\n showRateModal: false,\n ratingCount: 0,\n roomId: '',\n loggedUser: ''\n };\n },\n computed: Object(vuex__WEBPACK_IMPORTED_MODULE_0__[\"mapGetters\"])({\n user: 'auth/user'\n }),\n beforeMount: function beforeMount() {\n var _this$user,\n _this$user2,\n _this = this;\n\n console.log('this.user.username', this.user); // ASSIGNING USERNAME\n\n this.loggedUser = (_this$user = this.user) !== null && _this$user !== void 0 && _this$user.username ? (_this$user2 = this.user) === null || _this$user2 === void 0 ? void 0 : _this$user2.username : '';\n this.user ? this.connectClientWithUsername() : this.joinAsParticipant(); // CHECKING IF BROADCAST IS ONGOING\n\n axios.get('/api/video/' + this.name).then(function (response) {\n if (response.data.success) {\n _this.roomId = response.data.data.id;\n _this.dataSid = response.data.data.room_sid;\n _this.currentStatus = response.data.data.room_status; // vm.username !== vm.name ? this.joinAsParticipant() : this.joinAsParticipant();\n }\n })[\"catch\"](function (err) {\n console.log(err.response);\n }); // this.connectClientWithUsername();\n },\n methods: {\n // MODAL METHODS\n resetRatingForms: function resetRatingForms() {\n var vm = this;\n vm.ratingCount = 0;\n },\n handleSubmitRating: function handleSubmitRating() {\n var _this2 = this;\n\n var vm = this;\n\n if (!this.user) {\n Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[\"swalOops\"])('You have to login for you to rate the host.');\n }\n\n var data = {\n 'reference_id': vm.roomId,\n 'category': 'LIVE',\n 'rate': vm.ratingCount\n };\n axios.post(\"/api/rating/save\", data).then(function (response) {\n Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[\"swalSuccess\"])('Rating submitted!');\n\n _this2.resetRatingForms();\n });\n },\n // CHAT METHODS\n connectClientWithUsername: function connectClientWithUsername() {\n if (this.loggedUser) {\n this.tc.username = this.loggedUser;\n this.userNotJoined = false;\n axios.get('/api/video/view/' + this.name);\n this.fetchAccessToken(this.tc.username, this.connectMessagingClient);\n console.log('USERNAME', this.tc.username);\n } else {\n alert('NOT LOGGED IN');\n }\n },\n fetchAccessToken: function fetchAccessToken(username, handler) {\n axios.post('/api/video/chat', {\n identity: username,\n device: 'browser'\n }).then(function (response) {\n handler(response.data);\n })[\"catch\"](function (error) {\n console.log(error);\n });\n },\n connectMessagingClient: function connectMessagingClient(token) {\n // Initialize the Chat messaging client\n var vm = this;\n vm.tc.accessManager = new Twilio.AccessManager(token);\n Twilio.Chat.Client.create(token).then(function (client) {\n vm.tc.messagingClient = client;\n vm.updateConnectedUI();\n vm.loadChannelList(vm.joinGeneralChannel);\n vm.tc.messagingClient.on('channelAdded', _.throttle(vm.loadChannelList));\n vm.tc.messagingClient.on('channelRemoved', _.throttle(vm.loadChannelList));\n vm.tc.messagingClient.on('tokenExpired', vm.refreshToken);\n });\n },\n updateConnectedUI: function updateConnectedUI() {\n this.connected = true;\n },\n refreshToken: function refreshToken() {\n this.fetchAccessToken(this.tc.username, this.setNewToken);\n },\n setNewToken: function setNewToken(tokenResponse) {\n this.tc.accessManager.updateToken(tokenResponse.token);\n },\n loadChannelList: function loadChannelList(handler) {\n if (this.tc.messagingClient === undefined) {\n console.log('Client is not initialized');\n return;\n }\n\n this.getVisibleChannels(this.tc.messagingClient, handler);\n },\n getVisibleChannels: function getVisibleChannels(messagingClient, handler) {\n var vm = this;\n messagingClient.getPublicChannelDescriptors().then(function (channels) {\n vm.tc.channelArray = vm.sortChannelsByName(channels.items);\n vm.tc.channelArray.forEach(vm.addChannel);\n\n if (typeof handler === 'function') {\n handler();\n }\n });\n },\n sortChannelsByName: function sortChannelsByName(channels) {\n var vm = this;\n return channels.sort(function (a, b) {\n if (a.friendlyName === vm.name) {\n return -1;\n }\n\n if (b.friendlyName === vm.name) {\n return 1;\n }\n\n return a.friendlyName.localeCompare(b.friendlyName);\n });\n },\n joinGeneralChannel: function joinGeneralChannel() {\n var vm = this;\n console.log('Attempting to join \"general\" chat channel...', vm.name);\n\n if (vm.tc.generalChannel === null) {\n // If it doesn't exist, let's create it\n vm.tc.messagingClient.createChannel({\n uniqueName: vm.name,\n friendlyName: vm.name\n }).then(function (channel) {\n vm.tc.generalChannel = channel;\n vm.loadChannelList(vm.joinGeneralChannel);\n });\n } else {\n console.log('Found general channel:', vm.tc.generalChannel);\n vm.setupChannel(vm.tc.generalChannel);\n }\n },\n addChannel: function addChannel(channel) {\n var vm = this;\n\n if (channel.uniqueName === vm.name) {\n this.tc.generalChannel = channel;\n }\n },\n setupChannel: function setupChannel(channel) {\n var vm = this;\n return vm.leaveCurrentChannel().then(function () {\n return vm.initChannel(channel);\n }).then(function (_channel) {\n vm.tc.currentChannel = _channel;\n vm.loadMessages();\n return vm.joinChannel(_channel);\n }).then(vm.initChannelEvents);\n },\n leaveCurrentChannel: function leaveCurrentChannel() {\n var vm = this;\n\n if (this.tc.currentChannel) {\n return this.tc.currentChannel.leave().then(function (leftChannel) {\n console.log('left ' + leftChannel.friendlyName);\n leftChannel.removeListener('messageAdded', vm.addMessageToList);\n leftChannel.removeListener('typingStarted', vm.showTypingStarted);\n leftChannel.removeListener('typingEnded', vm.hideTypingStarted);\n leftChannel.removeListener('memberJoined', vm.notifyMemberJoined);\n leftChannel.removeListener('memberLeft', vm.notifyMemberLeft);\n });\n } else {\n console.log('resolving');\n return Promise.resolve();\n }\n },\n initChannel: function initChannel(channel) {\n console.log('Initialized channel ' + channel.friendlyName);\n return this.tc.messagingClient.getChannelBySid(channel.sid);\n },\n initChannelEvents: function initChannelEvents() {\n console.log(this.tc.currentChannel.friendlyName + ' ready.');\n this.tc.currentChannel.on('messageAdded', this.addMessageToList);\n this.tc.currentChannel.on('typingStarted', this.showTypingStarted);\n this.tc.currentChannel.on('typingEnded', this.hideTypingStarted);\n this.tc.currentChannel.on('memberJoined', this.notifyMemberJoined);\n this.tc.currentChannel.on('memberLeft', this.notifyMemberLeft); // $inputText.prop('disabled', false).focus();\n },\n showTypingStarted: function showTypingStarted(member) {\n console.log(member.identity + ' is typing...');\n this.notificationMsg = member.identity + ' is typing...';\n this.notification = true;\n },\n hideTypingStarted: function hideTypingStarted(member) {\n this.notificationMsg = '';\n this.notification = false;\n },\n notifyMemberJoined: function notifyMemberJoined(member) {\n console.log('joining');\n console.log(member.identity + ' joined the channel'); // notify(member.identity + ' joined the channel')\n },\n notifyMemberLeft: function notifyMemberLeft(member) {\n console.log('leaving');\n console.log(member);\n console.log(member.identity + ' left the channel'); // notify(member.identity + ' left the channel');\n },\n notify: function notify(message) {\n var row = $('<div>').addClass('col-md-12');\n row.loadTemplate('#member-notification-template', {\n status: message\n });\n this.tc.$messageList.append(row);\n },\n joinChannel: function joinChannel(_channel) {\n var vm = this;\n return _channel.join().then(function (joinedChannel) {\n console.log('Joined channel ' + joinedChannel.friendlyName); // vm.updateChannelUI(_channel);\n\n vm.tc.currentChannel = _channel;\n vm.loadMessages();\n return joinedChannel;\n })[\"catch\"](function (err) {\n console.warn('couldt join channel' + _channel.friendlyName + ' because ' + err); // alert(\"Couldn't join channel \" + _channel.friendlyName + ' because ' + err);\n });\n },\n // updateChannelUI(selectedChannel) {\n // let channelLists = this.$refs.channelList;\n // let activeChannelList = channelLists.filter(function(element) {\n // return element.dataset.sid === selectedChannel.sid;\n // });\n // activeChannelList = activeChannelList[0];\n // if (this.tc.currentChannelContainer === undefined && selectedChannel.friendlyName === vm.name) {\n // this.tc.currentChannelContainer = activeChannelList;\n // }\n // this.tc.currentChannelContainer.classList.remove('selected-channel');\n // this.tc.currentChannelContainer = activeChannelList;\n // this.tc.currentChannelContainer.classList.add('selected-channel');\n // },\n loadMessages: function loadMessages() {\n var vm = this;\n this.tc.currentChannel.getMessages(50).then(function (messages) {\n vm.showMessages = true;\n vm.tc.messagesArray = messages.items; // vm.userNotJoined = false\n\n messages.items.forEach(vm.addMessageToList);\n });\n },\n addMessageToList: function addMessageToList(message) {\n console.log(message);\n this.loadMessages();\n },\n handleInputTextKeypress: function handleInputTextKeypress() {\n this.tc.currentChannel.sendMessage(this.message);\n this.message = '';\n setTimeout(function () {\n this.loadMessages();\n }, 3000);\n },\n handleNewChannelInputKeypress: function handleNewChannelInputKeypress(event) {\n var vm = this;\n\n if (this.newChannel == '') {\n alert('Channel name cannot be empty');\n return;\n }\n\n this.tc.messagingClient.createChannel({\n friendlyName: this.newChannel\n }).then(function (channel) {\n console.log('Created channel');\n vm.loadChannelList(channel);\n }).then(this.hideAddChannelInput);\n this.newChannel = '';\n },\n selectChannel: function selectChannel(channel) {\n var channelSid = channel.sid;\n var selectedChannel = this.tc.channelArray.filter(function (channel) {\n return channel.sid === channelSid;\n })[0];\n\n if (selectedChannel === this.tc.currentChannel) {\n return;\n }\n\n this.setupChannel(selectedChannel);\n },\n hideAddChannelInput: function hideAddChannelInput() {\n this.showAddChannelInput = false;\n },\n createChannel: function createChannel() {\n this.showAddChannelInput = true;\n },\n deleteChannel: function deleteChannel() {\n // if (this.tc.currentChannel.sid === this.tc.generalChannel.sid) {\n // alert('You cannot delete the general channel');\n // return;\n // }\n this.tc.currentChannel[\"delete\"]().then(function (channel) {\n console.log('channel: ' + channel.friendlyName + ' deleted'); // setupChannel(this.tc.generalChannel);\n });\n },\n // VIDEO METHODS\n getVideoToken: function getVideoToken() {\n console.log('Video chat room loading...');\n var vm = this; // Request a new token\n\n axios.get(\"/api/video/access_token/\".concat(this.name)).then(function (response) {\n vm.accessToken = response.data;\n vm.currentStatus = 'ON_GOING';\n })[\"catch\"](function (error) {\n console.log(error);\n }).then(function () {\n vm.connectToRoom();\n });\n },\n joinAsParticipant: function joinAsParticipant() {\n console.log('Video chat room loading...');\n var vm = this;\n vm.tc.username = vm.name; // vm.fetchAccessToken(vm.name, vm.connectMessagingClient)\n\n console.log('USERNAME', vm.name); // Request a new token\n\n axios.get(\"/api/video/access_token/\".concat(vm.name)).then(function (response) {\n vm.accessToken = response.data;\n })[\"catch\"](function (error) {\n console.log(error);\n }).then(function () {\n vm.joinToRoom();\n });\n },\n connectToRoom: function connectToRoom() {\n var _this3 = this;\n\n var axios = __webpack_require__(/*! axios */ \"./node_modules/axios/index.js\");\n\n var _require = __webpack_require__(/*! twilio-video */ \"./node_modules/twilio-video/es5/index.js\"),\n connect = _require.connect,\n createLocalTracks = _require.createLocalTracks;\n\n connect(this.accessToken, {\n name: this.name\n }).then(function (room) {\n console.log(\"Successfully joined a Room: \".concat(room));\n console.log('Data::', room.sid);\n _this3.dataSid = room.sid;\n _this3.videoRoom = room;\n var request = {\n room_name: _this3.name,\n room_sid: room.sid,\n room_status: 'ON_GOING'\n };\n axios.post(\"/api/video/history/save\", request).then(function (response) {\n console.log(response);\n })[\"catch\"](function (err) {\n console.log(err);\n });\n var videoChatWindow = document.getElementById('my-video-chat-window');\n _this3.viewerCount = room.participants.size;\n var localTrack;\n createLocalTracks().then(function (track) {\n console.log(track);\n localTrack = track;\n track.forEach(function (media) {\n videoChatWindow.appendChild(media.attach());\n });\n });\n room.on('participantConnected', function (participant) {\n console.log(\"Participant \\\"\".concat(participant.identity, \"\\\" connected\"));\n _this3.viewerCount = room.participants.size; // participant.tracks.forEach(publication => {\n // if (publication.isSubscribed) {\n // const track = publication.track;\n // videoChatWindow.appendChild(track.attach());\n // }\n // });\n // participant.on('trackSubscribed', track => {\n // videoChatWindow.appendChild(track.attach());\n // });\n });\n room.on('disconnected', function (room) {\n // Detach the local media elements\n console.log('Host disconnected');\n console.log('localParticipant', room.localParticipant);\n console.log('videoChatWindow', videoChatWindow.childNodes[0]);\n _this3.viewerCount = room.participants.size;\n var child = videoChatWindow.lastElementChild;\n videoChatWindow.removeChild(child); // videoChatWindow.innerHTML =\"\";\n\n console.log('DC TRACKS', localTrack);\n localTrack.forEach(function (track) {\n track.stop();\n track.detach();\n });\n });\n room.on('participantDisconnected', function (room) {\n // Detach the local media elements\n console.log('Someone disconnected'); // this.viewerCount = this.viewerCount - 1\n\n _this3.viewerCount = room.participants.size;\n room.localParticipant.tracks.forEach(function (publication) {\n var attachedElements = publication.track.detach();\n attachedElements.forEach(function (element) {\n return element.remove();\n });\n });\n });\n }, function (error) {\n console.error(\"Unable to connect to Room: \".concat(error.message));\n Object(_helpers__WEBPACK_IMPORTED_MODULE_2__[\"swalOops\"])(\"Please make sure that your camera and microphone is connected, and have permissions\");\n\n _this3.stopBroadcasting();\n });\n },\n joinToRoom: function joinToRoom() {\n var _this4 = this;\n\n var _require2 = __webpack_require__(/*! twilio-video */ \"./node_modules/twilio-video/es5/index.js\"),\n connect = _require2.connect;\n\n connect(this.accessToken, {\n name: this.name,\n video: false,\n audio: false\n }).then(function (room) {\n console.log(\"Successfully joined a Room: \".concat(room));\n console.log('Data::', room.sid);\n _this4.dataSid = room.sid;\n var videoChatWindow = document.getElementById('my-video-chat-window');\n var localParticipant = room.localParticipant;\n console.log(\"Connected to the Room as LocalParticipant \\\"\".concat(localParticipant.identity, \"\\\"\")); // room.on('participantConnected', participant => {\n // console.log(`Participant \"${participant.identity}\" connected`)\n // participant.tracks.forEach(publication => {\n // if (publication.isSubscribed) {\n // const track = publication.track\n // videoChatWindow.appendChild(track.attach())\n // }\n // })\n // participant.on('trackSubscribed', track => {\n // videoChatWindow.appendChild(track.attach())\n // })\n // })\n\n room.participants.forEach(function (participant) {\n participant.tracks.forEach(function (publication) {\n console.log('detail', publication);\n console.log('kind', publication.kind);\n\n if (publication.kind === 'video') {\n videoChatWindow.appendChild(publication.attach());\n }\n });\n participant.on('trackSubscribed', function (track) {\n console.log('trackSubscribed', track);\n videoChatWindow.appendChild(track.attach());\n });\n _this4.viewerCount = room.participants.size;\n });\n room.on('participantConnected', function (participant) {\n console.log('new');\n _this4.viewerCount = room.participants.size;\n console.log(\"Participant \\\"\".concat(participant.identity, \"\\\" connected\"));\n participant.tracks.forEach(function (publication) {\n if (publication.isSubscribed) {\n var track = publication.track;\n videoChatWindow.appendChild(track.attach());\n }\n });\n participant.on('trackSubscribed', function (track) {\n videoChatWindow.appendChild(track.attach());\n });\n });\n room.on('participantDisconnected', function (room) {\n // Detach the local media elements\n console.log('Someone disconnected');\n _this4.viewerCount = _this4.viewerCount - 1; // room.participants.tracks.forEach(publication => {\n // const attachedElements = publication.track.detach()\n // attachedElements.forEach(element => element.remove())\n // })\n });\n }, function (error) {\n console.error(\"Unable to connect to Room: \".concat(error.message));\n });\n },\n stopBroadcasting: function stopBroadcasting() {\n var vm = this;\n vm.accessToken = '';\n vm.currentStatus = 'COMPLETED';\n vm.userNotJoined = true;\n vm.showMessages = false;\n vm.deleteChannel();\n vm.tc.accessManager = null;\n vm.tc.messagingClient = null;\n vm.tc.channel = [];\n vm.tc.channelArray = null;\n vm.tc.generalChannel = null;\n vm.tc.activeChannelIndex = null;\n vm.tc.messagesArray = [];\n var request = {\n room_name: vm.name,\n room_sid: vm.dataSid,\n room_status: 'COMPLETED'\n };\n axios.post(\"/api/video/history/save\", request).then(function (response) {\n console.log(response); // vm.currentStatus = 'COMPLETED'\n // vm.userNotJoined = true\n // vm.showMessages = false\n\n vm.videoRoom.disconnect(); // vm.deleteChannel()\n // vm.username = vm.user?.username ? vm.user?.username : ''\n // vm.tc.accessManager = null\n // vm.tc.messagingClient = null\n // vm.tc.channel = []\n // vm.tc.username = '';\n // vm.tc.channelArray = null\n // vm.tc.generalChannel = null\n // vm.tc.activeChannelIndex = null\n // vm.tc.messagesArray = []\n // list.removeChild(list.childNodes);\n // console.log(\"CONSOLE LIST\", list.childNodes);\n })[\"catch\"](function (err) {\n console.log(err);\n });\n }\n }\n});//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vcmVzb3VyY2VzL2pzL3BhZ2VzL3JlYWRlci9saXZlL2dvLWxpdmUudnVlPzBlMzAiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0FBeUlBO0FBQ0E7QUFDQTs7QUFDQTs7QUFDQTs7QUFDQTs7QUFFQTtBQUNBLG1CQURBO0FBR0E7QUFDQTtBQURBLEdBSEE7QUFPQTtBQUNBO0FBQ0E7QUFDQSwyQkFEQTtBQUVBLDZCQUZBO0FBR0EsbUJBSEE7QUFJQSxvQkFKQTtBQUtBLHdCQUxBO0FBTUEsNEJBTkE7QUFPQSw0QkFQQTtBQVFBLGdDQVJBO0FBU0E7QUFUQSxPQURBO0FBWUEsa0JBWkE7QUFhQSxzQkFiQTtBQWNBLHFCQWRBO0FBZUEseUJBZkE7QUFnQkEsb0JBaEJBO0FBaUJBLG1CQWpCQTtBQWtCQSx5QkFsQkE7QUFtQkEsb0JBbkJBO0FBb0JBLGdDQXBCQTtBQXFCQSx5QkFyQkE7QUFzQkEseUJBdEJBO0FBdUJBLHFCQXZCQTtBQXdCQSxpQkF4QkE7QUF5QkEsaUJBekJBO0FBMEJBLHVDQTFCQTtBQTJCQSxrQ0EzQkE7QUE0QkEsbUJBNUJBO0FBNkJBLG9CQTdCQTtBQThCQSwwQkE5QkE7QUErQkEsb0JBL0JBO0FBZ0NBLGdCQWhDQTtBQWlDQTtBQWpDQTtBQW1DQSxHQTNDQTtBQTZDQTtBQUNBO0FBREEsSUE3Q0E7QUFpREE7QUFBQTtBQUFBO0FBQUE7O0FBQ0EsaURBREEsQ0FFQTs7QUFDQTtBQUNBLDRFQUpBLENBTUE7O0FBRUEseUNBQ0EsSUFEQSxDQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNkRBSEEsQ0FJQTtBQUNBO0FBQ0EsS0FSQSxXQVNBO0FBQ0E7QUFDQSxLQVhBLEVBUkEsQ0FvQkE7QUFDQSxHQXRFQTtBQXdFQTtBQUVBO0FBRUEsb0JBSkEsOEJBSUE7QUFDQTtBQUNBO0FBQ0EsS0FQQTtBQVNBLHNCQVRBLGdDQVNBO0FBQUE7O0FBQ0E7O0FBRUE7QUFDQTtBQUNBOztBQUVBO0FBQ0EsaUNBREE7QUFFQSwwQkFGQTtBQUdBO0FBSEE7QUFNQTtBQUNBOztBQUNBO0FBQ0EsT0FIQTtBQUlBLEtBMUJBO0FBNEJBO0FBQ0EsNkJBN0JBLHVDQTZCQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBRUE7QUFDQTtBQUNBLE9BUEEsTUFPQTtBQUNBO0FBQ0E7QUFDQSxLQXhDQTtBQXlDQSxvQkF6Q0EsNEJBeUNBLFFBekNBLEVBeUNBLE9BekNBLEVBeUNBO0FBQ0E7QUFDQSwwQkFEQTtBQUVBO0FBRkEsU0FJQSxJQUpBLENBSUE7QUFDQTtBQUNBLE9BTkEsV0FPQTtBQUNBO0FBQ0EsT0FUQTtBQVVBLEtBcERBO0FBcURBLDBCQXJEQSxrQ0FxREEsS0FyREEsRUFxREE7QUFDQTtBQUNBO0FBRUE7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE9BUEE7QUFRQSxLQW5FQTtBQW9FQSxxQkFwRUEsK0JBb0VBO0FBQ0E7QUFDQSxLQXRFQTtBQXVFQSxnQkF2RUEsMEJBdUVBO0FBQ0E7QUFDQSxLQXpFQTtBQTBFQSxlQTFFQSx1QkEwRUEsYUExRUEsRUEwRUE7QUFDQTtBQUNBLEtBNUVBO0FBNkVBLG1CQTdFQSwyQkE2RUEsT0E3RUEsRUE2RUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFDQTtBQUNBLEtBbkZBO0FBb0ZBLHNCQXBGQSw4QkFvRkEsZUFwRkEsRUFvRkEsT0FwRkEsRUFvRkE7QUFDQTtBQUVBO0FBQ0E7QUFFQTs7QUFDQTtBQUNBO0FBQ0E7QUFDQSxPQVBBO0FBUUEsS0EvRkE7QUFnR0Esc0JBaEdBLDhCQWdHQSxRQWhHQSxFQWdHQTtBQUNBO0FBRUE7QUFDQTtBQUNBO0FBQ0E7O0FBQ0E7QUFDQTtBQUNBOztBQUNBO0FBQ0EsT0FSQTtBQVNBLEtBNUdBO0FBNkdBLHNCQTdHQSxnQ0E2R0E7QUFDQTtBQUNBOztBQUNBO0FBQ0E7QUFDQTtBQUNBLDZCQURBO0FBRUE7QUFGQSxXQUdBLElBSEEsQ0FHQTtBQUNBO0FBQ0E7QUFDQSxTQU5BO0FBT0EsT0FUQSxNQVNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsS0E3SEE7QUE4SEEsY0E5SEEsc0JBOEhBLE9BOUhBLEVBOEhBO0FBQ0E7O0FBQ0E7QUFDQTtBQUNBO0FBQ0EsS0FuSUE7QUFvSUEsZ0JBcElBLHdCQW9JQSxPQXBJQSxFQW9JQTtBQUNBO0FBQ0Esc0NBQ0EsSUFEQSxDQUNBO0FBQ0E7QUFDQSxPQUhBLEVBSUEsSUFKQSxDQUlBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsT0FSQSxFQVNBLElBVEEsQ0FTQSxvQkFUQTtBQVVBLEtBaEpBO0FBaUpBLHVCQWpKQSxpQ0FpSkE7QUFDQTs7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FQQTtBQVFBLE9BVEEsTUFTQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLEtBaEtBO0FBaUtBLGVBaktBLHVCQWlLQSxPQWpLQSxFQWlLQTtBQUNBO0FBQ0E7QUFDQSxLQXBLQTtBQXFLQSxxQkFyS0EsK0JBcUtBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHFFQU5BLENBT0E7QUFDQSxLQTdLQTtBQThLQSxxQkE5S0EsNkJBOEtBLE1BOUtBLEVBOEtBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsS0FsTEE7QUFtTEEscUJBbkxBLDZCQW1MQSxNQW5MQSxFQW1MQTtBQUNBO0FBQ0E7QUFDQSxLQXRMQTtBQXVMQSxzQkF2TEEsOEJBdUxBLE1BdkxBLEVBdUxBO0FBQ0E7QUFDQSwyREFGQSxDQUdBO0FBQ0EsS0EzTEE7QUE0TEEsb0JBNUxBLDRCQTRMQSxNQTVMQSxFQTRMQTtBQUNBO0FBQ0E7QUFDQSx5REFIQSxDQUlBO0FBQ0EsS0FqTUE7QUFrTUEsVUFsTUEsa0JBa01BLE9BbE1BLEVBa01BO0FBQ0E7QUFDQTtBQUNBO0FBREE7QUFHQTtBQUNBLEtBeE1BO0FBeU1BLGVBek1BLHVCQXlNQSxRQXpNQSxFQXlNQTtBQUNBO0FBQ0EsNkJBQ0EsSUFEQSxDQUNBO0FBQ0Esb0VBREEsQ0FFQTs7QUFDQTtBQUNBO0FBQ0E7QUFDQSxPQVBBLFdBUUE7QUFDQSx3RkFEQSxDQUVBO0FBQ0EsT0FYQTtBQVlBLEtBdk5BO0FBd05BO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFFQTtBQUNBO0FBRUE7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBek9BLDBCQXlPQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDZDQUZBLENBR0E7O0FBQ0E7QUFDQSxPQUxBO0FBTUEsS0FqUEE7QUFrUEEsb0JBbFBBLDRCQWtQQSxPQWxQQSxFQWtQQTtBQUNBO0FBQ0E7QUFDQSxLQXJQQTtBQXNQQSwyQkF0UEEscUNBc1BBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxPQUZBLEVBRUEsSUFGQTtBQUdBLEtBNVBBO0FBNlBBLGlDQTdQQSx5Q0E2UEEsS0E3UEEsRUE2UEE7QUFDQTs7QUFDQTtBQUNBO0FBQ0E7QUFDQTs7QUFDQTtBQUNBO0FBREEsU0FFQSxJQUZBLENBRUE7QUFDQTtBQUNBO0FBQ0EsT0FMQSxFQUtBLElBTEEsQ0FLQSx3QkFMQTtBQU1BO0FBQ0EsS0ExUUE7QUEyUUEsaUJBM1FBLHlCQTJRQSxPQTNRQSxFQTJRQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLE9BRkEsRUFFQSxDQUZBOztBQUdBO0FBQ0E7QUFDQTs7QUFDQTtBQUNBLEtBcFJBO0FBcVJBLHVCQXJSQSxpQ0FxUkE7QUFDQTtBQUNBLEtBdlJBO0FBd1JBLGlCQXhSQSwyQkF3UkE7QUFDQTtBQUNBLEtBMVJBO0FBMlJBLGlCQTNSQSwyQkEyUkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EscUVBREEsQ0FFQTtBQUNBLE9BSEE7QUFJQSxLQXBTQTtBQXNTQTtBQUNBO0FBQ0E7QUFFQSxvQkFIQSxDQUtBOztBQUNBLDhEQUNBLElBREEsQ0FDQTtBQUNBO0FBQ0E7QUFDQSxPQUpBLFdBS0E7QUFDQTtBQUNBLE9BUEEsRUFRQSxJQVJBLENBUUE7QUFDQTtBQUNBLE9BVkE7QUFXQSxLQXhUQTtBQXlUQTtBQUNBO0FBRUE7QUFDQSwrQkFKQSxDQUtBOztBQUNBLHVDQU5BLENBUUE7O0FBQ0EsNERBQ0EsSUFEQSxDQUNBO0FBQ0E7QUFDQSxPQUhBLFdBSUE7QUFDQTtBQUNBLE9BTkEsRUFPQSxJQVBBLENBT0E7QUFDQTtBQUNBLE9BVEE7QUFVQSxLQTVVQTtBQTZVQTtBQUFBOztBQUNBOztBQUVBO0FBQUE7QUFBQTs7QUFFQTtBQUFBO0FBQUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUVBO0FBQ0EsZ0NBREE7QUFFQSw0QkFGQTtBQUdBO0FBSEE7QUFNQSx1REFDQSxJQURBLENBQ0E7QUFDQTtBQUNBLFNBSEEsV0FJQTtBQUNBO0FBQ0EsU0FOQTtBQVFBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxXQUZBO0FBR0EsU0FOQTtBQVFBO0FBQ0E7QUFDQSxzREFGQSxDQUlBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUVBO0FBQ0E7QUFDQTtBQUNBLFNBZEE7QUFnQkE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw2Q0FQQSxDQVFBOztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsV0FIQTtBQUlBLFNBZEE7QUFnQkE7QUFDQTtBQUNBLDhDQUZBLENBR0E7O0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFBQTtBQUFBO0FBQ0EsV0FIQTtBQUlBLFNBVEE7QUFVQSxPQTFFQSxFQTBFQTtBQUNBO0FBQ0E7O0FBQ0E7QUFDQSxPQTlFQTtBQStFQSxLQWphQTtBQW1hQTtBQUFBOztBQUNBO0FBQUE7O0FBRUE7QUFBQTtBQUFBO0FBQUE7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUVBO0FBRUE7QUFDQSw0R0FSQSxDQVVBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTs7QUFDQTtBQUNBO0FBQ0E7QUFFQSxXQVBBO0FBU0E7QUFDQTtBQUVBO0FBQ0EsV0FKQTtBQU1BO0FBQ0EsU0FqQkE7QUFtQkE7QUFDQTtBQUNBO0FBQ0E7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsV0FMQTtBQU9BO0FBQ0E7QUFDQSxXQUZBO0FBR0EsU0FmQTtBQWlCQTtBQUNBO0FBQ0E7QUFDQSxzREFIQSxDQUtBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FUQTtBQVVBLE9BdkVBLEVBdUVBO0FBQ0E7QUFDQSxPQXpFQTtBQTBFQSxLQWhmQTtBQWtmQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBRUE7QUFDQSwwQkFEQTtBQUVBLDRCQUZBO0FBR0E7QUFIQTtBQU1BLHFEQUNBLElBREEsQ0FDQTtBQUNBLDhCQURBLENBRUE7QUFDQTtBQUNBOztBQUNBLGtDQUxBLENBTUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFFQTtBQUNBO0FBQ0EsT0FwQkEsV0FxQkE7QUFDQTtBQUNBLE9BdkJBO0FBd0JBO0FBL2hCQTtBQXhFQSIsImZpbGUiOiIuL25vZGVfbW9kdWxlcy9iYWJlbC1sb2FkZXIvbGliL2luZGV4LmpzPyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmLmpzIiwic291cmNlc0NvbnRlbnQiOlsiPHRlbXBsYXRlPlxuICA8Y2FyZCBjbGFzcz1cInAtNiBtLTRcIj5cbiAgICA8ZGl2IGNsYXNzPVwicm93XCI+XG4gICAgICA8ZGl2IGNsYXNzPVwiY29sLWxnLTEyXCI+XG4gICAgICAgIDxoNCBjbGFzcz1cIm1iLTNcIj5cbiAgICAgICAgICBHbyBMaXZlXG4gICAgICAgIDwvaDQ+XG4gICAgICAgIDxwIGNsYXNzPVwibWItNVwiPlxuICAgICAgICAgIE5lY2Vzc2l0YXRpYnVzIGVpdXMgY29uc2VxdWF0dXIgZXggYWxpcXVpZCBmdWdhIGV1bSBxdWlkZW0uXG4gICAgICAgIDwvcD5cbiAgICAgIDwvZGl2PlxuICAgIDwvZGl2PlxuICAgIDxkaXYgY2xhc3M9XCJtYi0yXCI+XG4gICAgICA8ZGl2IGNsYXNzPVwidGV4dC1jZW50ZXJcIj5cbiAgICAgICAgPCEtLSBjaGF0IGJveCBzdGFydHMgaGVyZSAtLT5cbiAgICAgICAgPGRpdiBjbGFzcz1cImNvbnRhaW5lciBwYi0yXCI+XG4gICAgICAgICAgPGRpdiBjbGFzcz1cInJvdyBqdXN0aWZ5LWNvbnRlbnQtY2VudGVyXCI+XG4gICAgICAgICAgICA8ZGl2IGNsYXNzPVwiY29sLW1kLTEyXCI+XG4gICAgICAgICAgICAgIDxkaXYgY2xhc3M9XCJyb3dcIj5cbiAgICAgICAgICAgICAgICA8ZGl2IGNsYXNzPVwiY29sLW1kLTcgdmlkZW8tZGl2XCI+XG4gICAgICAgICAgICAgICAgICA8IS0tIHZpZGVvIGNoYXQgZGl2IGhlcmUgLS0+XG4gICAgICAgICAgICAgICAgICA8ZGl2IGNsYXNzPVwidmlkZW8gZ3JpZCBncmlkLWZsb3ctcm93IGJnLWJsYWNrXCI+XG4gICAgICAgICAgICAgICAgICAgIDxkaXYgaWQ9XCJteS12aWRlby1jaGF0LXdpbmRvd1wiIC8+XG4gICAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICA8ZGl2IGNsYXNzPVwiY29sLW1kLTVcIj5cbiAgICAgICAgICAgICAgICAgIDxkaXYgY2xhc3M9XCJjYXJkXCI+XG4gICAgICAgICAgICAgICAgICAgIDxkaXYgY2xhc3M9XCJ2aWV3ZXItaGVhZGVyIHB4LTIgcHktMVwiPlxuICAgICAgICAgICAgICAgICAgICAgIDxwIGNsYXNzPVwibS0wIHB4LTIgdmlld2Vyc1wiPlxuICAgICAgICAgICAgICAgICAgICAgICAgPHNwYW4gdi1zaG93PVwiY3VycmVudFN0YXR1cyA9PT0nT05fR09JTkcnXCI+IDxmYSBpY29uPVwiZXllXCIgLz4ge3sgdmlld2VyQ291bnQgfX0gPC9zcGFuPlxuICAgICAgICAgICAgICAgICAgICAgICAgPHNwYW4gdi1zaG93PVwiY3VycmVudFN0YXR1cyAhPT0nT05fR09JTkcnXCI+IE9mZmxpbmUgPC9zcGFuPlxuICAgICAgICAgICAgICAgICAgICAgIDwvcD5cbiAgICAgICAgICAgICAgICAgICAgPC9kaXY+XG4gICAgICAgICAgICAgICAgICAgIDxkaXYgY2xhc3M9XCJjYXJkLWJvZHkgcC0wXCI+XG4gICAgICAgICAgICAgICAgICAgICAgPGRpdiBjbGFzcz1cIm1lc3NhZ2UtYm94XCI+XG4gICAgICAgICAgICAgICAgICAgICAgICA8ZGl2IHYtc2hvdz1cInNob3dNZXNzYWdlc1wiIGNsYXNzPVwibWVzc2FnZS1kaXYgcC00XCI+XG4gICAgICAgICAgICAgICAgICAgICAgICAgIDxkaXYgdi1mb3I9XCJtZXNzYWdlIGluIHRjLm1lc3NhZ2VzQXJyYXlcIiA6a2V5PVwibWVzc2FnZS5pZFwiIGNsYXNzPVwicm93IG1zZ1wiPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxkaXYgdi1pZj1cIm1lc3NhZ2UuYXV0aG9yID09IHVzZXIudXNlcm5hbWVcIiBjbGFzcz1cIm1lZGlhLWJvZHlcIj5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxwIGNsYXNzPVwibWVzc2FnZS1ob3N0LWF1dGhvclwiPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7eyBtZXNzYWdlLmF1dGhvciB9fVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPC9wPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPGJyPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPHAgY2xhc3M9XCJtZXNzYWdlLWhvc3QtYm9keVwiPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7eyBtZXNzYWdlLmJvZHkgfX1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvcD5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICA8ZGl2IHYtZWxzZSBjbGFzcz1cIm1lZGlhLWJvZHlcIj5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxwIGNsYXNzPVwibWVzc2FnZS1hdXRob3JcIj5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAge3sgbWVzc2FnZS5hdXRob3IgfX1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvcD5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxicj5cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDxwIGNsYXNzPVwibWVzc2FnZS1ib2R5XCI+XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHt7IG1lc3NhZ2UuYm9keSB9fVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPC9wPlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIDwvZGl2PlxuICAgICAgICAgICAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICAgICAgICAgIDwvZGl2PlxuICAgICAgICAgICAgICAgICAgICAgICAgPHAgdi1pZj1cIm5vdGlmaWNhdGlvblwiPlxuICAgICAgICAgICAgICAgICAgICAgICAgICB7eyBub3RpZmljYXRpb25Nc2cgfX1cbiAgICAgICAgICAgICAgICAgICAgICAgIDwvcD5cbiAgICAgICAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICAgICAgICA8IS0tIDxpbnB1dCB2LWlmPVwidXNlck5vdEpvaW5lZFwiIGNsYXNzPVwiZm9ybS1jb250cm9sXCIgdHlwZT1cInRleHRcIiB2LW1vZGVsPVwidXNlcm5hbWVcIiB2LW9uOmtleXVwLjEzPVwiY29ubmVjdENsaWVudFdpdGhVc2VybmFtZVwiIHBsYWNlaG9sZGVyPVwiWW91ciB1c2VybmFtZVwiPiAtLT5cbiAgICAgICAgICAgICAgICAgICAgICA8aW5wdXQgdi1pZj1cIiF1c2VyTm90Sm9pbmVkICYmIGN1cnJlbnRTdGF0dXMgPT09J09OX0dPSU5HJ1wiIHYtbW9kZWw9XCJtZXNzYWdlXCIgY2xhc3M9XCJmb3JtLWNvbnRyb2xcIiB0eXBlPVwidGV4dFwiIHBsYWNlaG9sZGVyPVwiWW91ciBtZXNzYWdlXCIgQGtleXVwLjEzPVwiaGFuZGxlSW5wdXRUZXh0S2V5cHJlc3NcIj5cbiAgICAgICAgICAgICAgICAgICAgPC9kaXY+XG4gICAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICAgICAgPC9kaXY+XG4gICAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgICA8L2Rpdj5cbiAgICAgICAgPC9kaXY+XG4gICAgICAgIDwhLS0gPHN0YXItcmF0aW5nLz4gLS0+XG4gICAgICAgIDxkaXYgY2xhc3M9XCJtLTNcIj5cbiAgICAgICAgICA8Yi1idXR0b24gdi1pZj1cIiF1c2VyTm90Sm9pbmVkICYmIChsb2dnZWRVc2VyICE9PSB1c2VybmFtZSkgJiYgY3VycmVudFN0YXR1cyA9PT0nT05fR09JTkcnXCIgdmFyaWFudD1cInByaW1hcnlcIiBAY2xpY2s9XCIkYnZNb2RhbC5zaG93KCdyYXRlLW1vZGFsJyk7XCI+XG4gICAgICAgICAgICA8Yi1pY29uLXN0YXItZmlsbCAvPiBSYXRlIG1lXG4gICAgICAgICAgPC9iLWJ1dHRvbj5cbiAgICAgICAgPC9kaXY+XG4gICAgICAgIDxkaXY+XG4gICAgICAgICAgPGJ1dHRvblxuICAgICAgICAgICAgdi1zaG93PVwiY3VycmVudFN0YXR1cyAhPT0nT05fR09JTkcnICYmIChsb2dnZWRVc2VyID09PSB0Yy51c2VybmFtZSlcIlxuICAgICAgICAgICAgY2xhc3M9XCJicm9hZGNhc3QgYnRuIGJ0bi1kYW5nZXIgYnRuLWxnXCJcbiAgICAgICAgICAgIEBjbGljaz1cImdldFZpZGVvVG9rZW4oKTsgY29ubmVjdENsaWVudFdpdGhVc2VybmFtZSgpO1wiXG4gICAgICAgICAgPlxuICAgICAgICAgICAgU3RhcnQgQnJvYWRjYXN0aW5nXG4gICAgICAgICAgPC9idXR0b24+XG4gICAgICAgICAgPGJ1dHRvblxuICAgICAgICAgICAgdi1pZj1cImN1cnJlbnRTdGF0dXMgPT09J09OX0dPSU5HJyAmJiAhdXNlck5vdEpvaW5lZFwiXG4gICAgICAgICAgICBjbGFzcz1cImJ0biBidG4tZGFuZ2VyIGJ0bi1sZ1wiXG4gICAgICAgICAgICBAY2xpY2s9XCJzdG9wQnJvYWRjYXN0aW5nKCk7XCJcbiAgICAgICAgICA+XG4gICAgICAgICAgICBTdG9wIEJyb2FkY2FzdGluZ1xuICAgICAgICAgIDwvYnV0dG9uPlxuICAgICAgICA8L2Rpdj5cbiAgICAgIDwvZGl2PlxuICAgIDwvZGl2PlxuXG4gICAgPCEtLSBNT0RBTCBIRVJFIC0tPlxuICAgIDxiLW1vZGFsIGlkPVwicmF0ZS1tb2RhbFwiIGhpZGUtZm9vdGVyPlxuICAgICAgPHRlbXBsYXRlICNtb2RhbC10aXRsZT5cbiAgICAgICAgPHNwYW4gY2xhc3M9XCJoMyB0ZXh0LWNlbnRlclwiPiBSYXRlICA8c3Ryb25nPiB7eyB1c2VybmFtZSB9fSA8L3N0cm9uZz4gPC9zcGFuPlxuICAgICAgPC90ZW1wbGF0ZT5cbiAgICAgIDxkaXYgY2xhc3M9XCJkLWJsb2NrIHRleHQtY2VudGVyXCI+XG4gICAgICAgIDxiLXJvdyBjbGFzcz1cInAtMyB0ZXh0LWNlbnRlclwiPlxuICAgICAgICAgIDxiLWNvbD5cbiAgICAgICAgICAgIDxzdGFyLXJhdGluZyB2LW1vZGVsPVwicmF0aW5nQ291bnRcIiAvPlxuICAgICAgICAgIDwvYi1jb2w+XG4gICAgICAgIDwvYi1yb3c+XG4gICAgICAgIDxiLXJvdyBjbGFzcz1cInAtMlwiPlxuICAgICAgICAgIDxiLWNvbCBjbGFzcz1cImQtZmxleCBqdXN0aWZ5LWNvbnRlbnQtY2VudGVyXCI+XG4gICAgICAgICAgICA8Yi1idXR0b25cbiAgICAgICAgICAgICAgdmFyaWFudD1cImxpbmtcIlxuICAgICAgICAgICAgICBzaXplPVwic21cIlxuICAgICAgICAgICAgICBAY2xpY2s9XCIoKT0+e1xuICAgICAgICAgICAgICAgICRidk1vZGFsLmhpZGUoJ3JhdGUtbW9kYWwnKTtcbiAgICAgICAgICAgICAgfVwiXG4gICAgICAgICAgICA+XG4gICAgICAgICAgICAgIENhbmNlbFxuICAgICAgICAgICAgPC9iLWJ1dHRvbj5cblxuICAgICAgICAgICAgPGItYnV0dG9uXG4gICAgICAgICAgICAgIHZhcmlhbnQ9XCJkYW5nZXJcIlxuICAgICAgICAgICAgICBzaXplPVwic21cIlxuICAgICAgICAgICAgICBjbGFzcz1cImZsb2F0LXJpZ2h0XCJcbiAgICAgICAgICAgICAgQGNsaWNrPVwiKCk9PntcbiAgICAgICAgICAgICAgICBoYW5kbGVTdWJtaXRSYXRpbmcoKTtcbiAgICAgICAgICAgICAgICAkYnZNb2RhbC5oaWRlKCdyYXRlLW1vZGFsJyk7XG4gICAgICAgICAgICAgIH1cIlxuICAgICAgICAgICAgPlxuICAgICAgICAgICAgICBTdWJtaXRcbiAgICAgICAgICAgIDwvYi1idXR0b24+XG4gICAgICAgICAgPC9iLWNvbD5cbiAgICAgICAgPC9iLXJvdz5cbiAgICAgIDwvZGl2PlxuICAgIDwvYi1tb2RhbD5cbiAgPC9jYXJkPlxuPC90ZW1wbGF0ZT5cblxuPHNjcmlwdD5cbmltcG9ydCB7IG1hcEdldHRlcnMgfSBmcm9tICd2dWV4J1xuaW1wb3J0IFN0YXJSYXRpbmcgZnJvbSAndnVlLXN0YXItcmF0aW5nJ1xuaW1wb3J0IHsgc3dhbE9vcHMsIHN3YWxTdWNjZXNzIH0gZnJvbSAnLi4vLi4vLi4vaGVscGVycydcbnZhciBtb21lbnQgPSByZXF1aXJlKCdtb21lbnQnKVxuY29uc3QgYXhpb3MgPSByZXF1aXJlKCdheGlvcycpXG5jb25zdCBfID0gcmVxdWlyZSgnbG9kYXNoJylcblxuZXhwb3J0IGRlZmF1bHQge1xuICBuYW1lOiAnVmlkZW9DaGF0JyxcblxuICBjb21wb25lbnRzOiB7XG4gICAgU3RhclJhdGluZ1xuICB9LFxuXG4gIGRhdGE6IGZ1bmN0aW9uICgpIHtcbiAgICByZXR1cm4ge1xuICAgICAgdGM6IHtcbiAgICAgICAgYWNjZXNzTWFuYWdlcjogbnVsbCxcbiAgICAgICAgbWVzc2FnaW5nQ2xpZW50OiBudWxsLFxuICAgICAgICBjaGFubmVsOiBbXSxcbiAgICAgICAgdXNlcm5hbWU6ICcnLFxuICAgICAgICBjaGFubmVsQXJyYXk6IFtdLFxuICAgICAgICBjdXJyZW50Q2hhbm5lbDogbnVsbCxcbiAgICAgICAgZ2VuZXJhbENoYW5uZWw6IG51bGwsXG4gICAgICAgIGFjdGl2ZUNoYW5uZWxJbmRleDogbnVsbCxcbiAgICAgICAgbWVzc2FnZXNBcnJheTogW11cbiAgICAgIH0sXG4gICAgICB1c2VybmFtZTogJycsXG4gICAgICBjb25uZWN0ZWQ6IGZhbHNlLFxuICAgICAgc2VsZWN0ZWQ6IGZhbHNlLFxuICAgICAgc2hvd01lc3NhZ2VzOiBmYWxzZSxcbiAgICAgIG1vbWVudDogbW9tZW50LFxuICAgICAgbWVzc2FnZTogbnVsbCxcbiAgICAgIHVzZXJOb3RKb2luZWQ6IHRydWUsXG4gICAgICBuZXdDaGFubmVsOiAnJyxcbiAgICAgIHNob3dBZGRDaGFubmVsSW5wdXQ6IGZhbHNlLFxuICAgICAgbm90aWZpY2F0aW9uOiBmYWxzZSxcbiAgICAgIG5vdGlmaWNhdGlvbk1zZzogJycsXG4gICAgICBhY2Nlc3NUb2tlbjogJycsXG4gICAgICByb29tU2lkOiAnJyxcbiAgICAgIGRhdGFTaWQ6ICcnLFxuICAgICAgbmFtZTogdGhpcy4kcm91dGUucGFyYW1zLnJvb21OYW1lLFxuICAgICAgY3VycmVudFN0YXR1czogJ25vdC1zdGFydGVkJyxcbiAgICAgIHZpZGVvUm9vbTogW10sXG4gICAgICB2aWV3ZXJDb3VudDogMCxcbiAgICAgIHNob3dSYXRlTW9kYWw6IGZhbHNlLFxuICAgICAgcmF0aW5nQ291bnQ6IDAsXG4gICAgICByb29tSWQ6ICcnLFxuICAgICAgbG9nZ2VkVXNlcjogJydcbiAgICB9XG4gIH0sXG5cbiAgY29tcHV0ZWQ6IG1hcEdldHRlcnMoe1xuICAgIHVzZXI6ICdhdXRoL3VzZXInXG4gIH0pLFxuXG4gIGJlZm9yZU1vdW50OiBmdW5jdGlvbiAoKSB7XG4gICAgY29uc29sZS5sb2coJ3RoaXMudXNlci51c2VybmFtZScsIHRoaXMudXNlcilcbiAgICAvLyBBU1NJR05JTkcgVVNFUk5BTUVcbiAgICB0aGlzLmxvZ2dlZFVzZXIgPSB0aGlzLnVzZXI/LnVzZXJuYW1lID8gdGhpcy51c2VyPy51c2VybmFtZSA6ICcnXG4gICAgdGhpcy51c2VyID8gdGhpcy5jb25uZWN0Q2xpZW50V2l0aFVzZXJuYW1lKCkgOiB0aGlzLmpvaW5Bc1BhcnRpY2lwYW50KClcblxuICAgIC8vIENIRUNLSU5HIElGIEJST0FEQ0FTVCBJUyBPTkdPSU5HXG5cbiAgICBheGlvcy5nZXQoJy9hcGkvdmlkZW8vJyArIHRoaXMubmFtZSlcbiAgICAgIC50aGVuKChyZXNwb25zZSkgPT4ge1xuICAgICAgICBpZiAocmVzcG9uc2UuZGF0YS5zdWNjZXNzKSB7XG4gICAgICAgICAgdGhpcy5yb29tSWQgPSByZXNwb25zZS5kYXRhLmRhdGEuaWRcbiAgICAgICAgICB0aGlzLmRhdGFTaWQgPSByZXNwb25zZS5kYXRhLmRhdGEucm9vbV9zaWRcbiAgICAgICAgICB0aGlzLmN1cnJlbnRTdGF0dXMgPSByZXNwb25zZS5kYXRhLmRhdGEucm9vbV9zdGF0dXNcbiAgICAgICAgICAvLyB2bS51c2VybmFtZSAhPT0gdm0ubmFtZSA/IHRoaXMuam9pbkFzUGFydGljaXBhbnQoKSA6IHRoaXMuam9pbkFzUGFydGljaXBhbnQoKTtcbiAgICAgICAgfVxuICAgICAgfSlcbiAgICAgIC5jYXRjaCgoZXJyKSA9PiB7XG4gICAgICAgIGNvbnNvbGUubG9nKGVyci5yZXNwb25zZSlcbiAgICAgIH0pXG4gICAgICAvLyB0aGlzLmNvbm5lY3RDbGllbnRXaXRoVXNlcm5hbWUoKTtcbiAgfSxcblxuICBtZXRob2RzOiB7XG5cbiAgICAvLyBNT0RBTCBNRVRIT0RTXG5cbiAgICByZXNldFJhdGluZ0Zvcm1zICgpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcbiAgICAgIHZtLnJhdGluZ0NvdW50ID0gMFxuICAgIH0sXG5cbiAgICBoYW5kbGVTdWJtaXRSYXRpbmcgKCkge1xuICAgICAgbGV0IHZtID0gdGhpc1xuXG4gICAgICBpZiAoIXRoaXMudXNlcikge1xuICAgICAgICBzd2FsT29wcygnWW91IGhhdmUgdG8gbG9naW4gZm9yIHlvdSB0byByYXRlIHRoZSBob3N0LicpXG4gICAgICB9XG5cbiAgICAgIGxldCBkYXRhID0ge1xuICAgICAgICAncmVmZXJlbmNlX2lkJzogdm0ucm9vbUlkLFxuICAgICAgICAnY2F0ZWdvcnknOiAnTElWRScsXG4gICAgICAgICdyYXRlJzogdm0ucmF0aW5nQ291bnRcbiAgICAgIH1cblxuICAgICAgYXhpb3MucG9zdChgL2FwaS9yYXRpbmcvc2F2ZWAsIGRhdGEpLnRoZW4oKHJlc3BvbnNlKSA9PiB7XG4gICAgICAgIHN3YWxTdWNjZXNzKCdSYXRpbmcgc3VibWl0dGVkIScpXG4gICAgICAgIHRoaXMucmVzZXRSYXRpbmdGb3JtcygpXG4gICAgICB9KVxuICAgIH0sXG5cbiAgICAvLyBDSEFUIE1FVEhPRFNcbiAgICBjb25uZWN0Q2xpZW50V2l0aFVzZXJuYW1lICgpIHtcbiAgICAgIGlmICh0aGlzLmxvZ2dlZFVzZXIpIHtcbiAgICAgICAgdGhpcy50Yy51c2VybmFtZSA9IHRoaXMubG9nZ2VkVXNlclxuICAgICAgICB0aGlzLnVzZXJOb3RKb2luZWQgPSBmYWxzZVxuICAgICAgICBheGlvcy5nZXQoJy9hcGkvdmlkZW8vdmlldy8nICsgdGhpcy5uYW1lKVxuXG4gICAgICAgIHRoaXMuZmV0Y2hBY2Nlc3NUb2tlbih0aGlzLnRjLnVzZXJuYW1lLCB0aGlzLmNvbm5lY3RNZXNzYWdpbmdDbGllbnQpXG4gICAgICAgIGNvbnNvbGUubG9nKCdVU0VSTkFNRScsIHRoaXMudGMudXNlcm5hbWUpXG4gICAgICB9IGVsc2Uge1xuICAgICAgICBhbGVydCgnTk9UIExPR0dFRCBJTicpXG4gICAgICB9XG4gICAgfSxcbiAgICBmZXRjaEFjY2Vzc1Rva2VuICh1c2VybmFtZSwgaGFuZGxlcikge1xuICAgICAgYXhpb3MucG9zdCgnL2FwaS92aWRlby9jaGF0Jywge1xuICAgICAgICBpZGVudGl0eTogdXNlcm5hbWUsXG4gICAgICAgIGRldmljZTogJ2Jyb3dzZXInXG4gICAgICB9KVxuICAgICAgICAudGhlbihmdW5jdGlvbiAocmVzcG9uc2UpIHtcbiAgICAgICAgICBoYW5kbGVyKHJlc3BvbnNlLmRhdGEpXG4gICAgICAgIH0pXG4gICAgICAgIC5jYXRjaChmdW5jdGlvbiAoZXJyb3IpIHtcbiAgICAgICAgICBjb25zb2xlLmxvZyhlcnJvcilcbiAgICAgICAgfSlcbiAgICB9LFxuICAgIGNvbm5lY3RNZXNzYWdpbmdDbGllbnQgKHRva2VuKSB7XG4gICAgICAvLyBJbml0aWFsaXplIHRoZSBDaGF0IG1lc3NhZ2luZyBjbGllbnRcbiAgICAgIGxldCB2bSA9IHRoaXNcblxuICAgICAgdm0udGMuYWNjZXNzTWFuYWdlciA9IG5ldyBUd2lsaW8uQWNjZXNzTWFuYWdlcih0b2tlbilcblxuICAgICAgVHdpbGlvLkNoYXQuQ2xpZW50LmNyZWF0ZSh0b2tlbikudGhlbihmdW5jdGlvbiAoY2xpZW50KSB7XG4gICAgICAgIHZtLnRjLm1lc3NhZ2luZ0NsaWVudCA9IGNsaWVudFxuICAgICAgICB2bS51cGRhdGVDb25uZWN0ZWRVSSgpXG4gICAgICAgIHZtLmxvYWRDaGFubmVsTGlzdCh2bS5qb2luR2VuZXJhbENoYW5uZWwpXG4gICAgICAgIHZtLnRjLm1lc3NhZ2luZ0NsaWVudC5vbignY2hhbm5lbEFkZGVkJywgXy50aHJvdHRsZSh2bS5sb2FkQ2hhbm5lbExpc3QpKVxuICAgICAgICB2bS50Yy5tZXNzYWdpbmdDbGllbnQub24oJ2NoYW5uZWxSZW1vdmVkJywgXy50aHJvdHRsZSh2bS5sb2FkQ2hhbm5lbExpc3QpKVxuICAgICAgICB2bS50Yy5tZXNzYWdpbmdDbGllbnQub24oJ3Rva2VuRXhwaXJlZCcsIHZtLnJlZnJlc2hUb2tlbilcbiAgICAgIH0pXG4gICAgfSxcbiAgICB1cGRhdGVDb25uZWN0ZWRVSSAoKSB7XG4gICAgICB0aGlzLmNvbm5lY3RlZCA9IHRydWVcbiAgICB9LFxuICAgIHJlZnJlc2hUb2tlbiAoKSB7XG4gICAgICB0aGlzLmZldGNoQWNjZXNzVG9rZW4odGhpcy50Yy51c2VybmFtZSwgdGhpcy5zZXROZXdUb2tlbilcbiAgICB9LFxuICAgIHNldE5ld1Rva2VuICh0b2tlblJlc3BvbnNlKSB7XG4gICAgICB0aGlzLnRjLmFjY2Vzc01hbmFnZXIudXBkYXRlVG9rZW4odG9rZW5SZXNwb25zZS50b2tlbilcbiAgICB9LFxuICAgIGxvYWRDaGFubmVsTGlzdCAoaGFuZGxlcikge1xuICAgICAgaWYgKHRoaXMudGMubWVzc2FnaW5nQ2xpZW50ID09PSB1bmRlZmluZWQpIHtcbiAgICAgICAgY29uc29sZS5sb2coJ0NsaWVudCBpcyBub3QgaW5pdGlhbGl6ZWQnKVxuICAgICAgICByZXR1cm5cbiAgICAgIH1cbiAgICAgIHRoaXMuZ2V0VmlzaWJsZUNoYW5uZWxzKHRoaXMudGMubWVzc2FnaW5nQ2xpZW50LCBoYW5kbGVyKVxuICAgIH0sXG4gICAgZ2V0VmlzaWJsZUNoYW5uZWxzIChtZXNzYWdpbmdDbGllbnQsIGhhbmRsZXIpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcblxuICAgICAgbWVzc2FnaW5nQ2xpZW50LmdldFB1YmxpY0NoYW5uZWxEZXNjcmlwdG9ycygpLnRoZW4oZnVuY3Rpb24gKGNoYW5uZWxzKSB7XG4gICAgICAgIHZtLnRjLmNoYW5uZWxBcnJheSA9IHZtLnNvcnRDaGFubmVsc0J5TmFtZShjaGFubmVscy5pdGVtcylcblxuICAgICAgICB2bS50Yy5jaGFubmVsQXJyYXkuZm9yRWFjaCh2bS5hZGRDaGFubmVsKVxuICAgICAgICBpZiAodHlwZW9mIGhhbmRsZXIgPT09ICdmdW5jdGlvbicpIHtcbiAgICAgICAgICBoYW5kbGVyKClcbiAgICAgICAgfVxuICAgICAgfSlcbiAgICB9LFxuICAgIHNvcnRDaGFubmVsc0J5TmFtZSAoY2hhbm5lbHMpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcblxuICAgICAgcmV0dXJuIGNoYW5uZWxzLnNvcnQoZnVuY3Rpb24gKGEsIGIpIHtcbiAgICAgICAgaWYgKGEuZnJpZW5kbHlOYW1lID09PSB2bS5uYW1lKSB7XG4gICAgICAgICAgcmV0dXJuIC0xXG4gICAgICAgIH1cbiAgICAgICAgaWYgKGIuZnJpZW5kbHlOYW1lID09PSB2bS5uYW1lKSB7XG4gICAgICAgICAgcmV0dXJuIDFcbiAgICAgICAgfVxuICAgICAgICByZXR1cm4gYS5mcmllbmRseU5hbWUubG9jYWxlQ29tcGFyZShiLmZyaWVuZGx5TmFtZSlcbiAgICAgIH0pXG4gICAgfSxcbiAgICBqb2luR2VuZXJhbENoYW5uZWwgKCkge1xuICAgICAgbGV0IHZtID0gdGhpc1xuICAgICAgY29uc29sZS5sb2coJ0F0dGVtcHRpbmcgdG8gam9pbiBcImdlbmVyYWxcIiBjaGF0IGNoYW5uZWwuLi4nLCB2bS5uYW1lKVxuICAgICAgaWYgKHZtLnRjLmdlbmVyYWxDaGFubmVsID09PSBudWxsKSB7XG4gICAgICAgIC8vIElmIGl0IGRvZXNuJ3QgZXhpc3QsIGxldCdzIGNyZWF0ZSBpdFxuICAgICAgICB2bS50Yy5tZXNzYWdpbmdDbGllbnQuY3JlYXRlQ2hhbm5lbCh7XG4gICAgICAgICAgdW5pcXVlTmFtZTogdm0ubmFtZSxcbiAgICAgICAgICBmcmllbmRseU5hbWU6IHZtLm5hbWVcbiAgICAgICAgfSkudGhlbihmdW5jdGlvbiAoY2hhbm5lbCkge1xuICAgICAgICAgIHZtLnRjLmdlbmVyYWxDaGFubmVsID0gY2hhbm5lbFxuICAgICAgICAgIHZtLmxvYWRDaGFubmVsTGlzdCh2bS5qb2luR2VuZXJhbENoYW5uZWwpXG4gICAgICAgIH0pXG4gICAgICB9IGVsc2Uge1xuICAgICAgICBjb25zb2xlLmxvZygnRm91bmQgZ2VuZXJhbCBjaGFubmVsOicsIHZtLnRjLmdlbmVyYWxDaGFubmVsKVxuICAgICAgICB2bS5zZXR1cENoYW5uZWwodm0udGMuZ2VuZXJhbENoYW5uZWwpXG4gICAgICB9XG4gICAgfSxcbiAgICBhZGRDaGFubmVsIChjaGFubmVsKSB7XG4gICAgICBsZXQgdm0gPSB0aGlzXG4gICAgICBpZiAoY2hhbm5lbC51bmlxdWVOYW1lID09PSB2bS5uYW1lKSB7XG4gICAgICAgIHRoaXMudGMuZ2VuZXJhbENoYW5uZWwgPSBjaGFubmVsXG4gICAgICB9XG4gICAgfSxcbiAgICBzZXR1cENoYW5uZWwgKGNoYW5uZWwpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcbiAgICAgIHJldHVybiB2bS5sZWF2ZUN1cnJlbnRDaGFubmVsKClcbiAgICAgICAgLnRoZW4oZnVuY3Rpb24gKCkge1xuICAgICAgICAgIHJldHVybiB2bS5pbml0Q2hhbm5lbChjaGFubmVsKVxuICAgICAgICB9KVxuICAgICAgICAudGhlbihmdW5jdGlvbiAoX2NoYW5uZWwpIHtcbiAgICAgICAgICB2bS50Yy5jdXJyZW50Q2hhbm5lbCA9IF9jaGFubmVsXG4gICAgICAgICAgdm0ubG9hZE1lc3NhZ2VzKClcbiAgICAgICAgICByZXR1cm4gdm0uam9pbkNoYW5uZWwoX2NoYW5uZWwpXG4gICAgICAgIH0pXG4gICAgICAgIC50aGVuKHZtLmluaXRDaGFubmVsRXZlbnRzKVxuICAgIH0sXG4gICAgbGVhdmVDdXJyZW50Q2hhbm5lbCAoKSB7XG4gICAgICBsZXQgdm0gPSB0aGlzXG4gICAgICBpZiAodGhpcy50Yy5jdXJyZW50Q2hhbm5lbCkge1xuICAgICAgICByZXR1cm4gdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5sZWF2ZSgpLnRoZW4oZnVuY3Rpb24gKGxlZnRDaGFubmVsKSB7XG4gICAgICAgICAgY29uc29sZS5sb2coJ2xlZnQgJyArIGxlZnRDaGFubmVsLmZyaWVuZGx5TmFtZSlcbiAgICAgICAgICBsZWZ0Q2hhbm5lbC5yZW1vdmVMaXN0ZW5lcignbWVzc2FnZUFkZGVkJywgdm0uYWRkTWVzc2FnZVRvTGlzdClcbiAgICAgICAgICBsZWZ0Q2hhbm5lbC5yZW1vdmVMaXN0ZW5lcigndHlwaW5nU3RhcnRlZCcsIHZtLnNob3dUeXBpbmdTdGFydGVkKVxuICAgICAgICAgIGxlZnRDaGFubmVsLnJlbW92ZUxpc3RlbmVyKCd0eXBpbmdFbmRlZCcsIHZtLmhpZGVUeXBpbmdTdGFydGVkKVxuICAgICAgICAgIGxlZnRDaGFubmVsLnJlbW92ZUxpc3RlbmVyKCdtZW1iZXJKb2luZWQnLCB2bS5ub3RpZnlNZW1iZXJKb2luZWQpXG4gICAgICAgICAgbGVmdENoYW5uZWwucmVtb3ZlTGlzdGVuZXIoJ21lbWJlckxlZnQnLCB2bS5ub3RpZnlNZW1iZXJMZWZ0KVxuICAgICAgICB9KVxuICAgICAgfSBlbHNlIHtcbiAgICAgICAgY29uc29sZS5sb2coJ3Jlc29sdmluZycpXG4gICAgICAgIHJldHVybiBQcm9taXNlLnJlc29sdmUoKVxuICAgICAgfVxuICAgIH0sXG4gICAgaW5pdENoYW5uZWwgKGNoYW5uZWwpIHtcbiAgICAgIGNvbnNvbGUubG9nKCdJbml0aWFsaXplZCBjaGFubmVsICcgKyBjaGFubmVsLmZyaWVuZGx5TmFtZSlcbiAgICAgIHJldHVybiB0aGlzLnRjLm1lc3NhZ2luZ0NsaWVudC5nZXRDaGFubmVsQnlTaWQoY2hhbm5lbC5zaWQpXG4gICAgfSxcbiAgICBpbml0Q2hhbm5lbEV2ZW50cyAoKSB7XG4gICAgICBjb25zb2xlLmxvZyh0aGlzLnRjLmN1cnJlbnRDaGFubmVsLmZyaWVuZGx5TmFtZSArICcgcmVhZHkuJylcbiAgICAgIHRoaXMudGMuY3VycmVudENoYW5uZWwub24oJ21lc3NhZ2VBZGRlZCcsIHRoaXMuYWRkTWVzc2FnZVRvTGlzdClcbiAgICAgIHRoaXMudGMuY3VycmVudENoYW5uZWwub24oJ3R5cGluZ1N0YXJ0ZWQnLCB0aGlzLnNob3dUeXBpbmdTdGFydGVkKVxuICAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5vbigndHlwaW5nRW5kZWQnLCB0aGlzLmhpZGVUeXBpbmdTdGFydGVkKVxuICAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5vbignbWVtYmVySm9pbmVkJywgdGhpcy5ub3RpZnlNZW1iZXJKb2luZWQpXG4gICAgICB0aGlzLnRjLmN1cnJlbnRDaGFubmVsLm9uKCdtZW1iZXJMZWZ0JywgdGhpcy5ub3RpZnlNZW1iZXJMZWZ0KVxuICAgICAgLy8gJGlucHV0VGV4dC5wcm9wKCdkaXNhYmxlZCcsIGZhbHNlKS5mb2N1cygpO1xuICAgIH0sXG4gICAgc2hvd1R5cGluZ1N0YXJ0ZWQgKG1lbWJlcikge1xuICAgICAgY29uc29sZS5sb2cobWVtYmVyLmlkZW50aXR5ICsgJyBpcyB0eXBpbmcuLi4nKVxuICAgICAgdGhpcy5ub3RpZmljYXRpb25Nc2cgPSBtZW1iZXIuaWRlbnRpdHkgKyAnIGlzIHR5cGluZy4uLidcbiAgICAgIHRoaXMubm90aWZpY2F0aW9uID0gdHJ1ZVxuICAgIH0sXG4gICAgaGlkZVR5cGluZ1N0YXJ0ZWQgKG1lbWJlcikge1xuICAgICAgdGhpcy5ub3RpZmljYXRpb25Nc2cgPSAnJ1xuICAgICAgdGhpcy5ub3RpZmljYXRpb24gPSBmYWxzZVxuICAgIH0sXG4gICAgbm90aWZ5TWVtYmVySm9pbmVkIChtZW1iZXIpIHtcbiAgICAgIGNvbnNvbGUubG9nKCdqb2luaW5nJylcbiAgICAgIGNvbnNvbGUubG9nKG1lbWJlci5pZGVudGl0eSArICcgam9pbmVkIHRoZSBjaGFubmVsJylcbiAgICAgIC8vIG5vdGlmeShtZW1iZXIuaWRlbnRpdHkgKyAnIGpvaW5lZCB0aGUgY2hhbm5lbCcpXG4gICAgfSxcbiAgICBub3RpZnlNZW1iZXJMZWZ0IChtZW1iZXIpIHtcbiAgICAgIGNvbnNvbGUubG9nKCdsZWF2aW5nJylcbiAgICAgIGNvbnNvbGUubG9nKG1lbWJlcilcbiAgICAgIGNvbnNvbGUubG9nKG1lbWJlci5pZGVudGl0eSArICcgbGVmdCB0aGUgY2hhbm5lbCcpXG4gICAgICAvLyBub3RpZnkobWVtYmVyLmlkZW50aXR5ICsgJyBsZWZ0IHRoZSBjaGFubmVsJyk7XG4gICAgfSxcbiAgICBub3RpZnkgKG1lc3NhZ2UpIHtcbiAgICAgIHZhciByb3cgPSAkKCc8ZGl2PicpLmFkZENsYXNzKCdjb2wtbWQtMTInKVxuICAgICAgcm93LmxvYWRUZW1wbGF0ZSgnI21lbWJlci1ub3RpZmljYXRpb24tdGVtcGxhdGUnLCB7XG4gICAgICAgIHN0YXR1czogbWVzc2FnZVxuICAgICAgfSlcbiAgICAgIHRoaXMudGMuJG1lc3NhZ2VMaXN0LmFwcGVuZChyb3cpXG4gICAgfSxcbiAgICBqb2luQ2hhbm5lbCAoX2NoYW5uZWwpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcbiAgICAgIHJldHVybiBfY2hhbm5lbC5qb2luKClcbiAgICAgICAgLnRoZW4oZnVuY3Rpb24gKGpvaW5lZENoYW5uZWwpIHtcbiAgICAgICAgICBjb25zb2xlLmxvZygnSm9pbmVkIGNoYW5uZWwgJyArIGpvaW5lZENoYW5uZWwuZnJpZW5kbHlOYW1lKVxuICAgICAgICAgIC8vIHZtLnVwZGF0ZUNoYW5uZWxVSShfY2hhbm5lbCk7XG4gICAgICAgICAgdm0udGMuY3VycmVudENoYW5uZWwgPSBfY2hhbm5lbFxuICAgICAgICAgIHZtLmxvYWRNZXNzYWdlcygpXG4gICAgICAgICAgcmV0dXJuIGpvaW5lZENoYW5uZWxcbiAgICAgICAgfSlcbiAgICAgICAgLmNhdGNoKGZ1bmN0aW9uIChlcnIpIHtcbiAgICAgICAgICBjb25zb2xlLndhcm4oJ2NvdWxkdCBqb2luIGNoYW5uZWwnICsgX2NoYW5uZWwuZnJpZW5kbHlOYW1lICsgJyBiZWNhdXNlICcgKyBlcnIpXG4gICAgICAgICAgLy8gYWxlcnQoXCJDb3VsZG4ndCBqb2luIGNoYW5uZWwgXCIgKyBfY2hhbm5lbC5mcmllbmRseU5hbWUgKyAnIGJlY2F1c2UgJyArIGVycik7XG4gICAgICAgIH0pXG4gICAgfSxcbiAgICAvLyB1cGRhdGVDaGFubmVsVUkoc2VsZWN0ZWRDaGFubmVsKSB7XG4gICAgLy8gICAgIGxldCBjaGFubmVsTGlzdHMgPSB0aGlzLiRyZWZzLmNoYW5uZWxMaXN0O1xuXG4gICAgLy8gICAgIGxldCBhY3RpdmVDaGFubmVsTGlzdCA9IGNoYW5uZWxMaXN0cy5maWx0ZXIoZnVuY3Rpb24oZWxlbWVudCkge1xuICAgIC8vICAgICByZXR1cm4gZWxlbWVudC5kYXRhc2V0LnNpZCA9PT0gc2VsZWN0ZWRDaGFubmVsLnNpZDtcbiAgICAvLyAgICAgfSk7XG5cbiAgICAvLyAgICAgYWN0aXZlQ2hhbm5lbExpc3QgPSBhY3RpdmVDaGFubmVsTGlzdFswXTtcbiAgICAvLyAgICAgaWYgKHRoaXMudGMuY3VycmVudENoYW5uZWxDb250YWluZXIgPT09IHVuZGVmaW5lZCAmJiBzZWxlY3RlZENoYW5uZWwuZnJpZW5kbHlOYW1lID09PSB2bS5uYW1lKSB7XG5cbiAgICAvLyAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbENvbnRhaW5lciA9IGFjdGl2ZUNoYW5uZWxMaXN0O1xuICAgIC8vICAgICB9XG5cbiAgICAvLyAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbENvbnRhaW5lci5jbGFzc0xpc3QucmVtb3ZlKCdzZWxlY3RlZC1jaGFubmVsJyk7XG4gICAgLy8gICAgIHRoaXMudGMuY3VycmVudENoYW5uZWxDb250YWluZXIgPSBhY3RpdmVDaGFubmVsTGlzdDtcbiAgICAvLyAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbENvbnRhaW5lci5jbGFzc0xpc3QuYWRkKCdzZWxlY3RlZC1jaGFubmVsJyk7XG4gICAgLy8gfSxcbiAgICBsb2FkTWVzc2FnZXMgKCkge1xuICAgICAgbGV0IHZtID0gdGhpc1xuICAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5nZXRNZXNzYWdlcyg1MCkudGhlbihmdW5jdGlvbiAobWVzc2FnZXMpIHtcbiAgICAgICAgdm0uc2hvd01lc3NhZ2VzID0gdHJ1ZVxuICAgICAgICB2bS50Yy5tZXNzYWdlc0FycmF5ID0gbWVzc2FnZXMuaXRlbXNcbiAgICAgICAgLy8gdm0udXNlck5vdEpvaW5lZCA9IGZhbHNlXG4gICAgICAgIG1lc3NhZ2VzLml0ZW1zLmZvckVhY2godm0uYWRkTWVzc2FnZVRvTGlzdClcbiAgICAgIH0pXG4gICAgfSxcbiAgICBhZGRNZXNzYWdlVG9MaXN0IChtZXNzYWdlKSB7XG4gICAgICBjb25zb2xlLmxvZyhtZXNzYWdlKVxuICAgICAgdGhpcy5sb2FkTWVzc2FnZXMoKVxuICAgIH0sXG4gICAgaGFuZGxlSW5wdXRUZXh0S2V5cHJlc3MgKCkge1xuICAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5zZW5kTWVzc2FnZSh0aGlzLm1lc3NhZ2UpXG4gICAgICB0aGlzLm1lc3NhZ2UgPSAnJ1xuICAgICAgc2V0VGltZW91dChmdW5jdGlvbiAoKSB7XG4gICAgICAgIHRoaXMubG9hZE1lc3NhZ2VzKClcbiAgICAgIH0sIDMwMDApXG4gICAgfSxcbiAgICBoYW5kbGVOZXdDaGFubmVsSW5wdXRLZXlwcmVzcyAoZXZlbnQpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcbiAgICAgIGlmICh0aGlzLm5ld0NoYW5uZWwgPT0gJycpIHtcbiAgICAgICAgYWxlcnQoJ0NoYW5uZWwgbmFtZSBjYW5ub3QgYmUgZW1wdHknKVxuICAgICAgICByZXR1cm5cbiAgICAgIH1cbiAgICAgIHRoaXMudGMubWVzc2FnaW5nQ2xpZW50LmNyZWF0ZUNoYW5uZWwoe1xuICAgICAgICBmcmllbmRseU5hbWU6IHRoaXMubmV3Q2hhbm5lbFxuICAgICAgfSkudGhlbihmdW5jdGlvbiAoY2hhbm5lbCkge1xuICAgICAgICBjb25zb2xlLmxvZygnQ3JlYXRlZCBjaGFubmVsJylcbiAgICAgICAgdm0ubG9hZENoYW5uZWxMaXN0KGNoYW5uZWwpXG4gICAgICB9KS50aGVuKHRoaXMuaGlkZUFkZENoYW5uZWxJbnB1dClcbiAgICAgIHRoaXMubmV3Q2hhbm5lbCA9ICcnXG4gICAgfSxcbiAgICBzZWxlY3RDaGFubmVsIChjaGFubmVsKSB7XG4gICAgICBsZXQgY2hhbm5lbFNpZCA9IGNoYW5uZWwuc2lkXG4gICAgICB2YXIgc2VsZWN0ZWRDaGFubmVsID0gdGhpcy50Yy5jaGFubmVsQXJyYXkuZmlsdGVyKGZ1bmN0aW9uIChjaGFubmVsKSB7XG4gICAgICAgIHJldHVybiBjaGFubmVsLnNpZCA9PT0gY2hhbm5lbFNpZFxuICAgICAgfSlbMF1cbiAgICAgIGlmIChzZWxlY3RlZENoYW5uZWwgPT09IHRoaXMudGMuY3VycmVudENoYW5uZWwpIHtcbiAgICAgICAgcmV0dXJuXG4gICAgICB9XG4gICAgICB0aGlzLnNldHVwQ2hhbm5lbChzZWxlY3RlZENoYW5uZWwpXG4gICAgfSxcbiAgICBoaWRlQWRkQ2hhbm5lbElucHV0ICgpIHtcbiAgICAgIHRoaXMuc2hvd0FkZENoYW5uZWxJbnB1dCA9IGZhbHNlXG4gICAgfSxcbiAgICBjcmVhdGVDaGFubmVsICgpIHtcbiAgICAgIHRoaXMuc2hvd0FkZENoYW5uZWxJbnB1dCA9IHRydWVcbiAgICB9LFxuICAgIGRlbGV0ZUNoYW5uZWwgKCkge1xuICAgICAgLy8gaWYgKHRoaXMudGMuY3VycmVudENoYW5uZWwuc2lkID09PSB0aGlzLnRjLmdlbmVyYWxDaGFubmVsLnNpZCkge1xuICAgICAgLy8gICAgIGFsZXJ0KCdZb3UgY2Fubm90IGRlbGV0ZSB0aGUgZ2VuZXJhbCBjaGFubmVsJyk7XG4gICAgICAvLyAgICAgcmV0dXJuO1xuICAgICAgLy8gfVxuICAgICAgdGhpcy50Yy5jdXJyZW50Q2hhbm5lbC5kZWxldGUoKS50aGVuKGZ1bmN0aW9uIChjaGFubmVsKSB7XG4gICAgICAgIGNvbnNvbGUubG9nKCdjaGFubmVsOiAnICsgY2hhbm5lbC5mcmllbmRseU5hbWUgKyAnIGRlbGV0ZWQnKVxuICAgICAgICAvLyBzZXR1cENoYW5uZWwodGhpcy50Yy5nZW5lcmFsQ2hhbm5lbCk7XG4gICAgICB9KVxuICAgIH0sXG5cbiAgICAvLyBWSURFTyBNRVRIT0RTXG4gICAgZ2V0VmlkZW9Ub2tlbjogZnVuY3Rpb24gKCkge1xuICAgICAgY29uc29sZS5sb2coJ1ZpZGVvIGNoYXQgcm9vbSBsb2FkaW5nLi4uJylcblxuICAgICAgY29uc3Qgdm0gPSB0aGlzXG5cbiAgICAgIC8vIFJlcXVlc3QgYSBuZXcgdG9rZW5cbiAgICAgIGF4aW9zLmdldChgL2FwaS92aWRlby9hY2Nlc3NfdG9rZW4vJHt0aGlzLm5hbWV9YClcbiAgICAgICAgLnRoZW4oZnVuY3Rpb24gKHJlc3BvbnNlKSB7XG4gICAgICAgICAgdm0uYWNjZXNzVG9rZW4gPSByZXNwb25zZS5kYXRhXG4gICAgICAgICAgdm0uY3VycmVudFN0YXR1cyA9ICdPTl9HT0lORydcbiAgICAgICAgfSlcbiAgICAgICAgLmNhdGNoKGZ1bmN0aW9uIChlcnJvcikge1xuICAgICAgICAgIGNvbnNvbGUubG9nKGVycm9yKVxuICAgICAgICB9KVxuICAgICAgICAudGhlbihmdW5jdGlvbiAoKSB7XG4gICAgICAgICAgdm0uY29ubmVjdFRvUm9vbSgpXG4gICAgICAgIH0pXG4gICAgfSxcbiAgICBqb2luQXNQYXJ0aWNpcGFudDogZnVuY3Rpb24gKCkge1xuICAgICAgY29uc29sZS5sb2coJ1ZpZGVvIGNoYXQgcm9vbSBsb2FkaW5nLi4uJylcblxuICAgICAgY29uc3Qgdm0gPSB0aGlzXG4gICAgICB2bS50Yy51c2VybmFtZSA9IHZtLm5hbWVcbiAgICAgIC8vIHZtLmZldGNoQWNjZXNzVG9rZW4odm0ubmFtZSwgdm0uY29ubmVjdE1lc3NhZ2luZ0NsaWVudClcbiAgICAgIGNvbnNvbGUubG9nKCdVU0VSTkFNRScsIHZtLm5hbWUpXG5cbiAgICAgIC8vIFJlcXVlc3QgYSBuZXcgdG9rZW5cbiAgICAgIGF4aW9zLmdldChgL2FwaS92aWRlby9hY2Nlc3NfdG9rZW4vJHt2bS5uYW1lfWApXG4gICAgICAgIC50aGVuKGZ1bmN0aW9uIChyZXNwb25zZSkge1xuICAgICAgICAgIHZtLmFjY2Vzc1Rva2VuID0gcmVzcG9uc2UuZGF0YVxuICAgICAgICB9KVxuICAgICAgICAuY2F0Y2goZnVuY3Rpb24gKGVycm9yKSB7XG4gICAgICAgICAgY29uc29sZS5sb2coZXJyb3IpXG4gICAgICAgIH0pXG4gICAgICAgIC50aGVuKGZ1bmN0aW9uICgpIHtcbiAgICAgICAgICB2bS5qb2luVG9Sb29tKClcbiAgICAgICAgfSlcbiAgICB9LFxuICAgIGNvbm5lY3RUb1Jvb206IGZ1bmN0aW9uICgpIHtcbiAgICAgIGNvbnN0IGF4aW9zID0gcmVxdWlyZSgnYXhpb3MnKVxuXG4gICAgICBjb25zdCB7IGNvbm5lY3QsIGNyZWF0ZUxvY2FsVHJhY2tzIH0gPSByZXF1aXJlKCd0d2lsaW8tdmlkZW8nKVxuXG4gICAgICBjb25uZWN0KHRoaXMuYWNjZXNzVG9rZW4sIHsgbmFtZTogdGhpcy5uYW1lIH0pLnRoZW4ocm9vbSA9PiB7XG4gICAgICAgIGNvbnNvbGUubG9nKGBTdWNjZXNzZnVsbHkgam9pbmVkIGEgUm9vbTogJHtyb29tfWApXG4gICAgICAgIGNvbnNvbGUubG9nKCdEYXRhOjonLCByb29tLnNpZClcbiAgICAgICAgdGhpcy5kYXRhU2lkID0gcm9vbS5zaWRcbiAgICAgICAgdGhpcy52aWRlb1Jvb20gPSByb29tXG5cbiAgICAgICAgbGV0IHJlcXVlc3QgPSB7XG4gICAgICAgICAgcm9vbV9uYW1lOiB0aGlzLm5hbWUsXG4gICAgICAgICAgcm9vbV9zaWQ6IHJvb20uc2lkLFxuICAgICAgICAgIHJvb21fc3RhdHVzOiAnT05fR09JTkcnXG4gICAgICAgIH1cblxuICAgICAgICBheGlvcy5wb3N0KGAvYXBpL3ZpZGVvL2hpc3Rvcnkvc2F2ZWAsIHJlcXVlc3QpXG4gICAgICAgICAgLnRoZW4oKHJlc3BvbnNlKSA9PiB7XG4gICAgICAgICAgICBjb25zb2xlLmxvZyhyZXNwb25zZSlcbiAgICAgICAgICB9KVxuICAgICAgICAgIC5jYXRjaCgoZXJyKSA9PiB7XG4gICAgICAgICAgICBjb25zb2xlLmxvZyhlcnIpXG4gICAgICAgICAgfSlcblxuICAgICAgICBjb25zdCB2aWRlb0NoYXRXaW5kb3cgPSBkb2N1bWVudC5nZXRFbGVtZW50QnlJZCgnbXktdmlkZW8tY2hhdC13aW5kb3cnKVxuICAgICAgICB0aGlzLnZpZXdlckNvdW50ID0gcm9vbS5wYXJ0aWNpcGFudHMuc2l6ZVxuXG4gICAgICAgIGxldCBsb2NhbFRyYWNrXG4gICAgICAgIGNyZWF0ZUxvY2FsVHJhY2tzKCkudGhlbih0cmFjayA9PiB7XG4gICAgICAgICAgY29uc29sZS5sb2codHJhY2spXG4gICAgICAgICAgbG9jYWxUcmFjayA9IHRyYWNrXG4gICAgICAgICAgdHJhY2suZm9yRWFjaCgobWVkaWEpID0+IHtcbiAgICAgICAgICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZChtZWRpYS5hdHRhY2goKSlcbiAgICAgICAgICB9KVxuICAgICAgICB9KVxuXG4gICAgICAgIHJvb20ub24oJ3BhcnRpY2lwYW50Q29ubmVjdGVkJywgcGFydGljaXBhbnQgPT4ge1xuICAgICAgICAgIGNvbnNvbGUubG9nKGBQYXJ0aWNpcGFudCBcIiR7cGFydGljaXBhbnQuaWRlbnRpdHl9XCIgY29ubmVjdGVkYClcbiAgICAgICAgICB0aGlzLnZpZXdlckNvdW50ID0gcm9vbS5wYXJ0aWNpcGFudHMuc2l6ZVxuXG4gICAgICAgICAgLy8gcGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAgIC8vICAgICBpZiAocHVibGljYXRpb24uaXNTdWJzY3JpYmVkKSB7XG4gICAgICAgICAgLy8gICAgICAgICBjb25zdCB0cmFjayA9IHB1YmxpY2F0aW9uLnRyYWNrO1xuICAgICAgICAgIC8vICAgICAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKTtcbiAgICAgICAgICAvLyAgICAgfVxuICAgICAgICAgIC8vIH0pO1xuXG4gICAgICAgICAgLy8gcGFydGljaXBhbnQub24oJ3RyYWNrU3Vic2NyaWJlZCcsIHRyYWNrID0+IHtcbiAgICAgICAgICAvLyAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKTtcbiAgICAgICAgICAvLyB9KTtcbiAgICAgICAgfSlcblxuICAgICAgICByb29tLm9uKCdkaXNjb25uZWN0ZWQnLCByb29tID0+IHtcbiAgICAgICAgICAvLyBEZXRhY2ggdGhlIGxvY2FsIG1lZGlhIGVsZW1lbnRzXG4gICAgICAgICAgY29uc29sZS5sb2coJ0hvc3QgZGlzY29ubmVjdGVkJylcbiAgICAgICAgICBjb25zb2xlLmxvZygnbG9jYWxQYXJ0aWNpcGFudCcsIHJvb20ubG9jYWxQYXJ0aWNpcGFudClcbiAgICAgICAgICBjb25zb2xlLmxvZygndmlkZW9DaGF0V2luZG93JywgdmlkZW9DaGF0V2luZG93LmNoaWxkTm9kZXNbMF0pXG4gICAgICAgICAgdGhpcy52aWV3ZXJDb3VudCA9IHJvb20ucGFydGljaXBhbnRzLnNpemVcbiAgICAgICAgICBjb25zdCBjaGlsZCA9IHZpZGVvQ2hhdFdpbmRvdy5sYXN0RWxlbWVudENoaWxkXG4gICAgICAgICAgdmlkZW9DaGF0V2luZG93LnJlbW92ZUNoaWxkKGNoaWxkKVxuICAgICAgICAgIC8vIHZpZGVvQ2hhdFdpbmRvdy5pbm5lckhUTUwgPVwiXCI7XG4gICAgICAgICAgY29uc29sZS5sb2coJ0RDIFRSQUNLUycsIGxvY2FsVHJhY2spXG4gICAgICAgICAgbG9jYWxUcmFjay5mb3JFYWNoKHRyYWNrID0+IHtcbiAgICAgICAgICAgIHRyYWNrLnN0b3AoKVxuICAgICAgICAgICAgdHJhY2suZGV0YWNoKClcbiAgICAgICAgICB9KVxuICAgICAgICB9KVxuXG4gICAgICAgIHJvb20ub24oJ3BhcnRpY2lwYW50RGlzY29ubmVjdGVkJywgcm9vbSA9PiB7XG4gICAgICAgICAgLy8gRGV0YWNoIHRoZSBsb2NhbCBtZWRpYSBlbGVtZW50c1xuICAgICAgICAgIGNvbnNvbGUubG9nKCdTb21lb25lIGRpc2Nvbm5lY3RlZCcpXG4gICAgICAgICAgLy8gdGhpcy52aWV3ZXJDb3VudCA9IHRoaXMudmlld2VyQ291bnQgLSAxXG4gICAgICAgICAgdGhpcy52aWV3ZXJDb3VudCA9IHJvb20ucGFydGljaXBhbnRzLnNpemVcbiAgICAgICAgICByb29tLmxvY2FsUGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAgICAgY29uc3QgYXR0YWNoZWRFbGVtZW50cyA9IHB1YmxpY2F0aW9uLnRyYWNrLmRldGFjaCgpXG4gICAgICAgICAgICBhdHRhY2hlZEVsZW1lbnRzLmZvckVhY2goZWxlbWVudCA9PiBlbGVtZW50LnJlbW92ZSgpKVxuICAgICAgICAgIH0pXG4gICAgICAgIH0pXG4gICAgICB9LCBlcnJvciA9PiB7XG4gICAgICAgIGNvbnNvbGUuZXJyb3IoYFVuYWJsZSB0byBjb25uZWN0IHRvIFJvb206ICR7ZXJyb3IubWVzc2FnZX1gKVxuICAgICAgICBzd2FsT29wcyhgUGxlYXNlIG1ha2Ugc3VyZSB0aGF0IHlvdXIgY2FtZXJhIGFuZCBtaWNyb3Bob25lIGlzIGNvbm5lY3RlZCwgYW5kIGhhdmUgcGVybWlzc2lvbnNgKVxuICAgICAgICB0aGlzLnN0b3BCcm9hZGNhc3RpbmcoKVxuICAgICAgfSlcbiAgICB9LFxuXG4gICAgam9pblRvUm9vbTogZnVuY3Rpb24gKCkge1xuICAgICAgY29uc3QgeyBjb25uZWN0IH0gPSByZXF1aXJlKCd0d2lsaW8tdmlkZW8nKVxuXG4gICAgICBjb25uZWN0KHRoaXMuYWNjZXNzVG9rZW4sIHsgbmFtZTogdGhpcy5uYW1lLCB2aWRlbzogZmFsc2UsIGF1ZGlvOiBmYWxzZSB9KS50aGVuKHJvb20gPT4ge1xuICAgICAgICBjb25zb2xlLmxvZyhgU3VjY2Vzc2Z1bGx5IGpvaW5lZCBhIFJvb206ICR7cm9vbX1gKVxuICAgICAgICBjb25zb2xlLmxvZygnRGF0YTo6Jywgcm9vbS5zaWQpXG4gICAgICAgIHRoaXMuZGF0YVNpZCA9IHJvb20uc2lkXG5cbiAgICAgICAgY29uc3QgdmlkZW9DaGF0V2luZG93ID0gZG9jdW1lbnQuZ2V0RWxlbWVudEJ5SWQoJ215LXZpZGVvLWNoYXQtd2luZG93JylcblxuICAgICAgICBjb25zdCBsb2NhbFBhcnRpY2lwYW50ID0gcm9vbS5sb2NhbFBhcnRpY2lwYW50XG4gICAgICAgIGNvbnNvbGUubG9nKGBDb25uZWN0ZWQgdG8gdGhlIFJvb20gYXMgTG9jYWxQYXJ0aWNpcGFudCBcIiR7bG9jYWxQYXJ0aWNpcGFudC5pZGVudGl0eX1cImApXG5cbiAgICAgICAgLy8gcm9vbS5vbigncGFydGljaXBhbnRDb25uZWN0ZWQnLCBwYXJ0aWNpcGFudCA9PiB7XG4gICAgICAgIC8vICAgY29uc29sZS5sb2coYFBhcnRpY2lwYW50IFwiJHtwYXJ0aWNpcGFudC5pZGVudGl0eX1cIiBjb25uZWN0ZWRgKVxuXG4gICAgICAgIC8vICAgcGFydGljaXBhbnQudHJhY2tzLmZvckVhY2gocHVibGljYXRpb24gPT4ge1xuICAgICAgICAvLyAgICAgaWYgKHB1YmxpY2F0aW9uLmlzU3Vic2NyaWJlZCkge1xuICAgICAgICAvLyAgICAgICBjb25zdCB0cmFjayA9IHB1YmxpY2F0aW9uLnRyYWNrXG4gICAgICAgIC8vICAgICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZCh0cmFjay5hdHRhY2goKSlcbiAgICAgICAgLy8gICAgIH1cbiAgICAgICAgLy8gICB9KVxuXG4gICAgICAgIC8vICAgcGFydGljaXBhbnQub24oJ3RyYWNrU3Vic2NyaWJlZCcsIHRyYWNrID0+IHtcbiAgICAgICAgLy8gICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZCh0cmFjay5hdHRhY2goKSlcbiAgICAgICAgLy8gICB9KVxuICAgICAgICAvLyB9KVxuXG4gICAgICAgIHJvb20ucGFydGljaXBhbnRzLmZvckVhY2gocGFydGljaXBhbnQgPT4ge1xuICAgICAgICAgIHBhcnRpY2lwYW50LnRyYWNrcy5mb3JFYWNoKHB1YmxpY2F0aW9uID0+IHtcbiAgICAgICAgICAgIGNvbnNvbGUubG9nKCdkZXRhaWwnLCBwdWJsaWNhdGlvbilcbiAgICAgICAgICAgIGNvbnNvbGUubG9nKCdraW5kJywgcHVibGljYXRpb24ua2luZClcbiAgICAgICAgICAgIGlmIChwdWJsaWNhdGlvbi5raW5kID09PSAndmlkZW8nKSB7XG4gICAgICAgICAgICAgIHZpZGVvQ2hhdFdpbmRvdy5hcHBlbmRDaGlsZChwdWJsaWNhdGlvbi5hdHRhY2goKSlcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgIH0pXG5cbiAgICAgICAgICBwYXJ0aWNpcGFudC5vbigndHJhY2tTdWJzY3JpYmVkJywgdHJhY2sgPT4ge1xuICAgICAgICAgICAgY29uc29sZS5sb2coJ3RyYWNrU3Vic2NyaWJlZCcsIHRyYWNrKVxuXG4gICAgICAgICAgICB2aWRlb0NoYXRXaW5kb3cuYXBwZW5kQ2hpbGQodHJhY2suYXR0YWNoKCkpXG4gICAgICAgICAgfSlcblxuICAgICAgICAgIHRoaXMudmlld2VyQ291bnQgPSByb29tLnBhcnRpY2lwYW50cy5zaXplXG4gICAgICAgIH0pXG5cbiAgICAgICAgcm9vbS5vbigncGFydGljaXBhbnRDb25uZWN0ZWQnLCBwYXJ0aWNpcGFudCA9PiB7XG4gICAgICAgICAgY29uc29sZS5sb2coJ25ldycpXG4gICAgICAgICAgdGhpcy52aWV3ZXJDb3VudCA9IHJvb20ucGFydGljaXBhbnRzLnNpemVcbiAgICAgICAgICBjb25zb2xlLmxvZyhgUGFydGljaXBhbnQgXCIke3BhcnRpY2lwYW50LmlkZW50aXR5fVwiIGNvbm5lY3RlZGApXG5cbiAgICAgICAgICBwYXJ0aWNpcGFudC50cmFja3MuZm9yRWFjaChwdWJsaWNhdGlvbiA9PiB7XG4gICAgICAgICAgICBpZiAocHVibGljYXRpb24uaXNTdWJzY3JpYmVkKSB7XG4gICAgICAgICAgICAgIGNvbnN0IHRyYWNrID0gcHVibGljYXRpb24udHJhY2tcbiAgICAgICAgICAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKVxuICAgICAgICAgICAgfVxuICAgICAgICAgIH0pXG5cbiAgICAgICAgICBwYXJ0aWNpcGFudC5vbigndHJhY2tTdWJzY3JpYmVkJywgdHJhY2sgPT4ge1xuICAgICAgICAgICAgdmlkZW9DaGF0V2luZG93LmFwcGVuZENoaWxkKHRyYWNrLmF0dGFjaCgpKVxuICAgICAgICAgIH0pXG4gICAgICAgIH0pXG5cbiAgICAgICAgcm9vbS5vbigncGFydGljaXBhbnREaXNjb25uZWN0ZWQnLCByb29tID0+IHtcbiAgICAgICAgICAvLyBEZXRhY2ggdGhlIGxvY2FsIG1lZGlhIGVsZW1lbnRzXG4gICAgICAgICAgY29uc29sZS5sb2coJ1NvbWVvbmUgZGlzY29ubmVjdGVkJylcbiAgICAgICAgICB0aGlzLnZpZXdlckNvdW50ID0gdGhpcy52aWV3ZXJDb3VudCAtIDFcblxuICAgICAgICAgIC8vIHJvb20ucGFydGljaXBhbnRzLnRyYWNrcy5mb3JFYWNoKHB1YmxpY2F0aW9uID0+IHtcbiAgICAgICAgICAvLyAgIGNvbnN0IGF0dGFjaGVkRWxlbWVudHMgPSBwdWJsaWNhdGlvbi50cmFjay5kZXRhY2goKVxuICAgICAgICAgIC8vICAgYXR0YWNoZWRFbGVtZW50cy5mb3JFYWNoKGVsZW1lbnQgPT4gZWxlbWVudC5yZW1vdmUoKSlcbiAgICAgICAgICAvLyB9KVxuICAgICAgICB9KVxuICAgICAgfSwgZXJyb3IgPT4ge1xuICAgICAgICBjb25zb2xlLmVycm9yKGBVbmFibGUgdG8gY29ubmVjdCB0byBSb29tOiAke2Vycm9yLm1lc3NhZ2V9YClcbiAgICAgIH0pXG4gICAgfSxcblxuICAgIHN0b3BCcm9hZGNhc3Rpbmc6IGZ1bmN0aW9uICgpIHtcbiAgICAgIGxldCB2bSA9IHRoaXNcbiAgICAgIHZtLmFjY2Vzc1Rva2VuID0gJydcbiAgICAgIHZtLmN1cnJlbnRTdGF0dXMgPSAnQ09NUExFVEVEJ1xuICAgICAgdm0udXNlck5vdEpvaW5lZCA9IHRydWVcbiAgICAgIHZtLnNob3dNZXNzYWdlcyA9IGZhbHNlXG4gICAgICB2bS5kZWxldGVDaGFubmVsKClcbiAgICAgIHZtLnRjLmFjY2Vzc01hbmFnZXIgPSBudWxsXG4gICAgICB2bS50Yy5tZXNzYWdpbmdDbGllbnQgPSBudWxsXG4gICAgICB2bS50Yy5jaGFubmVsID0gW11cbiAgICAgIHZtLnRjLmNoYW5uZWxBcnJheSA9IG51bGxcbiAgICAgIHZtLnRjLmdlbmVyYWxDaGFubmVsID0gbnVsbFxuICAgICAgdm0udGMuYWN0aXZlQ2hhbm5lbEluZGV4ID0gbnVsbFxuICAgICAgdm0udGMubWVzc2FnZXNBcnJheSA9IFtdXG5cbiAgICAgIGxldCByZXF1ZXN0ID0ge1xuICAgICAgICByb29tX25hbWU6IHZtLm5hbWUsXG4gICAgICAgIHJvb21fc2lkOiB2bS5kYXRhU2lkLFxuICAgICAgICByb29tX3N0YXR1czogJ0NPTVBMRVRFRCdcbiAgICAgIH1cblxuICAgICAgYXhpb3MucG9zdChgL2FwaS92aWRlby9oaXN0b3J5L3NhdmVgLCByZXF1ZXN0KVxuICAgICAgICAudGhlbigocmVzcG9uc2UpID0+IHtcbiAgICAgICAgICBjb25zb2xlLmxvZyhyZXNwb25zZSlcbiAgICAgICAgICAvLyB2bS5jdXJyZW50U3RhdHVzID0gJ0NPTVBMRVRFRCdcbiAgICAgICAgICAvLyB2bS51c2VyTm90Sm9pbmVkID0gdHJ1ZVxuICAgICAgICAgIC8vIHZtLnNob3dNZXNzYWdlcyA9IGZhbHNlXG4gICAgICAgICAgdm0udmlkZW9Sb29tLmRpc2Nvbm5lY3QoKVxuICAgICAgICAgIC8vIHZtLmRlbGV0ZUNoYW5uZWwoKVxuICAgICAgICAgIC8vIHZtLnVzZXJuYW1lID0gdm0udXNlcj8udXNlcm5hbWUgPyB2bS51c2VyPy51c2VybmFtZSA6ICcnXG4gICAgICAgICAgLy8gdm0udGMuYWNjZXNzTWFuYWdlciA9IG51bGxcbiAgICAgICAgICAvLyB2bS50Yy5tZXNzYWdpbmdDbGllbnQgPSBudWxsXG4gICAgICAgICAgLy8gdm0udGMuY2hhbm5lbCA9IFtdXG4gICAgICAgICAgLy8gdm0udGMudXNlcm5hbWUgPSAnJztcbiAgICAgICAgICAvLyB2bS50Yy5jaGFubmVsQXJyYXkgPSBudWxsXG4gICAgICAgICAgLy8gdm0udGMuZ2VuZXJhbENoYW5uZWwgPSBudWxsXG4gICAgICAgICAgLy8gdm0udGMuYWN0aXZlQ2hhbm5lbEluZGV4ID0gbnVsbFxuICAgICAgICAgIC8vIHZtLnRjLm1lc3NhZ2VzQXJyYXkgPSBbXVxuXG4gICAgICAgICAgLy8gbGlzdC5yZW1vdmVDaGlsZChsaXN0LmNoaWxkTm9kZXMpO1xuICAgICAgICAgIC8vIGNvbnNvbGUubG9nKFwiQ09OU09MRSBMSVNUXCIsIGxpc3QuY2hpbGROb2Rlcyk7XG4gICAgICAgIH0pXG4gICAgICAgIC5jYXRjaCgoZXJyKSA9PiB7XG4gICAgICAgICAgY29uc29sZS5sb2coZXJyKVxuICAgICAgICB9KVxuICAgIH1cblxuICB9XG59XG48L3NjcmlwdD5cbjxzdHlsZT5cbi52aWRlb3tcbiAgICBmbG9hdDpsZWZ0O1xufVxuXG4ubWVzc2FnZS1ib3h7XG4gICAgaGVpZ2h0OiA0MTBweDtcbn1cblxuLm1lc3NhZ2UtZGl2e1xuICAgIGhlaWdodDogNDEwcHg7XG4gICAgd2lkdGg6MTAwJTtcbiAgICBvdmVyZmxvdy15OiBzY3JvbGw7XG59XG5cbi5icm9hZGNhc3R7XG4gICAgZGlzcGxheTpncmlkO1xuICAgIG1hcmdpbjphdXRvO1xufVxuXG4udmlkZW8tZGl2e1xuICAgIHRleHQtYWxpZ246IGNlbnRlcjtcbiAgICBoZWlnaHQ6IDUwMHB4O1xufVxuXG4ubWVzc2FnZS1ob3N0LWJvZHl7XG4gICAgZm9udC1zaXplOiAxNHB4O1xuICAgIGNvbG9yOndoaXRlO1xuICAgIGJhY2tncm91bmQtY29sb3I6ICMzNzNFNEM7XG4gICAgYm9yZGVyLXJhZGl1czogMTBweDtcbiAgICBmbG9hdDpyaWdodDtcbiAgICBwYWRkaW5nOiA1cHggMTVweDtcbiAgICB0ZXh0LWFsaWduOmxlZnQ7XG4gICAgbWFyZ2luLWJvdHRvbTogMjBweDtcbn1cblxuLm1lc3NhZ2UtaG9zdC1hdXRob3J7XG4gICAgZm9udC1zaXplOiAxMnB4O1xuICAgIGNvbG9yOmdyYXk7XG4gICAgZmxvYXQ6cmlnaHQ7XG4gICAgbWFyZ2luLWJvdHRvbTogMHB4O1xufVxuXG4ubWVzc2FnZS10aW1le1xuICAgIGZvbnQtc2l6ZTogMTJweDtcbiAgICBjb2xvcjpncmF5O1xuICAgIGZsb2F0OnJpZ2h0O1xuICAgIG1hcmdpbi1ib3R0b206IDIwcHg7XG59XG5cbi5tZXNzYWdlLWJvZHl7XG4gICAgZm9udC1zaXplOiAxNHB4O1xuICAgIGNvbG9yOmJsYWNrO1xuICAgIGJhY2tncm91bmQtY29sb3I6ICNFNEU2RUI7XG4gICAgYm9yZGVyLXJhZGl1czogMTBweDtcbiAgICBmbG9hdDpsZWZ0O1xuICAgIHBhZGRpbmc6IDVweCAxNXB4O1xuICAgIHRleHQtYWxpZ246bGVmdDtcbiAgICBtYXJnaW4tYm90dG9tOiAyMHB4O1xufVxuXG4ubWVzc2FnZS1hdXRob3J7XG4gICAgZm9udC1zaXplOiAxMnB4O1xuICAgIGNvbG9yOmdyYXk7XG4gICAgZmxvYXQ6bGVmdDtcbiAgICBtYXJnaW4tYm90dG9tOiAwcHg7XG59XG5cbi5tZXNzYWdlLXRpbWV7XG4gICAgZm9udC1zaXplOiAxMnB4O1xuICAgIGNvbG9yOmdyYXk7XG4gICAgZmxvYXQ6bGVmdDtcbiAgICBtYXJnaW4tYm90dG9tOiAyMHB4O1xufVxuXG4udmlkZW97XG4gICAgY29udGFpbjpjb3Zlcjtcbn1cblxuLnZpZXdlci1oZWFkZXJ7XG4gICAgYm9yZGVyLWJvdHRvbTogMXB4IHNvbGlkICNERkRGREY7XG4gICAgdGV4dC1hbGlnbjogbGVmdDtcbn1cblxuLnZpZXdlcnN7XG4gICAgY29sb3I6d2hpdGU7XG4gICAgYmFja2dyb3VuZC1jb2xvcjogI0RDMzU0NTtcbiAgICB3aWR0aDogNzBweDtcbiAgICB0ZXh0LWFsaWduOmNlbnRlcjtcbiAgICBib3JkZXItcmFkaXVzOiA1cHg7XG59XG5cbi8qIHdpZHRoICovXG46Oi13ZWJraXQtc2Nyb2xsYmFyIHtcbiAgd2lkdGg6IDEwcHg7XG59XG5cbi8qIFRyYWNrICovXG46Oi13ZWJraXQtc2Nyb2xsYmFyLXRyYWNrIHtcbiAgYmFja2dyb3VuZDogI2YxZjFmMTtcbn1cblxuLyogSGFuZGxlICovXG46Oi13ZWJraXQtc2Nyb2xsYmFyLXRodW1iIHtcbiAgYmFja2dyb3VuZDogIzg4ODtcbn1cblxuLyogSGFuZGxlIG9uIGhvdmVyICovXG46Oi13ZWJraXQtc2Nyb2xsYmFyLXRodW1iOmhvdmVyIHtcbiAgYmFja2dyb3VuZDogIzU1NTtcbn1cblxuPC9zdHlsZT5cbiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&": /*!********************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/css-loader??ref--6-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css& ***! \********************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("exports = module.exports = __webpack_require__(/*! ../../../../../node_modules/css-loader/lib/css-base.js */ \"./node_modules/css-loader/lib/css-base.js\")(false);\n// imports\n\n\n// module\nexports.push([module.i, \"\\n.video{\\n float:left;\\n}\\n.message-box{\\n height: 410px;\\n}\\n.message-div{\\n height: 410px;\\n width:100%;\\n overflow-y: scroll;\\n}\\n.broadcast{\\n display:grid;\\n margin:auto;\\n}\\n.video-div{\\n text-align: center;\\n height: 500px;\\n}\\n.message-host-body{\\n font-size: 14px;\\n color:white;\\n background-color: #373E4C;\\n border-radius: 10px;\\n float:right;\\n padding: 5px 15px;\\n text-align:left;\\n margin-bottom: 20px;\\n}\\n.message-host-author{\\n font-size: 12px;\\n color:gray;\\n float:right;\\n margin-bottom: 0px;\\n}\\n.message-time{\\n font-size: 12px;\\n color:gray;\\n float:right;\\n margin-bottom: 20px;\\n}\\n.message-body{\\n font-size: 14px;\\n color:black;\\n background-color: #E4E6EB;\\n border-radius: 10px;\\n float:left;\\n padding: 5px 15px;\\n text-align:left;\\n margin-bottom: 20px;\\n}\\n.message-author{\\n font-size: 12px;\\n color:gray;\\n float:left;\\n margin-bottom: 0px;\\n}\\n.message-time{\\n font-size: 12px;\\n color:gray;\\n float:left;\\n margin-bottom: 20px;\\n}\\n.video{\\n contain:cover;\\n}\\n.viewer-header{\\n border-bottom: 1px solid #DFDFDF;\\n text-align: left;\\n}\\n.viewers{\\n color:white;\\n background-color: #DC3545;\\n width: 70px;\\n text-align:center;\\n border-radius: 5px;\\n}\\n\\n/* width */\\n::-webkit-scrollbar {\\n width: 10px;\\n}\\n\\n/* Track */\\n::-webkit-scrollbar-track {\\n background: #f1f1f1;\\n}\\n\\n/* Handle */\\n::-webkit-scrollbar-thumb {\\n background: #888;\\n}\\n\\n/* Handle on hover */\\n::-webkit-scrollbar-thumb:hover {\\n background: #555;\\n}\\n\\n\", \"\"]);\n\n// exports\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/ZmZjNCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSwyQkFBMkIsbUJBQU8sQ0FBQyx5R0FBd0Q7QUFDM0Y7OztBQUdBO0FBQ0EsY0FBYyxRQUFTLFlBQVksaUJBQWlCLEdBQUcsZUFBZSxvQkFBb0IsR0FBRyxlQUFlLG9CQUFvQixpQkFBaUIseUJBQXlCLEdBQUcsYUFBYSxtQkFBbUIsa0JBQWtCLEdBQUcsYUFBYSx5QkFBeUIsb0JBQW9CLEdBQUcscUJBQXFCLHNCQUFzQixrQkFBa0IsZ0NBQWdDLDBCQUEwQixrQkFBa0Isd0JBQXdCLHNCQUFzQiwwQkFBMEIsR0FBRyx1QkFBdUIsc0JBQXNCLGlCQUFpQixrQkFBa0IseUJBQXlCLEdBQUcsZ0JBQWdCLHNCQUFzQixpQkFBaUIsa0JBQWtCLDBCQUEwQixHQUFHLGdCQUFnQixzQkFBc0Isa0JBQWtCLGdDQUFnQywwQkFBMEIsaUJBQWlCLHdCQUF3QixzQkFBc0IsMEJBQTBCLEdBQUcsa0JBQWtCLHNCQUFzQixpQkFBaUIsaUJBQWlCLHlCQUF5QixHQUFHLGdCQUFnQixzQkFBc0IsaUJBQWlCLGlCQUFpQiwwQkFBMEIsR0FBRyxTQUFTLG9CQUFvQixHQUFHLGlCQUFpQix1Q0FBdUMsdUJBQXVCLEdBQUcsV0FBVyxrQkFBa0IsZ0NBQWdDLGtCQUFrQix3QkFBd0IseUJBQXlCLEdBQUcsc0NBQXNDLGdCQUFnQixHQUFHLDRDQUE0Qyx3QkFBd0IsR0FBRyw2Q0FBNkMscUJBQXFCLEdBQUcsNERBQTRELHFCQUFxQixHQUFHOztBQUU1bUQiLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9pbmRleC5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi9ub2RlX21vZHVsZXMvcG9zdGNzcy1sb2FkZXIvc3JjL2luZGV4LmpzPyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8hLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/dnVlJnR5cGU9c3R5bGUmaW5kZXg9MCZsYW5nPWNzcyYuanMiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnRzID0gbW9kdWxlLmV4cG9ydHMgPSByZXF1aXJlKFwiLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL2Nzcy1sb2FkZXIvbGliL2Nzcy1iYXNlLmpzXCIpKGZhbHNlKTtcbi8vIGltcG9ydHNcblxuXG4vLyBtb2R1bGVcbmV4cG9ydHMucHVzaChbbW9kdWxlLmlkLCBcIlxcbi52aWRlb3tcXG4gICAgZmxvYXQ6bGVmdDtcXG59XFxuLm1lc3NhZ2UtYm94e1xcbiAgICBoZWlnaHQ6IDQxMHB4O1xcbn1cXG4ubWVzc2FnZS1kaXZ7XFxuICAgIGhlaWdodDogNDEwcHg7XFxuICAgIHdpZHRoOjEwMCU7XFxuICAgIG92ZXJmbG93LXk6IHNjcm9sbDtcXG59XFxuLmJyb2FkY2FzdHtcXG4gICAgZGlzcGxheTpncmlkO1xcbiAgICBtYXJnaW46YXV0bztcXG59XFxuLnZpZGVvLWRpdntcXG4gICAgdGV4dC1hbGlnbjogY2VudGVyO1xcbiAgICBoZWlnaHQ6IDUwMHB4O1xcbn1cXG4ubWVzc2FnZS1ob3N0LWJvZHl7XFxuICAgIGZvbnQtc2l6ZTogMTRweDtcXG4gICAgY29sb3I6d2hpdGU7XFxuICAgIGJhY2tncm91bmQtY29sb3I6ICMzNzNFNEM7XFxuICAgIGJvcmRlci1yYWRpdXM6IDEwcHg7XFxuICAgIGZsb2F0OnJpZ2h0O1xcbiAgICBwYWRkaW5nOiA1cHggMTVweDtcXG4gICAgdGV4dC1hbGlnbjpsZWZ0O1xcbiAgICBtYXJnaW4tYm90dG9tOiAyMHB4O1xcbn1cXG4ubWVzc2FnZS1ob3N0LWF1dGhvcntcXG4gICAgZm9udC1zaXplOiAxMnB4O1xcbiAgICBjb2xvcjpncmF5O1xcbiAgICBmbG9hdDpyaWdodDtcXG4gICAgbWFyZ2luLWJvdHRvbTogMHB4O1xcbn1cXG4ubWVzc2FnZS10aW1le1xcbiAgICBmb250LXNpemU6IDEycHg7XFxuICAgIGNvbG9yOmdyYXk7XFxuICAgIGZsb2F0OnJpZ2h0O1xcbiAgICBtYXJnaW4tYm90dG9tOiAyMHB4O1xcbn1cXG4ubWVzc2FnZS1ib2R5e1xcbiAgICBmb250LXNpemU6IDE0cHg7XFxuICAgIGNvbG9yOmJsYWNrO1xcbiAgICBiYWNrZ3JvdW5kLWNvbG9yOiAjRTRFNkVCO1xcbiAgICBib3JkZXItcmFkaXVzOiAxMHB4O1xcbiAgICBmbG9hdDpsZWZ0O1xcbiAgICBwYWRkaW5nOiA1cHggMTVweDtcXG4gICAgdGV4dC1hbGlnbjpsZWZ0O1xcbiAgICBtYXJnaW4tYm90dG9tOiAyMHB4O1xcbn1cXG4ubWVzc2FnZS1hdXRob3J7XFxuICAgIGZvbnQtc2l6ZTogMTJweDtcXG4gICAgY29sb3I6Z3JheTtcXG4gICAgZmxvYXQ6bGVmdDtcXG4gICAgbWFyZ2luLWJvdHRvbTogMHB4O1xcbn1cXG4ubWVzc2FnZS10aW1le1xcbiAgICBmb250LXNpemU6IDEycHg7XFxuICAgIGNvbG9yOmdyYXk7XFxuICAgIGZsb2F0OmxlZnQ7XFxuICAgIG1hcmdpbi1ib3R0b206IDIwcHg7XFxufVxcbi52aWRlb3tcXG4gICAgY29udGFpbjpjb3ZlcjtcXG59XFxuLnZpZXdlci1oZWFkZXJ7XFxuICAgIGJvcmRlci1ib3R0b206IDFweCBzb2xpZCAjREZERkRGO1xcbiAgICB0ZXh0LWFsaWduOiBsZWZ0O1xcbn1cXG4udmlld2Vyc3tcXG4gICAgY29sb3I6d2hpdGU7XFxuICAgIGJhY2tncm91bmQtY29sb3I6ICNEQzM1NDU7XFxuICAgIHdpZHRoOiA3MHB4O1xcbiAgICB0ZXh0LWFsaWduOmNlbnRlcjtcXG4gICAgYm9yZGVyLXJhZGl1czogNXB4O1xcbn1cXG5cXG4vKiB3aWR0aCAqL1xcbjo6LXdlYmtpdC1zY3JvbGxiYXIge1xcbiAgd2lkdGg6IDEwcHg7XFxufVxcblxcbi8qIFRyYWNrICovXFxuOjotd2Via2l0LXNjcm9sbGJhci10cmFjayB7XFxuICBiYWNrZ3JvdW5kOiAjZjFmMWYxO1xcbn1cXG5cXG4vKiBIYW5kbGUgKi9cXG46Oi13ZWJraXQtc2Nyb2xsYmFyLXRodW1iIHtcXG4gIGJhY2tncm91bmQ6ICM4ODg7XFxufVxcblxcbi8qIEhhbmRsZSBvbiBob3ZlciAqL1xcbjo6LXdlYmtpdC1zY3JvbGxiYXItdGh1bWI6aG92ZXIge1xcbiAgYmFja2dyb3VuZDogIzU1NTtcXG59XFxuXFxuXCIsIFwiXCJdKTtcblxuLy8gZXhwb3J0c1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\n"); /***/ }), /***/ "./node_modules/style-loader/index.js!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&": /*!************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/style-loader!./node_modules/css-loader??ref--6-1!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src??ref--6-2!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css& ***! \************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("\nvar content = __webpack_require__(/*! !../../../../../node_modules/css-loader??ref--6-1!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--6-2!../../../../../node_modules/vue-loader/lib??vue-loader-options!./go-live.vue?vue&type=style&index=0&lang=css& */ \"./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\");\n\nif(typeof content === 'string') content = [[module.i, content, '']];\n\nvar transform;\nvar insertInto;\n\n\n\nvar options = {\"hmr\":true}\n\noptions.transform = transform\noptions.insertInto = undefined;\n\nvar update = __webpack_require__(/*! ../../../../../node_modules/style-loader/lib/addStyles.js */ \"./node_modules/style-loader/lib/addStyles.js\")(content, options);\n\nif(content.locals) module.exports = content.locals;\n\nif(false) {}//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/MTgzZCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQ0EsY0FBYyxtQkFBTyxDQUFDLHNpQkFBNFQ7O0FBRWxWLDRDQUE0QyxRQUFTOztBQUVyRDtBQUNBOzs7O0FBSUEsZUFBZTs7QUFFZjtBQUNBOztBQUVBLGFBQWEsbUJBQU8sQ0FBQywrR0FBNEQ7O0FBRWpGOztBQUVBLEdBQUcsS0FBVSxFQUFFIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL3N0eWxlLWxvYWRlci9pbmRleC5qcyEuL25vZGVfbW9kdWxlcy9jc3MtbG9hZGVyL2luZGV4LmpzPyEuL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3N0eWxlUG9zdExvYWRlci5qcyEuL25vZGVfbW9kdWxlcy9wb3N0Y3NzLWxvYWRlci9zcmMvaW5kZXguanM/IS4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPyEuL3Jlc291cmNlcy9qcy9wYWdlcy9yZWFkZXIvbGl2ZS9nby1saXZlLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJmxhbmc9Y3NzJi5qcyIsInNvdXJjZXNDb250ZW50IjpbIlxudmFyIGNvbnRlbnQgPSByZXF1aXJlKFwiISEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvY3NzLWxvYWRlci9pbmRleC5qcz8/cmVmLS02LTEhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2xvYWRlcnMvc3R5bGVQb3N0TG9hZGVyLmpzIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9wb3N0Y3NzLWxvYWRlci9zcmMvaW5kZXguanM/P3JlZi0tNi0yIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9pbmRleC5qcz8/dnVlLWxvYWRlci1vcHRpb25zIS4vZ28tbGl2ZS52dWU/dnVlJnR5cGU9c3R5bGUmaW5kZXg9MCZsYW5nPWNzcyZcIik7XG5cbmlmKHR5cGVvZiBjb250ZW50ID09PSAnc3RyaW5nJykgY29udGVudCA9IFtbbW9kdWxlLmlkLCBjb250ZW50LCAnJ11dO1xuXG52YXIgdHJhbnNmb3JtO1xudmFyIGluc2VydEludG87XG5cblxuXG52YXIgb3B0aW9ucyA9IHtcImhtclwiOnRydWV9XG5cbm9wdGlvbnMudHJhbnNmb3JtID0gdHJhbnNmb3JtXG5vcHRpb25zLmluc2VydEludG8gPSB1bmRlZmluZWQ7XG5cbnZhciB1cGRhdGUgPSByZXF1aXJlKFwiIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9zdHlsZS1sb2FkZXIvbGliL2FkZFN0eWxlcy5qc1wiKShjb250ZW50LCBvcHRpb25zKTtcblxuaWYoY29udGVudC5sb2NhbHMpIG1vZHVsZS5leHBvcnRzID0gY29udGVudC5sb2NhbHM7XG5cbmlmKG1vZHVsZS5ob3QpIHtcblx0bW9kdWxlLmhvdC5hY2NlcHQoXCIhIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9jc3MtbG9hZGVyL2luZGV4LmpzPz9yZWYtLTYtMSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Bvc3Rjc3MtbG9hZGVyL3NyYy9pbmRleC5qcz8/cmVmLS02LTIhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJmxhbmc9Y3NzJlwiLCBmdW5jdGlvbigpIHtcblx0XHR2YXIgbmV3Q29udGVudCA9IHJlcXVpcmUoXCIhIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9jc3MtbG9hZGVyL2luZGV4LmpzPz9yZWYtLTYtMSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy9zdHlsZVBvc3RMb2FkZXIuanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Bvc3Rjc3MtbG9hZGVyL3NyYy9pbmRleC5qcz8/cmVmLS02LTIhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJmxhbmc9Y3NzJlwiKTtcblxuXHRcdGlmKHR5cGVvZiBuZXdDb250ZW50ID09PSAnc3RyaW5nJykgbmV3Q29udGVudCA9IFtbbW9kdWxlLmlkLCBuZXdDb250ZW50LCAnJ11dO1xuXG5cdFx0dmFyIGxvY2FscyA9IChmdW5jdGlvbihhLCBiKSB7XG5cdFx0XHR2YXIga2V5LCBpZHggPSAwO1xuXG5cdFx0XHRmb3Ioa2V5IGluIGEpIHtcblx0XHRcdFx0aWYoIWIgfHwgYVtrZXldICE9PSBiW2tleV0pIHJldHVybiBmYWxzZTtcblx0XHRcdFx0aWR4Kys7XG5cdFx0XHR9XG5cblx0XHRcdGZvcihrZXkgaW4gYikgaWR4LS07XG5cblx0XHRcdHJldHVybiBpZHggPT09IDA7XG5cdFx0fShjb250ZW50LmxvY2FscywgbmV3Q29udGVudC5sb2NhbHMpKTtcblxuXHRcdGlmKCFsb2NhbHMpIHRocm93IG5ldyBFcnJvcignQWJvcnRpbmcgQ1NTIEhNUiBkdWUgdG8gY2hhbmdlZCBjc3MtbW9kdWxlcyBsb2NhbHMuJyk7XG5cblx0XHR1cGRhdGUobmV3Q29udGVudCk7XG5cdH0pO1xuXG5cdG1vZHVsZS5ob3QuZGlzcG9zZShmdW5jdGlvbigpIHsgdXBkYXRlKCk7IH0pO1xufSJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/style-loader/index.js!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\n"); /***/ }), /***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&": /*!*****************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81& ***! \*****************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return render; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return staticRenderFns; });\nvar render = function() {\n var _vm = this\n var _h = _vm.$createElement\n var _c = _vm._self._c || _h\n return _c(\n \"card\",\n { staticClass: \"p-6 m-4\" },\n [\n _c(\"div\", { staticClass: \"row\" }, [\n _c(\"div\", { staticClass: \"col-lg-12\" }, [\n _c(\"h4\", { staticClass: \"mb-3\" }, [\n _vm._v(\"\\n Go Live\\n \")\n ]),\n _vm._v(\" \"),\n _c(\"p\", { staticClass: \"mb-5\" }, [\n _vm._v(\n \"\\n Necessitatibus eius consequatur ex aliquid fuga eum quidem.\\n \"\n )\n ])\n ])\n ]),\n _vm._v(\" \"),\n _c(\"div\", { staticClass: \"mb-2\" }, [\n _c(\"div\", { staticClass: \"text-center\" }, [\n _c(\"div\", { staticClass: \"container pb-2\" }, [\n _c(\"div\", { staticClass: \"row justify-content-center\" }, [\n _c(\"div\", { staticClass: \"col-md-12\" }, [\n _c(\"div\", { staticClass: \"row\" }, [\n _c(\"div\", { staticClass: \"col-md-7 video-div\" }, [\n _c(\n \"div\",\n { staticClass: \"video grid grid-flow-row bg-black\" },\n [_c(\"div\", { attrs: { id: \"my-video-chat-window\" } })]\n )\n ]),\n _vm._v(\" \"),\n _c(\"div\", { staticClass: \"col-md-5\" }, [\n _c(\"div\", { staticClass: \"card\" }, [\n _c(\"div\", { staticClass: \"viewer-header px-2 py-1\" }, [\n _c(\"p\", { staticClass: \"m-0 px-2 viewers\" }, [\n _c(\n \"span\",\n {\n directives: [\n {\n name: \"show\",\n rawName: \"v-show\",\n value: _vm.currentStatus === \"ON_GOING\",\n expression: \"currentStatus ==='ON_GOING'\"\n }\n ]\n },\n [\n _c(\"fa\", { attrs: { icon: \"eye\" } }),\n _vm._v(\" \" + _vm._s(_vm.viewerCount) + \" \")\n ],\n 1\n ),\n _vm._v(\" \"),\n _c(\n \"span\",\n {\n directives: [\n {\n name: \"show\",\n rawName: \"v-show\",\n value: _vm.currentStatus !== \"ON_GOING\",\n expression: \"currentStatus !=='ON_GOING'\"\n }\n ]\n },\n [_vm._v(\" Offline \")]\n )\n ])\n ]),\n _vm._v(\" \"),\n _c(\"div\", { staticClass: \"card-body p-0\" }, [\n _c(\"div\", { staticClass: \"message-box\" }, [\n _c(\n \"div\",\n {\n directives: [\n {\n name: \"show\",\n rawName: \"v-show\",\n value: _vm.showMessages,\n expression: \"showMessages\"\n }\n ],\n staticClass: \"message-div p-4\"\n },\n _vm._l(_vm.tc.messagesArray, function(message) {\n return _c(\n \"div\",\n { key: message.id, staticClass: \"row msg\" },\n [\n message.author == _vm.user.username\n ? _c(\"div\", { staticClass: \"media-body\" }, [\n _c(\n \"p\",\n {\n staticClass: \"message-host-author\"\n },\n [\n _vm._v(\n \"\\n \" +\n _vm._s(message.author) +\n \"\\n \"\n )\n ]\n ),\n _vm._v(\" \"),\n _c(\"br\"),\n _vm._v(\" \"),\n _c(\n \"p\",\n { staticClass: \"message-host-body\" },\n [\n _vm._v(\n \"\\n \" +\n _vm._s(message.body) +\n \"\\n \"\n )\n ]\n )\n ])\n : _c(\"div\", { staticClass: \"media-body\" }, [\n _c(\n \"p\",\n { staticClass: \"message-author\" },\n [\n _vm._v(\n \"\\n \" +\n _vm._s(message.author) +\n \"\\n \"\n )\n ]\n ),\n _vm._v(\" \"),\n _c(\"br\"),\n _vm._v(\" \"),\n _c(\n \"p\",\n { staticClass: \"message-body\" },\n [\n _vm._v(\n \"\\n \" +\n _vm._s(message.body) +\n \"\\n \"\n )\n ]\n )\n ])\n ]\n )\n }),\n 0\n ),\n _vm._v(\" \"),\n _vm.notification\n ? _c(\"p\", [\n _vm._v(\n \"\\n \" +\n _vm._s(_vm.notificationMsg) +\n \"\\n \"\n )\n ])\n : _vm._e()\n ]),\n _vm._v(\" \"),\n !_vm.userNotJoined && _vm.currentStatus === \"ON_GOING\"\n ? _c(\"input\", {\n directives: [\n {\n name: \"model\",\n rawName: \"v-model\",\n value: _vm.message,\n expression: \"message\"\n }\n ],\n staticClass: \"form-control\",\n attrs: {\n type: \"text\",\n placeholder: \"Your message\"\n },\n domProps: { value: _vm.message },\n on: {\n keyup: function($event) {\n if (\n !$event.type.indexOf(\"key\") &&\n $event.keyCode !== 13\n ) {\n return null\n }\n return _vm.handleInputTextKeypress.apply(\n null,\n arguments\n )\n },\n input: function($event) {\n if ($event.target.composing) {\n return\n }\n _vm.message = $event.target.value\n }\n }\n })\n : _vm._e()\n ])\n ])\n ])\n ])\n ])\n ])\n ]),\n _vm._v(\" \"),\n _c(\n \"div\",\n { staticClass: \"m-3\" },\n [\n !_vm.userNotJoined &&\n _vm.loggedUser !== _vm.username &&\n _vm.currentStatus === \"ON_GOING\"\n ? _c(\n \"b-button\",\n {\n attrs: { variant: \"primary\" },\n on: {\n click: function($event) {\n return _vm.$bvModal.show(\"rate-modal\")\n }\n }\n },\n [_c(\"b-icon-star-fill\"), _vm._v(\" Rate me\\n \")],\n 1\n )\n : _vm._e()\n ],\n 1\n ),\n _vm._v(\" \"),\n _c(\"div\", [\n _c(\n \"button\",\n {\n directives: [\n {\n name: \"show\",\n rawName: \"v-show\",\n value:\n _vm.currentStatus !== \"ON_GOING\" &&\n _vm.loggedUser === _vm.tc.username,\n expression:\n \"currentStatus !=='ON_GOING' && (loggedUser === tc.username)\"\n }\n ],\n staticClass: \"broadcast btn btn-danger btn-lg\",\n on: {\n click: function($event) {\n _vm.getVideoToken()\n _vm.connectClientWithUsername()\n }\n }\n },\n [_vm._v(\"\\n Start Broadcasting\\n \")]\n ),\n _vm._v(\" \"),\n _vm.currentStatus === \"ON_GOING\" && !_vm.userNotJoined\n ? _c(\n \"button\",\n {\n staticClass: \"btn btn-danger btn-lg\",\n on: {\n click: function($event) {\n return _vm.stopBroadcasting()\n }\n }\n },\n [_vm._v(\"\\n Stop Broadcasting\\n \")]\n )\n : _vm._e()\n ])\n ])\n ]),\n _vm._v(\" \"),\n _c(\n \"b-modal\",\n {\n attrs: { id: \"rate-modal\", \"hide-footer\": \"\" },\n scopedSlots: _vm._u([\n {\n key: \"modal-title\",\n fn: function() {\n return [\n _c(\"span\", { staticClass: \"h3 text-center\" }, [\n _vm._v(\" Rate \"),\n _c(\"strong\", [_vm._v(\" \" + _vm._s(_vm.username) + \" \")])\n ])\n ]\n },\n proxy: true\n }\n ])\n },\n [\n _vm._v(\" \"),\n _c(\n \"div\",\n { staticClass: \"d-block text-center\" },\n [\n _c(\n \"b-row\",\n { staticClass: \"p-3 text-center\" },\n [\n _c(\n \"b-col\",\n [\n _c(\"star-rating\", {\n model: {\n value: _vm.ratingCount,\n callback: function($$v) {\n _vm.ratingCount = $$v\n },\n expression: \"ratingCount\"\n }\n })\n ],\n 1\n )\n ],\n 1\n ),\n _vm._v(\" \"),\n _c(\n \"b-row\",\n { staticClass: \"p-2\" },\n [\n _c(\n \"b-col\",\n { staticClass: \"d-flex justify-content-center\" },\n [\n _c(\n \"b-button\",\n {\n attrs: { variant: \"link\", size: \"sm\" },\n on: {\n click: function() {\n _vm.$bvModal.hide(\"rate-modal\")\n }\n }\n },\n [_vm._v(\"\\n Cancel\\n \")]\n ),\n _vm._v(\" \"),\n _c(\n \"b-button\",\n {\n staticClass: \"float-right\",\n attrs: { variant: \"danger\", size: \"sm\" },\n on: {\n click: function() {\n _vm.handleSubmitRating()\n _vm.$bvModal.hide(\"rate-modal\")\n }\n }\n },\n [_vm._v(\"\\n Submit\\n \")]\n )\n ],\n 1\n )\n ],\n 1\n )\n ],\n 1\n )\n ]\n )\n ],\n 1\n )\n}\nvar staticRenderFns = []\nrender._withStripped = true\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/ZWQ2NCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxLQUFLLHlCQUF5QjtBQUM5QjtBQUNBLGlCQUFpQixxQkFBcUI7QUFDdEMsbUJBQW1CLDJCQUEyQjtBQUM5QyxvQkFBb0Isc0JBQXNCO0FBQzFDO0FBQ0E7QUFDQTtBQUNBLG1CQUFtQixzQkFBc0I7QUFDekM7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxpQkFBaUIsc0JBQXNCO0FBQ3ZDLG1CQUFtQiw2QkFBNkI7QUFDaEQscUJBQXFCLGdDQUFnQztBQUNyRCx1QkFBdUIsNENBQTRDO0FBQ25FLHlCQUF5QiwyQkFBMkI7QUFDcEQsMkJBQTJCLHFCQUFxQjtBQUNoRCw2QkFBNkIsb0NBQW9DO0FBQ2pFO0FBQ0E7QUFDQSx1QkFBdUIsbURBQW1EO0FBQzFFLGtDQUFrQyxTQUFTLDZCQUE2QixFQUFFO0FBQzFFO0FBQ0E7QUFDQTtBQUNBLDZCQUE2QiwwQkFBMEI7QUFDdkQsK0JBQStCLHNCQUFzQjtBQUNyRCxpQ0FBaUMseUNBQXlDO0FBQzFFLGlDQUFpQyxrQ0FBa0M7QUFDbkU7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDZCQUE2QjtBQUM3QjtBQUNBLHdDQUF3QyxTQUFTLGNBQWMsRUFBRTtBQUNqRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDZCQUE2QjtBQUM3QjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUNBQWlDLCtCQUErQjtBQUNoRSxtQ0FBbUMsNkJBQTZCO0FBQ2hFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDZCQUE2QjtBQUM3QjtBQUNBO0FBQ0E7QUFDQSxpQ0FBaUMsMENBQTBDO0FBQzNFO0FBQ0E7QUFDQSxpREFBaUQsNEJBQTRCO0FBQzdFO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkNBQTJDO0FBQzNDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkNBQTJDLG1DQUFtQztBQUM5RTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxpREFBaUQsNEJBQTRCO0FBQzdFO0FBQ0E7QUFDQSwyQ0FBMkMsZ0NBQWdDO0FBQzNFO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkNBQTJDLDhCQUE4QjtBQUN6RTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNkJBQTZCO0FBQzdCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsK0JBQStCO0FBQy9CLHlDQUF5QyxxQkFBcUI7QUFDOUQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUNBQWlDO0FBQ2pDO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsNkJBQTZCO0FBQzdCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxhQUFhLHFCQUFxQjtBQUNsQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLDhCQUE4QixxQkFBcUI7QUFDbkQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHFCQUFxQjtBQUNyQjtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxlQUFlO0FBQ2Y7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxtQkFBbUI7QUFDbkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxrQkFBa0Isc0NBQXNDO0FBQ3hEO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSw4QkFBOEIsZ0NBQWdDO0FBQzlEO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZUFBZTtBQUNmO0FBQ0E7QUFDQTtBQUNBLFNBQVM7QUFDVDtBQUNBO0FBQ0E7QUFDQTtBQUNBLGFBQWEscUNBQXFDO0FBQ2xEO0FBQ0E7QUFDQTtBQUNBLGlCQUFpQixpQ0FBaUM7QUFDbEQ7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkJBQTJCO0FBQzNCO0FBQ0E7QUFDQSx1QkFBdUI7QUFDdkI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsaUJBQWlCLHFCQUFxQjtBQUN0QztBQUNBO0FBQ0E7QUFDQSxxQkFBcUIsK0NBQStDO0FBQ3BFO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0NBQWtDLDhCQUE4QjtBQUNoRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EseUJBQXlCO0FBQ3pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0Esa0NBQWtDLGdDQUFnQztBQUNsRTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSx5QkFBeUI7QUFDekI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EiLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvbG9hZGVycy90ZW1wbGF0ZUxvYWRlci5qcz8hLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/IS4vcmVzb3VyY2VzL2pzL3BhZ2VzL3JlYWRlci9saXZlL2dvLWxpdmUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTY1Mjc1YjgxJi5qcyIsInNvdXJjZXNDb250ZW50IjpbInZhciByZW5kZXIgPSBmdW5jdGlvbigpIHtcbiAgdmFyIF92bSA9IHRoaXNcbiAgdmFyIF9oID0gX3ZtLiRjcmVhdGVFbGVtZW50XG4gIHZhciBfYyA9IF92bS5fc2VsZi5fYyB8fCBfaFxuICByZXR1cm4gX2MoXG4gICAgXCJjYXJkXCIsXG4gICAgeyBzdGF0aWNDbGFzczogXCJwLTYgbS00XCIgfSxcbiAgICBbXG4gICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcInJvd1wiIH0sIFtcbiAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJjb2wtbGctMTJcIiB9LCBbXG4gICAgICAgICAgX2MoXCJoNFwiLCB7IHN0YXRpY0NsYXNzOiBcIm1iLTNcIiB9LCBbXG4gICAgICAgICAgICBfdm0uX3YoXCJcXG4gICAgICAgIEdvIExpdmVcXG4gICAgICBcIilcbiAgICAgICAgICBdKSxcbiAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgIF9jKFwicFwiLCB7IHN0YXRpY0NsYXNzOiBcIm1iLTVcIiB9LCBbXG4gICAgICAgICAgICBfdm0uX3YoXG4gICAgICAgICAgICAgIFwiXFxuICAgICAgICBOZWNlc3NpdGF0aWJ1cyBlaXVzIGNvbnNlcXVhdHVyIGV4IGFsaXF1aWQgZnVnYSBldW0gcXVpZGVtLlxcbiAgICAgIFwiXG4gICAgICAgICAgICApXG4gICAgICAgICAgXSlcbiAgICAgICAgXSlcbiAgICAgIF0pLFxuICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgIF9jKFwiZGl2XCIsIHsgc3RhdGljQ2xhc3M6IFwibWItMlwiIH0sIFtcbiAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJ0ZXh0LWNlbnRlclwiIH0sIFtcbiAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImNvbnRhaW5lciBwYi0yXCIgfSwgW1xuICAgICAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJyb3cganVzdGlmeS1jb250ZW50LWNlbnRlclwiIH0sIFtcbiAgICAgICAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJjb2wtbWQtMTJcIiB9LCBbXG4gICAgICAgICAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJyb3dcIiB9LCBbXG4gICAgICAgICAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImNvbC1tZC03IHZpZGVvLWRpdlwiIH0sIFtcbiAgICAgICAgICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgICAgICAgICAgXCJkaXZcIixcbiAgICAgICAgICAgICAgICAgICAgICB7IHN0YXRpY0NsYXNzOiBcInZpZGVvIGdyaWQgZ3JpZC1mbG93LXJvdyBiZy1ibGFja1wiIH0sXG4gICAgICAgICAgICAgICAgICAgICAgW19jKFwiZGl2XCIsIHsgYXR0cnM6IHsgaWQ6IFwibXktdmlkZW8tY2hhdC13aW5kb3dcIiB9IH0pXVxuICAgICAgICAgICAgICAgICAgICApXG4gICAgICAgICAgICAgICAgICBdKSxcbiAgICAgICAgICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImNvbC1tZC01XCIgfSwgW1xuICAgICAgICAgICAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImNhcmRcIiB9LCBbXG4gICAgICAgICAgICAgICAgICAgICAgX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJ2aWV3ZXItaGVhZGVyIHB4LTIgcHktMVwiIH0sIFtcbiAgICAgICAgICAgICAgICAgICAgICAgIF9jKFwicFwiLCB7IHN0YXRpY0NsYXNzOiBcIm0tMCBweC0yIHZpZXdlcnNcIiB9LCBbXG4gICAgICAgICAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwic3BhblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGRpcmVjdGl2ZXM6IFtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5hbWU6IFwic2hvd1wiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJhd05hbWU6IFwidi1zaG93XCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdmFsdWU6IF92bS5jdXJyZW50U3RhdHVzID09PSBcIk9OX0dPSU5HXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZXhwcmVzc2lvbjogXCJjdXJyZW50U3RhdHVzID09PSdPTl9HT0lORydcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBbXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfYyhcImZhXCIsIHsgYXR0cnM6IHsgaWNvbjogXCJleWVcIiB9IH0pLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFwiIFwiICsgX3ZtLl9zKF92bS52aWV3ZXJDb3VudCkgKyBcIiBcIilcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBdLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIDFcbiAgICAgICAgICAgICAgICAgICAgICAgICAgKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJzcGFuXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZGlyZWN0aXZlczogW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmFtZTogXCJzaG93XCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmF3TmFtZTogXCJ2LXNob3dcIixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB2YWx1ZTogX3ZtLmN1cnJlbnRTdGF0dXMgIT09IFwiT05fR09JTkdcIixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBleHByZXNzaW9uOiBcImN1cnJlbnRTdGF0dXMgIT09J09OX0dPSU5HJ1wiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtfdm0uX3YoXCIgT2ZmbGluZSBcIildXG4gICAgICAgICAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICAgICAgICAgICAgXSksXG4gICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgICAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcImNhcmQtYm9keSBwLTBcIiB9LCBbXG4gICAgICAgICAgICAgICAgICAgICAgICBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcIm1lc3NhZ2UtYm94XCIgfSwgW1xuICAgICAgICAgICAgICAgICAgICAgICAgICBfYyhcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBcImRpdlwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGRpcmVjdGl2ZXM6IFtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG5hbWU6IFwic2hvd1wiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJhd05hbWU6IFwidi1zaG93XCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgdmFsdWU6IF92bS5zaG93TWVzc2FnZXMsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZXhwcmVzc2lvbjogXCJzaG93TWVzc2FnZXNcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc3RhdGljQ2xhc3M6IFwibWVzc2FnZS1kaXYgcC00XCJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIF92bS5fbChfdm0udGMubWVzc2FnZXNBcnJheSwgZnVuY3Rpb24obWVzc2FnZSkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcImRpdlwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7IGtleTogbWVzc2FnZS5pZCwgc3RhdGljQ2xhc3M6IFwicm93IG1zZ1wiIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBtZXNzYWdlLmF1dGhvciA9PSBfdm0udXNlci51c2VybmFtZVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgPyBfYyhcImRpdlwiLCB7IHN0YXRpY0NsYXNzOiBcIm1lZGlhLWJvZHlcIiB9LCBbXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcInBcIixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc3RhdGljQ2xhc3M6IFwibWVzc2FnZS1ob3N0LWF1dGhvclwiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIiArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3MobWVzc2FnZS5hdXRob3IpICtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwiXFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwiXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICApLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX2MoXCJiclwiKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJwXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7IHN0YXRpY0NsYXNzOiBcIm1lc3NhZ2UtaG9zdC1ib2R5XCIgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwiXFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCIgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl9zKG1lc3NhZ2UuYm9keSkgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXSlcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIDogX2MoXCJkaXZcIiwgeyBzdGF0aWNDbGFzczogXCJtZWRpYS1ib2R5XCIgfSwgW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJwXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7IHN0YXRpY0NsYXNzOiBcIm1lc3NhZ2UtYXV0aG9yXCIgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwiXFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCIgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl9zKG1lc3NhZ2UuYXV0aG9yKSArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIlxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICApXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF9jKFwiYnJcIiksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfYyhcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIFwicFwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgeyBzdGF0aWNDbGFzczogXCJtZXNzYWdlLWJvZHlcIiB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIiArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3MobWVzc2FnZS5ib2R5KSArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIlxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICApXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdKVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICApXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgfSksXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgMFxuICAgICAgICAgICAgICAgICAgICAgICAgICApLFxuICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0ubm90aWZpY2F0aW9uXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgPyBfYyhcInBcIiwgW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcXG4gICAgICAgICAgICAgICAgICAgICAgICBcIiArXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uX3MoX3ZtLm5vdGlmaWNhdGlvbk1zZykgK1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXCJcXG4gICAgICAgICAgICAgICAgICAgICAgXCJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgXSlcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICA6IF92bS5fZSgpXG4gICAgICAgICAgICAgICAgICAgICAgICBdKSxcbiAgICAgICAgICAgICAgICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgICAgICAgICAgICAgICAhX3ZtLnVzZXJOb3RKb2luZWQgJiYgX3ZtLmN1cnJlbnRTdGF0dXMgPT09IFwiT05fR09JTkdcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICA/IF9jKFwiaW5wdXRcIiwge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgZGlyZWN0aXZlczogW1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbmFtZTogXCJtb2RlbFwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHJhd05hbWU6IFwidi1tb2RlbFwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIHZhbHVlOiBfdm0ubWVzc2FnZSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBleHByZXNzaW9uOiBcIm1lc3NhZ2VcIlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBdLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc3RhdGljQ2xhc3M6IFwiZm9ybS1jb250cm9sXCIsXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBhdHRyczoge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB0eXBlOiBcInRleHRcIixcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgcGxhY2Vob2xkZXI6IFwiWW91ciBtZXNzYWdlXCJcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBkb21Qcm9wczogeyB2YWx1ZTogX3ZtLm1lc3NhZ2UgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIG9uOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGtleXVwOiBmdW5jdGlvbigkZXZlbnQpIHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICBpZiAoXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAhJGV2ZW50LnR5cGUuaW5kZXhPZihcImtleVwiKSAmJlxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJGV2ZW50LmtleUNvZGUgIT09IDEzXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gbnVsbFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gX3ZtLmhhbmRsZUlucHV0VGV4dEtleXByZXNzLmFwcGx5KFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgbnVsbCxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGFyZ3VtZW50c1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgaW5wdXQ6IGZ1bmN0aW9uKCRldmVudCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIGlmICgkZXZlbnQudGFyZ2V0LmNvbXBvc2luZykge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF92bS5tZXNzYWdlID0gJGV2ZW50LnRhcmdldC52YWx1ZVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgfSlcbiAgICAgICAgICAgICAgICAgICAgICAgICAgOiBfdm0uX2UoKVxuICAgICAgICAgICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICAgICAgICBdKVxuICAgICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICAgIF0pXG4gICAgICAgICAgICBdKVxuICAgICAgICAgIF0pLFxuICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgX2MoXG4gICAgICAgICAgICBcImRpdlwiLFxuICAgICAgICAgICAgeyBzdGF0aWNDbGFzczogXCJtLTNcIiB9LFxuICAgICAgICAgICAgW1xuICAgICAgICAgICAgICAhX3ZtLnVzZXJOb3RKb2luZWQgJiZcbiAgICAgICAgICAgICAgX3ZtLmxvZ2dlZFVzZXIgIT09IF92bS51c2VybmFtZSAmJlxuICAgICAgICAgICAgICBfdm0uY3VycmVudFN0YXR1cyA9PT0gXCJPTl9HT0lOR1wiXG4gICAgICAgICAgICAgICAgPyBfYyhcbiAgICAgICAgICAgICAgICAgICAgXCJiLWJ1dHRvblwiLFxuICAgICAgICAgICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgICAgICAgYXR0cnM6IHsgdmFyaWFudDogXCJwcmltYXJ5XCIgfSxcbiAgICAgICAgICAgICAgICAgICAgICBvbjoge1xuICAgICAgICAgICAgICAgICAgICAgICAgY2xpY2s6IGZ1bmN0aW9uKCRldmVudCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICByZXR1cm4gX3ZtLiRidk1vZGFsLnNob3coXCJyYXRlLW1vZGFsXCIpXG4gICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICAgICAgICBbX2MoXCJiLWljb24tc3Rhci1maWxsXCIpLCBfdm0uX3YoXCIgUmF0ZSBtZVxcbiAgICAgICAgXCIpXSxcbiAgICAgICAgICAgICAgICAgICAgMVxuICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICAgIDogX3ZtLl9lKClcbiAgICAgICAgICAgIF0sXG4gICAgICAgICAgICAxXG4gICAgICAgICAgKSxcbiAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgIF9jKFwiZGl2XCIsIFtcbiAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICBcImJ1dHRvblwiLFxuICAgICAgICAgICAgICB7XG4gICAgICAgICAgICAgICAgZGlyZWN0aXZlczogW1xuICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICBuYW1lOiBcInNob3dcIixcbiAgICAgICAgICAgICAgICAgICAgcmF3TmFtZTogXCJ2LXNob3dcIixcbiAgICAgICAgICAgICAgICAgICAgdmFsdWU6XG4gICAgICAgICAgICAgICAgICAgICAgX3ZtLmN1cnJlbnRTdGF0dXMgIT09IFwiT05fR09JTkdcIiAmJlxuICAgICAgICAgICAgICAgICAgICAgIF92bS5sb2dnZWRVc2VyID09PSBfdm0udGMudXNlcm5hbWUsXG4gICAgICAgICAgICAgICAgICAgIGV4cHJlc3Npb246XG4gICAgICAgICAgICAgICAgICAgICAgXCJjdXJyZW50U3RhdHVzICE9PSdPTl9HT0lORycgJiYgKGxvZ2dlZFVzZXIgPT09IHRjLnVzZXJuYW1lKVwiXG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgXSxcbiAgICAgICAgICAgICAgICBzdGF0aWNDbGFzczogXCJicm9hZGNhc3QgYnRuIGJ0bi1kYW5nZXIgYnRuLWxnXCIsXG4gICAgICAgICAgICAgICAgb246IHtcbiAgICAgICAgICAgICAgICAgIGNsaWNrOiBmdW5jdGlvbigkZXZlbnQpIHtcbiAgICAgICAgICAgICAgICAgICAgX3ZtLmdldFZpZGVvVG9rZW4oKVxuICAgICAgICAgICAgICAgICAgICBfdm0uY29ubmVjdENsaWVudFdpdGhVc2VybmFtZSgpXG4gICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICBbX3ZtLl92KFwiXFxuICAgICAgICAgIFN0YXJ0IEJyb2FkY2FzdGluZ1xcbiAgICAgICAgXCIpXVxuICAgICAgICAgICAgKSxcbiAgICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgICBfdm0uY3VycmVudFN0YXR1cyA9PT0gXCJPTl9HT0lOR1wiICYmICFfdm0udXNlck5vdEpvaW5lZFxuICAgICAgICAgICAgICA/IF9jKFxuICAgICAgICAgICAgICAgICAgXCJidXR0b25cIixcbiAgICAgICAgICAgICAgICAgIHtcbiAgICAgICAgICAgICAgICAgICAgc3RhdGljQ2xhc3M6IFwiYnRuIGJ0bi1kYW5nZXIgYnRuLWxnXCIsXG4gICAgICAgICAgICAgICAgICAgIG9uOiB7XG4gICAgICAgICAgICAgICAgICAgICAgY2xpY2s6IGZ1bmN0aW9uKCRldmVudCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgcmV0dXJuIF92bS5zdG9wQnJvYWRjYXN0aW5nKClcbiAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAgICAgICBbX3ZtLl92KFwiXFxuICAgICAgICAgIFN0b3AgQnJvYWRjYXN0aW5nXFxuICAgICAgICBcIildXG4gICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICA6IF92bS5fZSgpXG4gICAgICAgICAgXSlcbiAgICAgICAgXSlcbiAgICAgIF0pLFxuICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgIF9jKFxuICAgICAgICBcImItbW9kYWxcIixcbiAgICAgICAge1xuICAgICAgICAgIGF0dHJzOiB7IGlkOiBcInJhdGUtbW9kYWxcIiwgXCJoaWRlLWZvb3RlclwiOiBcIlwiIH0sXG4gICAgICAgICAgc2NvcGVkU2xvdHM6IF92bS5fdShbXG4gICAgICAgICAgICB7XG4gICAgICAgICAgICAgIGtleTogXCJtb2RhbC10aXRsZVwiLFxuICAgICAgICAgICAgICBmbjogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICAgICAgcmV0dXJuIFtcbiAgICAgICAgICAgICAgICAgIF9jKFwic3BhblwiLCB7IHN0YXRpY0NsYXNzOiBcImgzIHRleHQtY2VudGVyXCIgfSwgW1xuICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXCIgUmF0ZSAgXCIpLFxuICAgICAgICAgICAgICAgICAgICBfYyhcInN0cm9uZ1wiLCBbX3ZtLl92KFwiIFwiICsgX3ZtLl9zKF92bS51c2VybmFtZSkgKyBcIiBcIildKVxuICAgICAgICAgICAgICAgICAgXSlcbiAgICAgICAgICAgICAgICBdXG4gICAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAgIHByb3h5OiB0cnVlXG4gICAgICAgICAgICB9XG4gICAgICAgICAgXSlcbiAgICAgICAgfSxcbiAgICAgICAgW1xuICAgICAgICAgIF92bS5fdihcIiBcIiksXG4gICAgICAgICAgX2MoXG4gICAgICAgICAgICBcImRpdlwiLFxuICAgICAgICAgICAgeyBzdGF0aWNDbGFzczogXCJkLWJsb2NrIHRleHQtY2VudGVyXCIgfSxcbiAgICAgICAgICAgIFtcbiAgICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgICAgXCJiLXJvd1wiLFxuICAgICAgICAgICAgICAgIHsgc3RhdGljQ2xhc3M6IFwicC0zIHRleHQtY2VudGVyXCIgfSxcbiAgICAgICAgICAgICAgICBbXG4gICAgICAgICAgICAgICAgICBfYyhcbiAgICAgICAgICAgICAgICAgICAgXCJiLWNvbFwiLFxuICAgICAgICAgICAgICAgICAgICBbXG4gICAgICAgICAgICAgICAgICAgICAgX2MoXCJzdGFyLXJhdGluZ1wiLCB7XG4gICAgICAgICAgICAgICAgICAgICAgICBtb2RlbDoge1xuICAgICAgICAgICAgICAgICAgICAgICAgICB2YWx1ZTogX3ZtLnJhdGluZ0NvdW50LFxuICAgICAgICAgICAgICAgICAgICAgICAgICBjYWxsYmFjazogZnVuY3Rpb24oJCR2KSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLnJhdGluZ0NvdW50ID0gJCR2XG4gICAgICAgICAgICAgICAgICAgICAgICAgIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAgIGV4cHJlc3Npb246IFwicmF0aW5nQ291bnRcIlxuICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgIH0pXG4gICAgICAgICAgICAgICAgICAgIF0sXG4gICAgICAgICAgICAgICAgICAgIDFcbiAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICBdLFxuICAgICAgICAgICAgICAgIDFcbiAgICAgICAgICAgICAgKSxcbiAgICAgICAgICAgICAgX3ZtLl92KFwiIFwiKSxcbiAgICAgICAgICAgICAgX2MoXG4gICAgICAgICAgICAgICAgXCJiLXJvd1wiLFxuICAgICAgICAgICAgICAgIHsgc3RhdGljQ2xhc3M6IFwicC0yXCIgfSxcbiAgICAgICAgICAgICAgICBbXG4gICAgICAgICAgICAgICAgICBfYyhcbiAgICAgICAgICAgICAgICAgICAgXCJiLWNvbFwiLFxuICAgICAgICAgICAgICAgICAgICB7IHN0YXRpY0NsYXNzOiBcImQtZmxleCBqdXN0aWZ5LWNvbnRlbnQtY2VudGVyXCIgfSxcbiAgICAgICAgICAgICAgICAgICAgW1xuICAgICAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgXCJiLWJ1dHRvblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICAgICAgICBhdHRyczogeyB2YXJpYW50OiBcImxpbmtcIiwgc2l6ZTogXCJzbVwiIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAgIG9uOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgY2xpY2s6IGZ1bmN0aW9uKCkge1xuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgX3ZtLiRidk1vZGFsLmhpZGUoXCJyYXRlLW1vZGFsXCIpXG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgICAgICAgICB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgW192bS5fdihcIlxcbiAgICAgICAgICAgIENhbmNlbFxcbiAgICAgICAgICBcIildXG4gICAgICAgICAgICAgICAgICAgICAgKSxcbiAgICAgICAgICAgICAgICAgICAgICBfdm0uX3YoXCIgXCIpLFxuICAgICAgICAgICAgICAgICAgICAgIF9jKFxuICAgICAgICAgICAgICAgICAgICAgICAgXCJiLWJ1dHRvblwiLFxuICAgICAgICAgICAgICAgICAgICAgICAge1xuICAgICAgICAgICAgICAgICAgICAgICAgICBzdGF0aWNDbGFzczogXCJmbG9hdC1yaWdodFwiLFxuICAgICAgICAgICAgICAgICAgICAgICAgICBhdHRyczogeyB2YXJpYW50OiBcImRhbmdlclwiLCBzaXplOiBcInNtXCIgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICAgb246IHtcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICBjbGljazogZnVuY3Rpb24oKSB7XG4gICAgICAgICAgICAgICAgICAgICAgICAgICAgICBfdm0uaGFuZGxlU3VibWl0UmF0aW5nKClcbiAgICAgICAgICAgICAgICAgICAgICAgICAgICAgIF92bS4kYnZNb2RhbC5oaWRlKFwicmF0ZS1tb2RhbFwiKVxuICAgICAgICAgICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgICAgICAgICAgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgIFtfdm0uX3YoXCJcXG4gICAgICAgICAgICBTdWJtaXRcXG4gICAgICAgICAgXCIpXVxuICAgICAgICAgICAgICAgICAgICAgIClcbiAgICAgICAgICAgICAgICAgICAgXSxcbiAgICAgICAgICAgICAgICAgICAgMVxuICAgICAgICAgICAgICAgICAgKVxuICAgICAgICAgICAgICAgIF0sXG4gICAgICAgICAgICAgICAgMVxuICAgICAgICAgICAgICApXG4gICAgICAgICAgICBdLFxuICAgICAgICAgICAgMVxuICAgICAgICAgIClcbiAgICAgICAgXVxuICAgICAgKVxuICAgIF0sXG4gICAgMVxuICApXG59XG52YXIgc3RhdGljUmVuZGVyRm5zID0gW11cbnJlbmRlci5fd2l0aFN0cmlwcGVkID0gdHJ1ZVxuXG5leHBvcnQgeyByZW5kZXIsIHN0YXRpY1JlbmRlckZucyB9Il0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&\n"); /***/ }), /***/ "./resources/js/pages/reader/live/go-live.vue": /*!****************************************************!*\ !*** ./resources/js/pages/reader/live/go-live.vue ***! \****************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./go-live.vue?vue&type=template&id=65275b81& */ \"./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&\");\n/* harmony import */ var _go_live_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./go-live.vue?vue&type=script&lang=js& */ \"./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport *//* harmony import */ var _go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./go-live.vue?vue&type=style&index=0&lang=css& */ \"./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\");\n/* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ \"./node_modules/vue-loader/lib/runtime/componentNormalizer.js\");\n\n\n\n\n\n\n/* normalize component */\n\nvar component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__[\"default\"])(\n _go_live_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[\"default\"],\n _go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__[\"render\"],\n _go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"],\n false,\n null,\n null,\n null\n \n)\n\n/* hot reload */\nif (false) { var api; }\ncomponent.options.__file = \"resources/js/pages/reader/live/go-live.vue\"\n/* harmony default export */ __webpack_exports__[\"default\"] = (component.exports);//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/ZDZmNCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQXNGO0FBQzNCO0FBQ0w7QUFDYTs7O0FBR25FO0FBQ21HO0FBQ25HLGdCQUFnQiwyR0FBVTtBQUMxQixFQUFFLDZFQUFNO0FBQ1IsRUFBRSxrRkFBTTtBQUNSLEVBQUUsMkZBQWU7QUFDakI7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7O0FBRUE7QUFDQSxJQUFJLEtBQVUsRUFBRSxZQWlCZjtBQUNEO0FBQ2UsZ0YiLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWUuanMiLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgeyByZW5kZXIsIHN0YXRpY1JlbmRlckZucyB9IGZyb20gXCIuL2dvLWxpdmUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTY1Mjc1YjgxJlwiXG5pbXBvcnQgc2NyaXB0IGZyb20gXCIuL2dvLWxpdmUudnVlP3Z1ZSZ0eXBlPXNjcmlwdCZsYW5nPWpzJlwiXG5leHBvcnQgKiBmcm9tIFwiLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIlxuaW1wb3J0IHN0eWxlMCBmcm9tIFwiLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJmxhbmc9Y3NzJlwiXG5cblxuLyogbm9ybWFsaXplIGNvbXBvbmVudCAqL1xuaW1wb3J0IG5vcm1hbGl6ZXIgZnJvbSBcIiEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvcnVudGltZS9jb21wb25lbnROb3JtYWxpemVyLmpzXCJcbnZhciBjb21wb25lbnQgPSBub3JtYWxpemVyKFxuICBzY3JpcHQsXG4gIHJlbmRlcixcbiAgc3RhdGljUmVuZGVyRm5zLFxuICBmYWxzZSxcbiAgbnVsbCxcbiAgbnVsbCxcbiAgbnVsbFxuICBcbilcblxuLyogaG90IHJlbG9hZCAqL1xuaWYgKG1vZHVsZS5ob3QpIHtcbiAgdmFyIGFwaSA9IHJlcXVpcmUoXCIvVXNlcnMvYXphL0RvY3VtZW50cy9HaXRIdWIvdGlrLXRvay10YXJvdC9ub2RlX21vZHVsZXMvdnVlLWhvdC1yZWxvYWQtYXBpL2Rpc3QvaW5kZXguanNcIilcbiAgYXBpLmluc3RhbGwocmVxdWlyZSgndnVlJykpXG4gIGlmIChhcGkuY29tcGF0aWJsZSkge1xuICAgIG1vZHVsZS5ob3QuYWNjZXB0KClcbiAgICBpZiAoIWFwaS5pc1JlY29yZGVkKCc2NTI3NWI4MScpKSB7XG4gICAgICBhcGkuY3JlYXRlUmVjb3JkKCc2NTI3NWI4MScsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH0gZWxzZSB7XG4gICAgICBhcGkucmVsb2FkKCc2NTI3NWI4MScsIGNvbXBvbmVudC5vcHRpb25zKVxuICAgIH1cbiAgICBtb2R1bGUuaG90LmFjY2VwdChcIi4vZ28tbGl2ZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NjUyNzViODEmXCIsIGZ1bmN0aW9uICgpIHtcbiAgICAgIGFwaS5yZXJlbmRlcignNjUyNzViODEnLCB7XG4gICAgICAgIHJlbmRlcjogcmVuZGVyLFxuICAgICAgICBzdGF0aWNSZW5kZXJGbnM6IHN0YXRpY1JlbmRlckZuc1xuICAgICAgfSlcbiAgICB9KVxuICB9XG59XG5jb21wb25lbnQub3B0aW9ucy5fX2ZpbGUgPSBcInJlc291cmNlcy9qcy9wYWdlcy9yZWFkZXIvbGl2ZS9nby1saXZlLnZ1ZVwiXG5leHBvcnQgZGVmYXVsdCBjb21wb25lbnQuZXhwb3J0cyJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/pages/reader/live/go-live.vue\n"); /***/ }), /***/ "./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&": /*!*****************************************************************************!*\ !*** ./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js& ***! \*****************************************************************************/ /*! exports provided: default */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/babel-loader/lib??ref--4-0!../../../../../node_modules/vue-loader/lib??vue-loader-options!./go-live.vue?vue&type=script&lang=js& */ \"./node_modules/babel-loader/lib/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&\");\n/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__[\"default\"] = (_node_modules_babel_loader_lib_index_js_ref_4_0_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[\"default\"]); //# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/ZjZiYiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUEsd0NBQW1NLENBQWdCLG1QQUFHLEVBQUMiLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/dnVlJnR5cGU9c2NyaXB0Jmxhbmc9anMmLmpzIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IG1vZCBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIjsgZXhwb3J0IGRlZmF1bHQgbW9kOyBleHBvcnQgKiBmcm9tIFwiLSEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvYmFiZWwtbG9hZGVyL2xpYi9pbmRleC5qcz8/cmVmLS00LTAhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2luZGV4LmpzPz92dWUtbG9hZGVyLW9wdGlvbnMhLi9nby1saXZlLnZ1ZT92dWUmdHlwZT1zY3JpcHQmbGFuZz1qcyZcIiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./resources/js/pages/reader/live/go-live.vue?vue&type=script&lang=js&\n"); /***/ }), /***/ "./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&": /*!*************************************************************************************!*\ !*** ./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css& ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/style-loader!../../../../../node_modules/css-loader??ref--6-1!../../../../../node_modules/vue-loader/lib/loaders/stylePostLoader.js!../../../../../node_modules/postcss-loader/src??ref--6-2!../../../../../node_modules/vue-loader/lib??vue-loader-options!./go-live.vue?vue&type=style&index=0&lang=css& */ \"./node_modules/style-loader/index.js!./node_modules/css-loader/index.js?!./node_modules/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/postcss-loader/src/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\");\n/* harmony import */ var _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__);\n/* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__) if([\"default\"].indexOf(__WEBPACK_IMPORT_KEY__) < 0) (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _node_modules_style_loader_index_js_node_modules_css_loader_index_js_ref_6_1_node_modules_vue_loader_lib_loaders_stylePostLoader_js_node_modules_postcss_loader_src_index_js_ref_6_2_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__));\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/OGJmYiJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQSIsImZpbGUiOiIuL3Jlc291cmNlcy9qcy9wYWdlcy9yZWFkZXIvbGl2ZS9nby1saXZlLnZ1ZT92dWUmdHlwZT1zdHlsZSZpbmRleD0wJmxhbmc9Y3NzJi5qcyIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCAqIGZyb20gXCItIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy9zdHlsZS1sb2FkZXIvaW5kZXguanMhLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL2Nzcy1sb2FkZXIvaW5kZXguanM/P3JlZi0tNi0xIS4uLy4uLy4uLy4uLy4uL25vZGVfbW9kdWxlcy92dWUtbG9hZGVyL2xpYi9sb2FkZXJzL3N0eWxlUG9zdExvYWRlci5qcyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvcG9zdGNzcy1sb2FkZXIvc3JjL2luZGV4LmpzPz9yZWYtLTYtMiEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL2dvLWxpdmUudnVlP3Z1ZSZ0eXBlPXN0eWxlJmluZGV4PTAmbGFuZz1jc3MmXCIiXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./resources/js/pages/reader/live/go-live.vue?vue&type=style&index=0&lang=css&\n"); /***/ }), /***/ "./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&": /*!***********************************************************************************!*\ !*** ./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81& ***! \***********************************************************************************/ /*! exports provided: render, staticRenderFns */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../../node_modules/vue-loader/lib??vue-loader-options!./go-live.vue?vue&type=template&id=65275b81& */ \"./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&\");\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"render\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__[\"render\"]; });\n\n/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, \"staticRenderFns\", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_go_live_vue_vue_type_template_id_65275b81___WEBPACK_IMPORTED_MODULE_0__[\"staticRenderFns\"]; });\n\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/ZmQzOCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTtBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQUEiLCJmaWxlIjoiLi9yZXNvdXJjZXMvanMvcGFnZXMvcmVhZGVyL2xpdmUvZ28tbGl2ZS52dWU/dnVlJnR5cGU9dGVtcGxhdGUmaWQ9NjUyNzViODEmLmpzIiwic291cmNlc0NvbnRlbnQiOlsiZXhwb3J0ICogZnJvbSBcIi0hLi4vLi4vLi4vLi4vLi4vbm9kZV9tb2R1bGVzL3Z1ZS1sb2FkZXIvbGliL2xvYWRlcnMvdGVtcGxhdGVMb2FkZXIuanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuLi8uLi8uLi8uLi8uLi9ub2RlX21vZHVsZXMvdnVlLWxvYWRlci9saWIvaW5kZXguanM/P3Z1ZS1sb2FkZXItb3B0aW9ucyEuL2dvLWxpdmUudnVlP3Z1ZSZ0eXBlPXRlbXBsYXRlJmlkPTY1Mjc1YjgxJlwiIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./resources/js/pages/reader/live/go-live.vue?vue&type=template&id=65275b81&\n"); /***/ }) }]);
const DataStore = require('nedb-promise'); const db = new DataStore({filename:__dirname + '/toursDB', autoload: true}); const users = require('./tours.json'); async function initialize() { try { let numRemoved = await db.remove({}, {multi: true}); console.log(`Cleanup, removed ${numRemoved} tours`); let newDocs = await db.insert(users); console.log(`Added ${newDocs.length} tours`); } catch (err) { console.log(`Database error: ${err}`); } } initialize();
var path = require('path'); var webpack = require('webpack'); var ngAnnotatePlugin = require('ng-annotate-webpack-plugin'); // load webpack config here for for webpack preprocessor var webpackConfig = require('./webpack.config'); delete webpackConfig.devtool; webpackConfig.cache = true; var file; var entry = [ 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.10/d3.min.js', 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js', 'https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-animate.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.15/angular-ui-router.js', 'https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.8/angular-mocks.js', ]; var preprocessors = {}; for (var chunk in webpackConfig.entry) { file = path.resolve(webpackConfig.context, webpackConfig.entry[chunk]); entry.push(file); preprocessors[file] = ['webpack']; } module.exports = function (config) { config.set({ basePath: './', frameworks: ['mocha', 'chai', 'sinon'], files: entry, webpack: webpackConfig, // list of files to exclude exclude: [ 'src/switcher.js' ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: preprocessors, reporters: ['progress'], port: 9876, colors: true, autoWatch: true, browsers: ['PhantomJS', 'Chrome', 'Firefox', 'Safari'], plugins: [ require('karma-webpack'), 'karma-coverage', 'karma-phantomjs-launcher', 'karma-chrome-launcher', 'karma-firefox-launcher', 'karma-safari-launcher', 'karma-mocha', 'karma-chai', 'karma-sinon', ] }); };
import React from 'react'; import { PureTaskList } from './TaskList'; import * as TaskStories from './Task.stories'; export default { component: PureTaskList, title: 'TaskList', decorators: [story => <div style={{ padding: '3rem' }}>{story()}</div>], }; const Template = args => <PureTaskList {...args} />; export const Default = Template.bind({}); Default.args = { // Shaping the stories through args composition. // The data was inherited the Default story in task.stories.js. tasks: [ { ...TaskStories.Default.args.task, id: '1', title: 'Task 1' }, { ...TaskStories.Default.args.task, id: '2', title: 'Task 2' }, { ...TaskStories.Default.args.task, id: '3', title: 'Task 3' }, { ...TaskStories.Default.args.task, id: '4', title: 'Task 4' }, { ...TaskStories.Default.args.task, id: '5', title: 'Task 5' }, { ...TaskStories.Default.args.task, id: '6', title: 'Task 6' }, ], }; export const WithPinnedTasks = Template.bind({}); WithPinnedTasks.args = { // Shaping the stories through args composition. // Inherited data coming from the Default story. tasks: [ ...Default.args.tasks.slice(0, 5), { id: '6', title: 'Task 6 (pinned)', state: 'TASK_PINNED' }, ], }; export const Loading = Template.bind({}); Loading.args = { tasks: [], loading: true, }; export const Empty = Template.bind({}); Empty.args = { // Shaping the stories through args composition. // Inherited data coming from the Loading story. ...Loading.args, loading: false, };
'use strict' const { EOL } = require('os') /** * @memberof module:@the-/code.processors * @function processFileEnd * @param {string} content * @returns {string} processed */ function processFileEnd(content) { const endsWithEOL = content.substr(content.length - EOL.length, EOL.length) === EOL if (!endsWithEOL) { content += EOL } return content.replace(/\s*\s$/, EOL) } module.exports = processFileEnd
const addvehiclesvs = () => { return async (req, res, next) => { const data = req.body; // console.log(req.body); const vehicleData = require('../../models/vehicleData'); const vehicleInfo = { rf_tag: data.rf_tag, manufacturer: data.manufacturer, vehicleModel: data.model, engineType: data.type, yom: data.yom, engineNumber: data.engineNum, chassisNumber: data.chassisNum, }; console.log(vehicleInfo); try { await vehicleData.create(vehicleInfo); res.status(201).json({ msg: 'Data Processed', }); } catch (err) { console.log(err); res.status(200).json({ msg: 'Something went wrong', }); } next(); }; }; module.exports = addvehiclesvs;
/** * Copyright since 2007 PrestaShop SA and Contributors * PrestaShop is an International Registered Trademark & Property of PrestaShop SA * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.md. * It is also available through the world-wide-web at this URL: * https://opensource.org/licenses/OSL-3.0 * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to https://devdocs.prestashop.com/ for more information. * * @author PrestaShop SA and Contributors <contact@prestashop.com> * @copyright Since 2007 PrestaShop SA and Contributors * @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0) */ import Grid from '../../components/grid/grid'; import SortingExtension from '../../components/grid/extension/sorting-extension'; import FiltersResetExtension from '../../components/grid/extension/filters-reset-extension'; import ReloadListActionExtension from '../../components/grid/extension/reload-list-extension'; import ExportToSqlManagerExtension from '../../components/grid/extension/export-to-sql-manager-extension'; import TranslatableInput from '../../components/translatable-input'; import FiltersSubmitButtonEnablerExtension from '../../components/grid/extension/filters-submit-button-enabler-extension'; const $ = window.$; $(() => { const creditSlipGrid = new Grid('credit_slip'); creditSlipGrid.addExtension(new ExportToSqlManagerExtension()); creditSlipGrid.addExtension(new ReloadListActionExtension()); creditSlipGrid.addExtension(new SortingExtension()); creditSlipGrid.addExtension(new FiltersResetExtension()); creditSlipGrid.addExtension(new FiltersSubmitButtonEnablerExtension()); new TranslatableInput(); });
process.on('uncaughtException', function (error) { console.log("uncaughtException :" + error); }); var routes = require('./routes'); var requestSender = require('./app/RequestSender'); function run(callback, requestSenderService) { var express = require('express'); var app = express(); var bodyparser = require('body-parser'); app.set('port', (process.env.PORT || 8080)); var server = app.listen(app.get('port'), function () { if (!process.env.ENCRYPT_KEY) { process.env.ENCRYPT_KEY = "9bcDPot4"; console.log("ERROR: WILL NOT WORK IF IS INTO PRODUCTION, ENCRYPT KEY NOT SET"); } if(!process.env.WAKANDA_STATISTIC_RECEIVER) { throw "WAKANDA STATISTIC RECEIVER NOT CONFIGURATED SERVER WILL NOT START"; } var host = process.env.host; var port = app.get('port'); if(callback) { callback(); } console.log("Listening at http://%s:%s", host, port); }); server.on('close', function() { console.log('Server closed'); }); app.use(require('cors')()); app.use(bodyparser.json()); routes.injectRequestSender(requestSenderService); app.post('/generate', routes.generate); app.get('/projects', routes.projects); app.delete('/projects', routes.deleteProject); return server; } if(!process.env.TEST_ENVIRONMENT) { console.log('Production Environment'); run(null, requestSender); } else { console.log('Test Environment'); } exports.run = run;
var assert = require('assert'); var utils = require('./../../lib/utils.js'); var addresses = require('./../fixtures/addresses.js'); suite('unit - utils.parseLedger()', function() { const DEFAULT_LEDGER = 'validated'; test('parseLedger() -- ledger (empty string)', function() { var ledger = ''; assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (void)', function() { var ledger = void(0); assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (hash)', function() { var ledger_hash = 'FD22E2A8D665A01711C0147173ECC0A32466BA976DE697E95197933311267BE8'; assert.strictEqual(utils.parseLedger(ledger_hash), ledger_hash); }); test('parseLedger() -- ledger (sequence)', function() { var ledger_sequence = '9592219'; assert.strictEqual(utils.parseLedger(ledger_sequence), 9592219); }); test('parseLedger() -- ledger (validated)', function() { var ledger = 'validated'; assert.strictEqual(utils.parseLedger(ledger), ledger); }); test('parseLedger() -- ledger (closed)', function() { var ledger = 'closed'; assert.strictEqual(utils.parseLedger(ledger), ledger); }); test('parseLedger() -- ledger (current)', function() { var ledger = 'current'; assert.strictEqual(utils.parseLedger(ledger), ledger); }); test('parseLedger() -- ledger (foo)', function() { var ledger = 'foo'; assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (negative number)', function() { var ledger = -1; assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (zero)', function() { var ledger = -1; assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (infinity)', function() { var ledger = -1; assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); test('parseLedger() -- ledger (invalid hash)', function() { var ledger = 'FD22E2A8D665A01711C0147173ECC0A32466BA976DE697E95197933311267BE'; assert.strictEqual(ledger.length, 63); assert.strictEqual(utils.parseLedger(ledger), DEFAULT_LEDGER); }); }); suite('unit - utils.parseCurrencyAmount()', function() { const nativeAmount = '1000000'; const usdAmount = { currency: 'USD', issuer: 'rMwjYedjc7qqtKYVLiAccJSmCwih4LnE2q', amount: '100' }; test('parseCurrencyAmount() -- XRP', function() { assert.deepEqual(utils.parseCurrencyAmount(nativeAmount), { currency: 'XRP', counterparty: '', value: utils.dropsToXrp(nativeAmount) }); }); test('parseCurrencyAmount() -- USD', function() { assert.deepEqual(utils.parseCurrencyAmount(usdAmount), { currency: usdAmount.currency, counterparty: usdAmount.issuer, value: usdAmount.value }); }); }); suite('unit - utils.parseCurrencyQuery()', function() { test('parseCurrencyQuery() -- value+XRP', function() { assert.deepEqual(utils.parseCurrencyQuery('123+XRP'), { value: '123', currency: 'XRP', issuer: '' }); }); test('parseCurrencyQuery() -- XRP', function() { assert.deepEqual(utils.parseCurrencyQuery('XRP'), { currency: 'XRP', issuer: '' }); }); test('parseCurrencyQuery() -- USD', function() { assert.deepEqual(utils.parseCurrencyQuery('USD'), { currency: 'USD', issuer: '' }); }); test('parseCurrencyQuery() -- 123+USD', function() { assert.deepEqual(utils.parseCurrencyQuery('123+USD'), { value: '123', currency: 'USD', issuer: '' }); }); test('parseCurrencyQuery() -- USD+issuer', function() { assert.deepEqual(utils.parseCurrencyQuery('USD+' + addresses.VALID), { currency: 'USD', issuer: addresses.VALID }); }); test('parseCurrencyQuery() -- 123+USD+issuer', function() { assert.deepEqual(utils.parseCurrencyQuery('123+USD+' + addresses.VALID), { value: '123', currency: 'USD', issuer: addresses.VALID }); }); test('parseCurrencyQuery() -- XRP+issuer', function() { assert.deepEqual(utils.parseCurrencyQuery('XRP+' + addresses.VALID), { currency: 'XRP', issuer: addresses.VALID }); }); test('parseCurrencyQuery() -- 123+XRP+issuer', function() { assert.deepEqual(utils.parseCurrencyQuery('123+XRP+' + addresses.VALID), { value: '123', currency: 'XRP', issuer: addresses.VALID }); }); test('parseCurrencyQuery() -- XRP+', function() { assert.deepEqual(utils.parseCurrencyQuery('XRP+'), { currency: 'XRP', issuer: '' }); }); test('parseCurrencyQuery() -- 123+XRP+', function() { assert.deepEqual(utils.parseCurrencyQuery('123+XRP+'), { value: '123', currency: 'XRP', issuer: '' }); }); test('parseCurrencyQuery() -- 123', function() { assert.deepEqual(utils.parseCurrencyQuery('123'), { value: '123', currency: '', issuer: '' }); }); });
import Add from './source/Add'; import AddAnother from './source/AddAnother'; import Kanban from './source/Kanban'; export default { Add : Add, AddAnother : AddAnother, Kanban : Kanban, }
# coding: utf-8 ######################################################################### # 网站: <a href="http://www.crazyit.org">疯狂Java联盟</a> # # author yeeku.H.lee kongyeeku@163.com # # # # version 1.0 # # # # Copyright (C), 2001-2018, yeeku.H.Lee # # # # This program is protected by copyright laws. # # # # Program Name: # # # # <br>Date: # ######################################################################### from tkinter import * # 导入ttk from tkinter import ttk class App: def __init__(self, master): self.master = master self.initWidgets() def initWidgets(self): topF = Frame(self.master) topF.pack(fill=Y, expand=YES) # 创建Listbox组件 self.lb = Listbox(topF) self.lb.pack(side=LEFT, fill=Y, expand=YES) for item in range(20): self.lb.insert(END, str(item)) # 创建Scrollbar组件,设置该组件与self.lb的纵向滚动关联 scroll = Scrollbar(topF, command=self.lb.yview) scroll.pack(side=RIGHT, fill=Y) # 设置self.lb的纵向滚动影响scroll滚动条 self.lb.configure(yscrollcommand=scroll.set) # 为双击事件绑定事件处理方法 self.lb.bind("<Double-1>", self.click) def click(self, event): from tkinter import messagebox # 获取Listbox当前选中项 messagebox.showinfo(title=None, message=str(self.lb.curselection())) root = Tk() root.title("Listbox测试") # 改变窗口图标 root.iconbitmap('images/fklogo.ico') App(root) root.mainloop()
/******/ (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; /******/ /******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // 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 = 9); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * jQuery JavaScript Library v3.1.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2016-09-22T22:30Z */ ( 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 document = window.document; var getProto = Object.getPrototypeOf; var slice = arr.slice; var concat = arr.concat; 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 = {}; function DOMEval( code, doc ) { doc = doc || document; var script = doc.createElement( "script" ); script.text = code; doc.head.appendChild( script ).parentNode.removeChild( script ); } /* 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.1.1", // 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 ); }, // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }; 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 ); }, 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" && !jQuery.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 ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject( copy ) || ( copyIsArray = jQuery.isArray( copy ) ) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray( src ) ? src : []; } else { clone = src && jQuery.isPlainObject( src ) ? src : {}; } // 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() {}, isFunction: function( obj ) { return jQuery.type( obj ) === "function"; }, isArray: Array.isArray, isWindow: function( obj ) { return obj != null && obj === obj.window; }, 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 ) ); }, 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 ) { /* eslint-disable no-unused-vars */ // See https://github.com/eslint/eslint/issues/6125 var name; for ( name in obj ) { return false; } return true; }, type: function( 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; }, // Evaluates a script in a global context globalEval: function( code ) { DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, 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; }, // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // 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 concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. 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 ( !jQuery.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; }, now: Date.now, // 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 = jQuery.type( obj ); if ( type === "function" || jQuery.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.3 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-08-08 */ (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(), sortOrder = function( a, b ) { if ( a === b ) { hasDuplicate = true; } return 0; }, // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], pop = arr.pop, push_native = 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]", // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // 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 + "*" ), rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ), 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" ) }, 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-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint // Support: Firefox<24 // Workaround erroneous numeric interpretation of +"0x" return high !== high || escapedWhitespace ? escaped : high < 0 ? // BMP codepoint String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) 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(); }, disabledAncestor = addCombinator( function( elem ) { return elem.disabled === true && ("form" in elem || "label" in elem); }, { 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 arr[ preferredDoc.childNodes.length ].nodeType; } catch ( e ) { push = { apply: arr.length ? // Leverage slice if possible function( target, els ) { push_native.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 ) { if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { 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 && !compilerCache[ selector + " " ] && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { if ( nodeType !== 1 ) { newContext = context; newSelector = selector; // qSA looks outside Element context, which is not what we want // Thanks to Andrew Dupont for this workaround technique // Support: IE <=8 // Exclude object elements } else if ( context.nodeName.toLowerCase() !== "object" ) { // 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 + " " + toSelector( groups[i] ); } newSelector = groups.join( "," ); // Expand context for sibling selectors newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; } if ( newSelector ) { try { push.apply( results, newContext.querySelectorAll( newSelector ) ); return results; } catch ( qsaError ) { } 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 && disabledAncestor( 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 ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * 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 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 // Accessing iframe documents after unload throws "permission denied" errors (jQuery #13936) 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 ); } } /* 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 ) { // 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("~="); } // 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(".#.+[+~]"); } }); 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" ); } // 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 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 if ( a === document || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) { return -1; } 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 ) { return a === document ? -1 : b === document ? 1 : 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 ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); if ( support.matchesSelector && documentIsHTML && !compilerCache[ 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) {} } return Sizzle( expr, document, null, [ elem ] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { // Set document vars if needed 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 += ""; 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; }; }, "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 || elem.innerText || 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 ) { 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; 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 ) { 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; 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; var rsingleTag = ( /^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i ); var risSimple = /^.[^:#\[\.,]*$/; // Implement the identical functionality for filter and not function winnow( elements, qualifier, not ) { if ( jQuery.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; } ); } // Simple selector that can be filtered directly, removing non-Elements if ( risSimple.test( qualifier ) ) { return jQuery.filter( qualifier, elements, not ); } // Complex selector, compare the two sets, removing non-Elements qualifier = jQuery.filter( qualifier, elements ); return jQuery.grep( elements, function( elem ) { return ( indexOf.call( qualifier, elem ) > -1 ) !== not && elem.nodeType === 1; } ); } 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 ( jQuery.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 ( jQuery.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 ) { return elem.contentDocument || 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 = 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 ( jQuery.isFunction( arg ) ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && jQuery.type( 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 ) { var method; try { // Check for promise aspect first to privilege synchronous behavior if ( value && jQuery.isFunction( ( method = value.promise ) ) ) { method.call( value ).done( resolve ).fail( reject ); // Other thenables } else if ( value && jQuery.isFunction( ( method = value.then ) ) ) { method.call( value, resolve, reject ); // Other non-thenables } else { // Support: Android 4.0 only // Strict mode functions invoked without .call/.apply get global-object context resolve.call( undefined, value ); } // 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.call( 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 = jQuery.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 && jQuery.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 ( jQuery.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, jQuery.isFunction( onProgress ) ? onProgress : Identity, newDefer.notifyWith ) ); // fulfilled_handlers.add( ... ) tuples[ 1 ][ 3 ].add( resolve( 0, newDefer, jQuery.isFunction( onFulfilled ) ? onFulfilled : Identity ) ); // rejected_handlers.add( ... ) tuples[ 2 ][ 3 ].add( resolve( 0, newDefer, jQuery.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, // progress_callbacks.lock tuples[ 0 ][ 2 ].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 master Deferred master = 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 ) ) { master.resolveWith( resolveContexts, resolveValues ); } }; }; // Single- and empty arguments are adopted like Promise.resolve if ( remaining <= 1 ) { adoptValue( singleValue, master.done( updateFunc( i ) ).resolve, master.reject ); // Use .then() to unwrap secondary thenables (cf. gh-3000) if ( master.state() === "pending" || jQuery.isFunction( resolveValues[ i ] && resolveValues[ i ].then ) ) { return master.then(); } } // Multiple arguments are aggregated like Promise.all array elements while ( i-- ) { adoptValue( resolveValues[ i ], updateFunc( i ), master.reject ); } return master.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, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // 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 ( jQuery.type( 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 ( !jQuery.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; }; 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[ jQuery.camelCase( data ) ] = value; // Handle: [ owner, { properties } ] args } else { // Copy the properties one-by-one to the cache object for ( prop in data ) { cache[ jQuery.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 ][ jQuery.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 ( jQuery.isArray( key ) ) { // If key is an array of keys... // We always set camelCase keys, so remove that. key = key.map( jQuery.camelCase ); } else { key = jQuery.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 = jQuery.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 || jQuery.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 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. jQuery.contains( elem.ownerDocument, elem ) && jQuery.css( elem, "display" ) === "none"; }; var swap = function( elem, options, callback, args ) { 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.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; }; function adjustCSS( elem, prop, valueParts, tween ) { var adjusted, scale = 1, 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 = ( jQuery.cssNumber[ prop ] || unit !== "px" && +initial ) && rcssNum.exec( jQuery.css( elem, prop ) ); if ( initialInUnit && initialInUnit[ 3 ] !== unit ) { // Trust units reported by jQuery.css unit = unit || initialInUnit[ 3 ]; // Make sure we update the tween properties later on valueParts = valueParts || []; // Iteratively approximate from a nonzero starting point initialInUnit = +initial || 1; do { // If previous iteration zeroed out, double until we get *something*. // Use string for doubling so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply initialInUnit = initialInUnit / scale; jQuery.style( elem, prop, initialInUnit + unit ); // Update scale, tolerating zero or NaN from tween.cur() // Break the loop if scale is unchanged or perfect, or if we've just had enough. } while ( scale !== ( scale = currentValue() / initial ) && scale !== 1 && --maxIterations ); } 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 = ( /^$|\/(?:java|ecma)script/i ); // We have to close these tags to support XHTML (#13200) var wrapMap = { // Support: IE <=9 only option: [ 1, "<select multiple='multiple'>", "</select>" ], // 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, "", "" ] }; // Support: IE <=9 only wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; 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 && jQuery.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, contains, 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 ( jQuery.type( 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; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( fragment.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( ( elem = tmp[ j++ ] ) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } return fragment; } ( 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; } )(); var documentElement = document.documentElement; var rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|pointer|contextmenu|drag|drop)|click/, rtypenamespace = /^([^.]*)(?:\.(.+)|)/; function returnTrue() { return true; } function returnFalse() { return false; } // Support: IE <=9 only // See #13393 for more info 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 ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { 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 = {}; } 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 ) { // Make a writable jQuery.Event from the native event object var event = jQuery.event.fix( nativeEvent ); var i, j, ret, matched, handleObj, handlerQueue, args = new Array( arguments.length ), handlers = ( dataPriv.get( this, "events" ) || {} )[ 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() ) { // Triggered event must either 1) have no namespace, or 2) have namespace(s) // a subset or equal to those in the bound event (both can have no namespace). if ( !event.rnamespace || 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: jQuery.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 }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== safeActiveElement() && this.focus ) { this.focus(); return false; } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === safeActiveElement() && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) { this.click(); return false; } }, // For cross-browser consistency, don't fire native .click() on links _default: function( event ) { return jQuery.nodeName( event.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; } } } } }; 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 || jQuery.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, 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: function( event ) { var button = event.button; // Add which for key events if ( event.which == null && rkeyEvent.test( event.type ) ) { return event.charCode != null ? event.charCode : event.keyCode; } // Add which for click: 1 === left; 2 === middle; 3 === right if ( !event.which && button !== undefined && rmouseEvent.test( event.type ) ) { if ( button & 1 ) { return 1; } if ( button & 2 ) { return 3; } if ( button & 4 ) { return 2; } return 0; } return event.which; } }, jQuery.event.addProp ); // 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 /* eslint-disable max-len */ // See https://github.com/eslint/eslint/issues/3229 rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi, /* eslint-enable */ // Support: IE <=10 - 11, Edge 12 - 13 // 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, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g; function manipulationTarget( elem, content ) { if ( jQuery.nodeName( elem, "table" ) && jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ) { return elem.getElementsByTagName( "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 ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[ 1 ]; } else { elem.removeAttribute( "type" ); } return elem; } function cloneCopyEvent( src, dest ) { var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events; if ( dest.nodeType !== 1 ) { return; } // 1. Copy private data: events, handlers, etc. if ( dataPriv.hasData( src ) ) { pdataOld = dataPriv.access( src ); pdataCur = dataPriv.set( dest, pdataOld ); events = pdataOld.events; if ( events ) { delete pdataCur.handle; pdataCur.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 = concat.apply( [], args ); var fragment, first, scripts, hasScripts, node, doc, i = 0, l = collection.length, iNoClone = l - 1, value = args[ 0 ], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test( value ) ) ) { return collection.each( function( index ) { var self = collection.eq( index ); if ( isFunction ) { 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 ) { // Optional AJAX dependency, but won't run scripts if not present if ( jQuery._evalUrl ) { jQuery._evalUrl( node.src ); } } else { DOMEval( node.textContent.replace( rcleanScript, "" ), 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 && jQuery.contains( node.ownerDocument, node ) ) { setGlobalEval( getAll( node, "script" ) ); } node.parentNode.removeChild( node ); } } return elem; } jQuery.extend( { htmlPrefilter: function( html ) { return html.replace( rxhtmlTag, "<$1></$2>" ); }, clone: function( elem, dataAndEvents, deepDataAndEvents ) { var i, l, srcElements, destElements, clone = elem.cloneNode( true ), inPage = jQuery.contains( elem.ownerDocument, 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 rmargin = ( /^margin/ ); 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 ); }; ( 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; } div.style.cssText = "box-sizing:border-box;" + "position:relative;display:block;" + "margin:auto;border:1px;padding:1px;" + "top:1%;width:50%"; div.innerHTML = ""; documentElement.appendChild( container ); var divStyle = window.getComputedStyle( div ); pixelPositionVal = divStyle.top !== "1%"; // Support: Android 4.0 - 4.3 only, Firefox <=3 - 44 reliableMarginLeftVal = divStyle.marginLeft === "2px"; boxSizingReliableVal = divStyle.width === "4px"; // Support: Android 4.0 - 4.3 only // Some styles come back with percentage values, even though they shouldn't div.style.marginRight = "50%"; pixelMarginRightVal = divStyle.marginRight === "4px"; 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; } var pixelPositionVal, boxSizingReliableVal, pixelMarginRightVal, 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"; container.style.cssText = "border:0;width:8px;height:0;top:0;left:-9999px;" + "padding:0;margin-top:1px;position:absolute"; container.appendChild( div ); jQuery.extend( support, { pixelPosition: function() { computeStyleTests(); return pixelPositionVal; }, boxSizingReliable: function() { computeStyleTests(); return boxSizingReliableVal; }, pixelMarginRight: function() { computeStyleTests(); return pixelMarginRightVal; }, reliableMarginLeft: function() { computeStyleTests(); return reliableMarginLeftVal; } } ); } )(); function curCSS( elem, name, computed ) { var width, minWidth, maxWidth, ret, style = elem.style; computed = computed || getStyles( elem ); // Support: IE <=9 only // getPropertyValue is only needed for .css('filter') (#12537) if ( computed ) { ret = computed.getPropertyValue( name ) || computed[ name ]; if ( ret === "" && !jQuery.contains( elem.ownerDocument, 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.pixelMarginRight() && rnumnonpx.test( ret ) && rmargin.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 // 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]).+)/, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "Moz", "ms" ], emptyStyle = document.createElement( "div" ).style; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( name ) { // Shortcut for names that are not vendor prefixed if ( name in emptyStyle ) { return 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; } } } 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 augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i, val = 0; // If we already have the right measurement, avoid augmentation if ( extra === ( isBorderBox ? "border" : "content" ) ) { i = 4; // Otherwise initialize for horizontal or vertical properties } else { i = name === "width" ? 1 : 0; } for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var val, valueIsBorderBox = true, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Support: IE <=11 only // Running getBoundingClientRect on a disconnected node // in IE throws an error. if ( elem.getClientRects().length ) { val = elem.getBoundingClientRect()[ name ]; } // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test( val ) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "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, "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: { "float": "cssFloat" }, // 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 = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || 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) if ( type === "number" ) { 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 ) { 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 = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( origName ) || 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, name ) { jQuery.cssHooks[ name ] = { 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, name, extra ); } ) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var matches, styles = extra && getStyles( elem ), subtract = extra && augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ); // Convert to pixels if value adjustment is needed if ( subtract && ( matches = rcssNum.exec( value ) ) && ( matches[ 3 ] || "px" ) !== "px" ) { elem.style[ name ] = value; value = jQuery.css( elem, name ); } 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 ( !rmargin.test( prefix ) ) { 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 ( jQuery.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 && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { 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, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rrun = /queueHooks$/; function raf() { if ( timerId ) { window.requestAnimationFrame( raf ); jQuery.fx.tick(); } } // Animations created synchronously will run synchronously function createFxNow() { window.setTimeout( function() { fxNow = undefined; } ); return ( fxNow = jQuery.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 - 13 // Record all 3 overflow attributes because IE does not infer the shorthand // from identically-valued overflowX and overflowY 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 = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.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 ( percent < 1 && length ) { return remaining; } else { 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 ( jQuery.isFunction( result.stop ) ) { jQuery._queueHooks( animation.elem, animation.opts.queue ).stop = jQuery.proxy( result.stop, result ); } return result; } } jQuery.map( props, createTween, animation ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue } ) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } 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 ( jQuery.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 || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; // Go to the end state if fx are off or if document is hidden if ( jQuery.fx.off || document.hidden ) { 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 ( jQuery.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 && type !== false ) { 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 = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed 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 ); if ( timer() ) { jQuery.fx.start(); } else { jQuery.timers.pop(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = window.requestAnimationFrame ? window.requestAnimationFrame( raf ) : window.setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { if ( window.cancelAnimationFrame ) { window.cancelAnimationFrame( timerId ); } else { window.clearInterval( timerId ); } timerId = 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" && jQuery.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://html.spec.whatwg.org/multipage/infrastructure.html#strip-and-collapse-whitespace function stripAndCollapse( value ) { var tokens = value.match( rnothtmlwhite ) || []; return tokens.join( " " ); } function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, i = 0; if ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).addClass( value.call( this, j, getClass( this ) ) ); } ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; 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 ( jQuery.isFunction( value ) ) { return this.each( function( j ) { jQuery( this ).removeClass( value.call( this, j, getClass( this ) ) ); } ); } if ( !arguments.length ) { return this.attr( "class", "" ); } if ( typeof value === "string" && value ) { classes = value.match( rnothtmlwhite ) || []; 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; if ( typeof stateVal === "boolean" && type === "string" ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } if ( jQuery.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 ( type === "string" ) { // Toggle individual class names i = 0; self = jQuery( this ); classNames = value.match( rnothtmlwhite ) || []; 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, isFunction, 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; } isFunction = jQuery.isFunction( value ); return this.each( function( i ) { var val; if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { 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 ( jQuery.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 || !jQuery.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 ( jQuery.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 var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/; jQuery.extend( jQuery.event, { trigger: function( event, data, elem, onlyHandlers ) { var i, cur, tmp, bubbleType, ontype, handle, special, eventPath = [ elem || document ], type = hasOwn.call( event, "type" ) ? event.type : event, namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : []; cur = 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 && !jQuery.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() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( dataPriv.get( cur, "events" ) || {} )[ 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 && jQuery.isFunction( elem[ type ] ) && !jQuery.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; elem[ type ](); 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 ); } } } ); 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 ); }; } ); jQuery.fn.extend( { hover: function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); } } ); support.focusin = "onfocusin" in window; // 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() { var doc = this.ownerDocument || 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, 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 = jQuery.now(); var rquery = ( /\?/ ); // Cross-browser xml parsing jQuery.parseXML = function( data ) { var xml; 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 ) { xml = undefined; } if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + 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 ( jQuery.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 && jQuery.type( 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 = jQuery.isFunction( valueOrFunction ) ? valueOrFunction() : valueOrFunction; s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value == null ? "" : value ); }; // If an array was passed in, assume that it is an array of form elements. if ( jQuery.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 ( jQuery.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 ( jQuery.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() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // 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 - 13 // 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, append data to url if ( s.data ) { 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++ ) + 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 ); } // 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 ( jQuery.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._evalUrl = function( url ) { 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, "throws": true } ); }; jQuery.fn.extend( { wrapAll: function( html ) { var wrap; if ( this[ 0 ] ) { if ( jQuery.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 ( jQuery.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 isFunction = jQuery.isFunction( html ); return this.each( function( i ) { jQuery( this ).wrapAll( isFunction ? 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.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 = 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 requests if ( s.crossDomain ) { var script, callback; return { send: function( _, complete ) { script = jQuery( "<script>" ).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++ ) ); 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 = jQuery.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 && jQuery.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 ( jQuery.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; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) { jQuery.fn[ type ] = function( fn ) { return this.on( type, fn ); }; } ); jQuery.expr.pseudos.animated = function( elem ) { return jQuery.grep( jQuery.timers, function( fn ) { return elem === fn.elem; } ).length; }; /** * Gets a window from an element */ function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView; } 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 ( jQuery.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: function( options ) { // Preserve chaining for setter if ( arguments.length ) { return options === undefined ? this : this.each( function( i ) { jQuery.offset.setOffset( this, options, i ); } ); } var docElem, win, rect, doc, elem = this[ 0 ]; if ( !elem ) { return; } // Support: IE <=11 only // Running getBoundingClientRect on a // disconnected node in IE throws an error if ( !elem.getClientRects().length ) { return { top: 0, left: 0 }; } rect = elem.getBoundingClientRect(); // Make sure element is not hidden (display: none) if ( rect.width || rect.height ) { doc = elem.ownerDocument; win = getWindow( doc ); docElem = doc.documentElement; return { top: rect.top + win.pageYOffset - docElem.clientTop, left: rect.left + win.pageXOffset - docElem.clientLeft }; } // Return zeros for disconnected and hidden elements (gh-2310) return rect; }, position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, elem = this[ 0 ], parentOffset = { top: 0, left: 0 }; // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // because it is its only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // Assume getBoundingClientRect is there when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset = { top: parentOffset.top + jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ), left: parentOffset.left + jQuery.css( offsetParent[ 0 ], "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 ) { var win = getWindow( elem ); 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 ( jQuery.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.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 ); } } ); jQuery.parseJSON = JSON.parse; // 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 ( true ) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return jQuery; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } 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 ( !noGlobal ) { window.jQuery = window.$ = jQuery; } return jQuery; } ); /***/ }), /* 1 */ /***/ (function(module, exports) { /*! Waypoints - 4.0.1 Copyright © 2011-2016 Caleb Troughton Licensed under the MIT license. https://github.com/imakewebthings/waypoints/blob/master/licenses.txt */ (function() { 'use strict' var keyCounter = 0 var allWaypoints = {} /* http://imakewebthings.com/waypoints/api/waypoint */ function Waypoint(options) { if (!options) { throw new Error('No options passed to Waypoint constructor') } if (!options.element) { throw new Error('No element option passed to Waypoint constructor') } if (!options.handler) { throw new Error('No handler option passed to Waypoint constructor') } this.key = 'waypoint-' + keyCounter this.options = Waypoint.Adapter.extend({}, Waypoint.defaults, options) this.element = this.options.element this.adapter = new Waypoint.Adapter(this.element) this.callback = options.handler this.axis = this.options.horizontal ? 'horizontal' : 'vertical' this.enabled = this.options.enabled this.triggerPoint = null this.group = Waypoint.Group.findOrCreate({ name: this.options.group, axis: this.axis }) this.context = Waypoint.Context.findOrCreateByElement(this.options.context) if (Waypoint.offsetAliases[this.options.offset]) { this.options.offset = Waypoint.offsetAliases[this.options.offset] } this.group.add(this) this.context.add(this) allWaypoints[this.key] = this keyCounter += 1 } /* Private */ Waypoint.prototype.queueTrigger = function(direction) { this.group.queueTrigger(this, direction) } /* Private */ Waypoint.prototype.trigger = function(args) { if (!this.enabled) { return } if (this.callback) { this.callback.apply(this, args) } } /* Public */ /* http://imakewebthings.com/waypoints/api/destroy */ Waypoint.prototype.destroy = function() { this.context.remove(this) this.group.remove(this) delete allWaypoints[this.key] } /* Public */ /* http://imakewebthings.com/waypoints/api/disable */ Waypoint.prototype.disable = function() { this.enabled = false return this } /* Public */ /* http://imakewebthings.com/waypoints/api/enable */ Waypoint.prototype.enable = function() { this.context.refresh() this.enabled = true return this } /* Public */ /* http://imakewebthings.com/waypoints/api/next */ Waypoint.prototype.next = function() { return this.group.next(this) } /* Public */ /* http://imakewebthings.com/waypoints/api/previous */ Waypoint.prototype.previous = function() { return this.group.previous(this) } /* Private */ Waypoint.invokeAll = function(method) { var allWaypointsArray = [] for (var waypointKey in allWaypoints) { allWaypointsArray.push(allWaypoints[waypointKey]) } for (var i = 0, end = allWaypointsArray.length; i < end; i++) { allWaypointsArray[i][method]() } } /* Public */ /* http://imakewebthings.com/waypoints/api/destroy-all */ Waypoint.destroyAll = function() { Waypoint.invokeAll('destroy') } /* Public */ /* http://imakewebthings.com/waypoints/api/disable-all */ Waypoint.disableAll = function() { Waypoint.invokeAll('disable') } /* Public */ /* http://imakewebthings.com/waypoints/api/enable-all */ Waypoint.enableAll = function() { Waypoint.Context.refreshAll() for (var waypointKey in allWaypoints) { allWaypoints[waypointKey].enabled = true } return this } /* Public */ /* http://imakewebthings.com/waypoints/api/refresh-all */ Waypoint.refreshAll = function() { Waypoint.Context.refreshAll() } /* Public */ /* http://imakewebthings.com/waypoints/api/viewport-height */ Waypoint.viewportHeight = function() { return window.innerHeight || document.documentElement.clientHeight } /* Public */ /* http://imakewebthings.com/waypoints/api/viewport-width */ Waypoint.viewportWidth = function() { return document.documentElement.clientWidth } Waypoint.adapters = [] Waypoint.defaults = { context: window, continuous: true, enabled: true, group: 'default', horizontal: false, offset: 0 } Waypoint.offsetAliases = { 'bottom-in-view': function() { return this.context.innerHeight() - this.adapter.outerHeight() }, 'right-in-view': function() { return this.context.innerWidth() - this.adapter.outerWidth() } } window.Waypoint = Waypoint }()) ;(function() { 'use strict' function requestAnimationFrameShim(callback) { window.setTimeout(callback, 1000 / 60) } var keyCounter = 0 var contexts = {} var Waypoint = window.Waypoint var oldWindowLoad = window.onload /* http://imakewebthings.com/waypoints/api/context */ function Context(element) { this.element = element this.Adapter = Waypoint.Adapter this.adapter = new this.Adapter(element) this.key = 'waypoint-context-' + keyCounter this.didScroll = false this.didResize = false this.oldScroll = { x: this.adapter.scrollLeft(), y: this.adapter.scrollTop() } this.waypoints = { vertical: {}, horizontal: {} } element.waypointContextKey = this.key contexts[element.waypointContextKey] = this keyCounter += 1 if (!Waypoint.windowContext) { Waypoint.windowContext = true Waypoint.windowContext = new Context(window) } this.createThrottledScrollHandler() this.createThrottledResizeHandler() } /* Private */ Context.prototype.add = function(waypoint) { var axis = waypoint.options.horizontal ? 'horizontal' : 'vertical' this.waypoints[axis][waypoint.key] = waypoint this.refresh() } /* Private */ Context.prototype.checkEmpty = function() { var horizontalEmpty = this.Adapter.isEmptyObject(this.waypoints.horizontal) var verticalEmpty = this.Adapter.isEmptyObject(this.waypoints.vertical) var isWindow = this.element == this.element.window if (horizontalEmpty && verticalEmpty && !isWindow) { this.adapter.off('.waypoints') delete contexts[this.key] } } /* Private */ Context.prototype.createThrottledResizeHandler = function() { var self = this function resizeHandler() { self.handleResize() self.didResize = false } this.adapter.on('resize.waypoints', function() { if (!self.didResize) { self.didResize = true Waypoint.requestAnimationFrame(resizeHandler) } }) } /* Private */ Context.prototype.createThrottledScrollHandler = function() { var self = this function scrollHandler() { self.handleScroll() self.didScroll = false } this.adapter.on('scroll.waypoints', function() { if (!self.didScroll || Waypoint.isTouch) { self.didScroll = true Waypoint.requestAnimationFrame(scrollHandler) } }) } /* Private */ Context.prototype.handleResize = function() { Waypoint.Context.refreshAll() } /* Private */ Context.prototype.handleScroll = function() { var triggeredGroups = {} var axes = { horizontal: { newScroll: this.adapter.scrollLeft(), oldScroll: this.oldScroll.x, forward: 'right', backward: 'left' }, vertical: { newScroll: this.adapter.scrollTop(), oldScroll: this.oldScroll.y, forward: 'down', backward: 'up' } } for (var axisKey in axes) { var axis = axes[axisKey] var isForward = axis.newScroll > axis.oldScroll var direction = isForward ? axis.forward : axis.backward for (var waypointKey in this.waypoints[axisKey]) { var waypoint = this.waypoints[axisKey][waypointKey] if (waypoint.triggerPoint === null) { continue } var wasBeforeTriggerPoint = axis.oldScroll < waypoint.triggerPoint var nowAfterTriggerPoint = axis.newScroll >= waypoint.triggerPoint var crossedForward = wasBeforeTriggerPoint && nowAfterTriggerPoint var crossedBackward = !wasBeforeTriggerPoint && !nowAfterTriggerPoint if (crossedForward || crossedBackward) { waypoint.queueTrigger(direction) triggeredGroups[waypoint.group.id] = waypoint.group } } } for (var groupKey in triggeredGroups) { triggeredGroups[groupKey].flushTriggers() } this.oldScroll = { x: axes.horizontal.newScroll, y: axes.vertical.newScroll } } /* Private */ Context.prototype.innerHeight = function() { /*eslint-disable eqeqeq */ if (this.element == this.element.window) { return Waypoint.viewportHeight() } /*eslint-enable eqeqeq */ return this.adapter.innerHeight() } /* Private */ Context.prototype.remove = function(waypoint) { delete this.waypoints[waypoint.axis][waypoint.key] this.checkEmpty() } /* Private */ Context.prototype.innerWidth = function() { /*eslint-disable eqeqeq */ if (this.element == this.element.window) { return Waypoint.viewportWidth() } /*eslint-enable eqeqeq */ return this.adapter.innerWidth() } /* Public */ /* http://imakewebthings.com/waypoints/api/context-destroy */ Context.prototype.destroy = function() { var allWaypoints = [] for (var axis in this.waypoints) { for (var waypointKey in this.waypoints[axis]) { allWaypoints.push(this.waypoints[axis][waypointKey]) } } for (var i = 0, end = allWaypoints.length; i < end; i++) { allWaypoints[i].destroy() } } /* Public */ /* http://imakewebthings.com/waypoints/api/context-refresh */ Context.prototype.refresh = function() { /*eslint-disable eqeqeq */ var isWindow = this.element == this.element.window /*eslint-enable eqeqeq */ var contextOffset = isWindow ? undefined : this.adapter.offset() var triggeredGroups = {} var axes this.handleScroll() axes = { horizontal: { contextOffset: isWindow ? 0 : contextOffset.left, contextScroll: isWindow ? 0 : this.oldScroll.x, contextDimension: this.innerWidth(), oldScroll: this.oldScroll.x, forward: 'right', backward: 'left', offsetProp: 'left' }, vertical: { contextOffset: isWindow ? 0 : contextOffset.top, contextScroll: isWindow ? 0 : this.oldScroll.y, contextDimension: this.innerHeight(), oldScroll: this.oldScroll.y, forward: 'down', backward: 'up', offsetProp: 'top' } } for (var axisKey in axes) { var axis = axes[axisKey] for (var waypointKey in this.waypoints[axisKey]) { var waypoint = this.waypoints[axisKey][waypointKey] var adjustment = waypoint.options.offset var oldTriggerPoint = waypoint.triggerPoint var elementOffset = 0 var freshWaypoint = oldTriggerPoint == null var contextModifier, wasBeforeScroll, nowAfterScroll var triggeredBackward, triggeredForward if (waypoint.element !== waypoint.element.window) { elementOffset = waypoint.adapter.offset()[axis.offsetProp] } if (typeof adjustment === 'function') { adjustment = adjustment.apply(waypoint) } else if (typeof adjustment === 'string') { adjustment = parseFloat(adjustment) if (waypoint.options.offset.indexOf('%') > - 1) { adjustment = Math.ceil(axis.contextDimension * adjustment / 100) } } contextModifier = axis.contextScroll - axis.contextOffset waypoint.triggerPoint = Math.floor(elementOffset + contextModifier - adjustment) wasBeforeScroll = oldTriggerPoint < axis.oldScroll nowAfterScroll = waypoint.triggerPoint >= axis.oldScroll triggeredBackward = wasBeforeScroll && nowAfterScroll triggeredForward = !wasBeforeScroll && !nowAfterScroll if (!freshWaypoint && triggeredBackward) { waypoint.queueTrigger(axis.backward) triggeredGroups[waypoint.group.id] = waypoint.group } else if (!freshWaypoint && triggeredForward) { waypoint.queueTrigger(axis.forward) triggeredGroups[waypoint.group.id] = waypoint.group } else if (freshWaypoint && axis.oldScroll >= waypoint.triggerPoint) { waypoint.queueTrigger(axis.forward) triggeredGroups[waypoint.group.id] = waypoint.group } } } Waypoint.requestAnimationFrame(function() { for (var groupKey in triggeredGroups) { triggeredGroups[groupKey].flushTriggers() } }) return this } /* Private */ Context.findOrCreateByElement = function(element) { return Context.findByElement(element) || new Context(element) } /* Private */ Context.refreshAll = function() { for (var contextId in contexts) { contexts[contextId].refresh() } } /* Public */ /* http://imakewebthings.com/waypoints/api/context-find-by-element */ Context.findByElement = function(element) { return contexts[element.waypointContextKey] } window.onload = function() { if (oldWindowLoad) { oldWindowLoad() } Context.refreshAll() } Waypoint.requestAnimationFrame = function(callback) { var requestFn = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || requestAnimationFrameShim requestFn.call(window, callback) } Waypoint.Context = Context }()) ;(function() { 'use strict' function byTriggerPoint(a, b) { return a.triggerPoint - b.triggerPoint } function byReverseTriggerPoint(a, b) { return b.triggerPoint - a.triggerPoint } var groups = { vertical: {}, horizontal: {} } var Waypoint = window.Waypoint /* http://imakewebthings.com/waypoints/api/group */ function Group(options) { this.name = options.name this.axis = options.axis this.id = this.name + '-' + this.axis this.waypoints = [] this.clearTriggerQueues() groups[this.axis][this.name] = this } /* Private */ Group.prototype.add = function(waypoint) { this.waypoints.push(waypoint) } /* Private */ Group.prototype.clearTriggerQueues = function() { this.triggerQueues = { up: [], down: [], left: [], right: [] } } /* Private */ Group.prototype.flushTriggers = function() { for (var direction in this.triggerQueues) { var waypoints = this.triggerQueues[direction] var reverse = direction === 'up' || direction === 'left' waypoints.sort(reverse ? byReverseTriggerPoint : byTriggerPoint) for (var i = 0, end = waypoints.length; i < end; i += 1) { var waypoint = waypoints[i] if (waypoint.options.continuous || i === waypoints.length - 1) { waypoint.trigger([direction]) } } } this.clearTriggerQueues() } /* Private */ Group.prototype.next = function(waypoint) { this.waypoints.sort(byTriggerPoint) var index = Waypoint.Adapter.inArray(waypoint, this.waypoints) var isLast = index === this.waypoints.length - 1 return isLast ? null : this.waypoints[index + 1] } /* Private */ Group.prototype.previous = function(waypoint) { this.waypoints.sort(byTriggerPoint) var index = Waypoint.Adapter.inArray(waypoint, this.waypoints) return index ? this.waypoints[index - 1] : null } /* Private */ Group.prototype.queueTrigger = function(waypoint, direction) { this.triggerQueues[direction].push(waypoint) } /* Private */ Group.prototype.remove = function(waypoint) { var index = Waypoint.Adapter.inArray(waypoint, this.waypoints) if (index > -1) { this.waypoints.splice(index, 1) } } /* Public */ /* http://imakewebthings.com/waypoints/api/first */ Group.prototype.first = function() { return this.waypoints[0] } /* Public */ /* http://imakewebthings.com/waypoints/api/last */ Group.prototype.last = function() { return this.waypoints[this.waypoints.length - 1] } /* Private */ Group.findOrCreate = function(options) { return groups[options.axis][options.name] || new Group(options) } Waypoint.Group = Group }()) ;(function() { 'use strict' var Waypoint = window.Waypoint function isWindow(element) { return element === element.window } function getWindow(element) { if (isWindow(element)) { return element } return element.defaultView } function NoFrameworkAdapter(element) { this.element = element this.handlers = {} } NoFrameworkAdapter.prototype.innerHeight = function() { var isWin = isWindow(this.element) return isWin ? this.element.innerHeight : this.element.clientHeight } NoFrameworkAdapter.prototype.innerWidth = function() { var isWin = isWindow(this.element) return isWin ? this.element.innerWidth : this.element.clientWidth } NoFrameworkAdapter.prototype.off = function(event, handler) { function removeListeners(element, listeners, handler) { for (var i = 0, end = listeners.length - 1; i < end; i++) { var listener = listeners[i] if (!handler || handler === listener) { element.removeEventListener(listener) } } } var eventParts = event.split('.') var eventType = eventParts[0] var namespace = eventParts[1] var element = this.element if (namespace && this.handlers[namespace] && eventType) { removeListeners(element, this.handlers[namespace][eventType], handler) this.handlers[namespace][eventType] = [] } else if (eventType) { for (var ns in this.handlers) { removeListeners(element, this.handlers[ns][eventType] || [], handler) this.handlers[ns][eventType] = [] } } else if (namespace && this.handlers[namespace]) { for (var type in this.handlers[namespace]) { removeListeners(element, this.handlers[namespace][type], handler) } this.handlers[namespace] = {} } } /* Adapted from jQuery 1.x offset() */ NoFrameworkAdapter.prototype.offset = function() { if (!this.element.ownerDocument) { return null } var documentElement = this.element.ownerDocument.documentElement var win = getWindow(this.element.ownerDocument) var rect = { top: 0, left: 0 } if (this.element.getBoundingClientRect) { rect = this.element.getBoundingClientRect() } return { top: rect.top + win.pageYOffset - documentElement.clientTop, left: rect.left + win.pageXOffset - documentElement.clientLeft } } NoFrameworkAdapter.prototype.on = function(event, handler) { var eventParts = event.split('.') var eventType = eventParts[0] var namespace = eventParts[1] || '__default' var nsHandlers = this.handlers[namespace] = this.handlers[namespace] || {} var nsTypeList = nsHandlers[eventType] = nsHandlers[eventType] || [] nsTypeList.push(handler) this.element.addEventListener(eventType, handler) } NoFrameworkAdapter.prototype.outerHeight = function(includeMargin) { var height = this.innerHeight() var computedStyle if (includeMargin && !isWindow(this.element)) { computedStyle = window.getComputedStyle(this.element) height += parseInt(computedStyle.marginTop, 10) height += parseInt(computedStyle.marginBottom, 10) } return height } NoFrameworkAdapter.prototype.outerWidth = function(includeMargin) { var width = this.innerWidth() var computedStyle if (includeMargin && !isWindow(this.element)) { computedStyle = window.getComputedStyle(this.element) width += parseInt(computedStyle.marginLeft, 10) width += parseInt(computedStyle.marginRight, 10) } return width } NoFrameworkAdapter.prototype.scrollLeft = function() { var win = getWindow(this.element) return win ? win.pageXOffset : this.element.scrollLeft } NoFrameworkAdapter.prototype.scrollTop = function() { var win = getWindow(this.element) return win ? win.pageYOffset : this.element.scrollTop } NoFrameworkAdapter.extend = function() { var args = Array.prototype.slice.call(arguments) function merge(target, obj) { if (typeof target === 'object' && typeof obj === 'object') { for (var key in obj) { if (obj.hasOwnProperty(key)) { target[key] = obj[key] } } } return target } for (var i = 1, end = args.length; i < end; i++) { merge(args[0], args[i]) } return args[0] } NoFrameworkAdapter.inArray = function(element, array, i) { return array == null ? -1 : array.indexOf(element, i) } NoFrameworkAdapter.isEmptyObject = function(obj) { /* eslint no-unused-vars: 0 */ for (var name in obj) { return false } return true } Waypoint.adapters.push({ name: 'noframework', Adapter: NoFrameworkAdapter }) Waypoint.Adapter = NoFrameworkAdapter }()) ; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _jquery = __webpack_require__(0); var _jquery2 = _interopRequireDefault(_jquery); var _jquerySmoothScroll = __webpack_require__(8); var _jquerySmoothScroll2 = _interopRequireDefault(_jquerySmoothScroll); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var BackToTop = function () { function BackToTop() { _classCallCheck(this, BackToTop); this.backToTopIcon = (0, _jquery2.default)('.back-to-top a'); this.addSmoothScrolling(); } _createClass(BackToTop, [{ key: 'addSmoothScrolling', value: function addSmoothScrolling() { this.backToTopIcon.smoothScroll(); } }]); return BackToTop; }(); exports.default = BackToTop; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _jquery = __webpack_require__(0); var _jquery2 = _interopRequireDefault(_jquery); var _noframework = __webpack_require__(1); var _noframework2 = _interopRequireDefault(_noframework); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var RevealOnScroll = function () { function RevealOnScroll(elem, offset) { _classCallCheck(this, RevealOnScroll); this.lazyImages = (0, _jquery2.default)('.lazyload'); this.itemsToReveal = elem; this.offsetPercentage = (0, _jquery2.default)('.page-section'); this.hideInitially(); this.createWaypoints(); this.refreshWaypoints(); } _createClass(RevealOnScroll, [{ key: 'refreshWaypoints', value: function refreshWaypoints() { this.lazyImages.on('load', function () { Waypoint.refreshAll(); }); } }, { key: 'hideInitially', value: function hideInitially() { this.itemsToReveal.addClass('reveal-item'); } }, { key: 'createWaypoints', value: function createWaypoints() { var currentObject = this; // This will select the currently selected Object ( in this case we will use to select offsetPercentage) this.itemsToReveal.each(function () { var currentItem = this; // This will select all elements with a .reveal-item class new Waypoint({ element: currentItem, handler: function handler(direction) { if (direction == 'down') { (0, _jquery2.default)(currentItem).addClass('reveal-item--is-visible'); } else { (0, _jquery2.default)(currentItem).removeClass('reveal-item--is-visible'); } }, offset: currentObject.offsetPercentage }); }); } }]); return RevealOnScroll; }(); exports.default = RevealOnScroll; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); 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 _jquery = __webpack_require__(0); var _jquery2 = _interopRequireDefault(_jquery); var _noframework = __webpack_require__(1); var _noframework2 = _interopRequireDefault(_noframework); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SideNavMenu = function () { function SideNavMenu() { _classCallCheck(this, SideNavMenu); this.closeSideNav = (0, _jquery2.default)('#menuToggler'); this.SideNavTrigger = (0, _jquery2.default)('.page-section'); this.createSideNavWaypoint(); } _createClass(SideNavMenu, [{ key: 'createSideNavWaypoint', value: function createSideNavWaypoint() { var currentElement = this; new Waypoint({ element: this.SideNavTrigger[0], handler: function handler(direction) { if (direction == 'down') { currentElement.closeSideNav.prop('checked', false); } else { currentElement.closeSideNav.prop('checked', true); } } }); } }]); return SideNavMenu; }(); exports.default = SideNavMenu; /***/ }), /* 5 */, /* 6 */, /* 7 */, /* 8 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! * jQuery Smooth Scroll - v2.1.2 - 2017-01-19 * https://github.com/kswedberg/jquery-smooth-scroll * Copyright (c) 2017 Karl Swedberg * Licensed MIT */ (function(factory) { if (true) { // AMD. Register as an anonymous module. !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(0)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module === 'object' && module.exports) { // CommonJS factory(require('jquery')); } else { // Browser globals factory(jQuery); } }(function($) { var version = '2.1.2'; var optionOverrides = {}; var defaults = { exclude: [], excludeWithin: [], offset: 0, // one of 'top' or 'left' direction: 'top', // if set, bind click events through delegation // supported since jQuery 1.4.2 delegateSelector: null, // jQuery set of elements you wish to scroll (for $.smoothScroll). // if null (default), $('html, body').firstScrollable() is used. scrollElement: null, // only use if you want to override default behavior scrollTarget: null, // fn(opts) function to be called before scrolling occurs. // `this` is the element(s) being scrolled beforeScroll: function() {}, // fn(opts) function to be called after scrolling occurs. // `this` is the triggering element afterScroll: function() {}, // easing name. jQuery comes with "swing" and "linear." For others, you'll need an easing plugin // from jQuery UI or elsewhere easing: 'swing', // speed can be a number or 'auto' // if 'auto', the speed will be calculated based on the formula: // (current scroll position - target scroll position) / autoCoeffic speed: 400, // coefficient for "auto" speed autoCoefficient: 2, // $.fn.smoothScroll only: whether to prevent the default click action preventDefault: true }; var getScrollable = function(opts) { var scrollable = []; var scrolled = false; var dir = opts.dir && opts.dir === 'left' ? 'scrollLeft' : 'scrollTop'; this.each(function() { var el = $(this); if (this === document || this === window) { return; } if (document.scrollingElement && (this === document.documentElement || this === document.body)) { scrollable.push(document.scrollingElement); return false; } if (el[dir]() > 0) { scrollable.push(this); } else { // if scroll(Top|Left) === 0, nudge the element 1px and see if it moves el[dir](1); scrolled = el[dir]() > 0; if (scrolled) { scrollable.push(this); } // then put it back, of course el[dir](0); } }); if (!scrollable.length) { this.each(function() { // If no scrollable elements and <html> has scroll-behavior:smooth because // "When this property is specified on the root element, it applies to the viewport instead." // and "The scroll-behavior property of the … body element is *not* propagated to the viewport." // → https://drafts.csswg.org/cssom-view/#propdef-scroll-behavior if (this === document.documentElement && $(this).css('scrollBehavior') === 'smooth') { scrollable = [this]; } // If still no scrollable elements, fall back to <body>, // if it's in the jQuery collection // (doing this because Safari sets scrollTop async, // so can't set it to 1 and immediately get the value.) if (!scrollable.length && this.nodeName === 'BODY') { scrollable = [this]; } }); } // Use the first scrollable element if we're calling firstScrollable() if (opts.el === 'first' && scrollable.length > 1) { scrollable = [scrollable[0]]; } return scrollable; }; var rRelative = /^([\-\+]=)(\d+)/; $.fn.extend({ scrollable: function(dir) { var scrl = getScrollable.call(this, {dir: dir}); return this.pushStack(scrl); }, firstScrollable: function(dir) { var scrl = getScrollable.call(this, {el: 'first', dir: dir}); return this.pushStack(scrl); }, smoothScroll: function(options, extra) { options = options || {}; if (options === 'options') { if (!extra) { return this.first().data('ssOpts'); } return this.each(function() { var $this = $(this); var opts = $.extend($this.data('ssOpts') || {}, extra); $(this).data('ssOpts', opts); }); } var opts = $.extend({}, $.fn.smoothScroll.defaults, options); var clickHandler = function(event) { var escapeSelector = function(str) { return str.replace(/(:|\.|\/)/g, '\\$1'); }; var link = this; var $link = $(this); var thisOpts = $.extend({}, opts, $link.data('ssOpts') || {}); var exclude = opts.exclude; var excludeWithin = thisOpts.excludeWithin; var elCounter = 0; var ewlCounter = 0; var include = true; var clickOpts = {}; var locationPath = $.smoothScroll.filterPath(location.pathname); var linkPath = $.smoothScroll.filterPath(link.pathname); var hostMatch = location.hostname === link.hostname || !link.hostname; var pathMatch = thisOpts.scrollTarget || (linkPath === locationPath); var thisHash = escapeSelector(link.hash); if (thisHash && !$(thisHash).length) { include = false; } if (!thisOpts.scrollTarget && (!hostMatch || !pathMatch || !thisHash)) { include = false; } else { while (include && elCounter < exclude.length) { if ($link.is(escapeSelector(exclude[elCounter++]))) { include = false; } } while (include && ewlCounter < excludeWithin.length) { if ($link.closest(excludeWithin[ewlCounter++]).length) { include = false; } } } if (include) { if (thisOpts.preventDefault) { event.preventDefault(); } $.extend(clickOpts, thisOpts, { scrollTarget: thisOpts.scrollTarget || thisHash, link: link }); $.smoothScroll(clickOpts); } }; if (options.delegateSelector !== null) { this .off('click.smoothscroll', options.delegateSelector) .on('click.smoothscroll', options.delegateSelector, clickHandler); } else { this .off('click.smoothscroll') .on('click.smoothscroll', clickHandler); } return this; } }); var getExplicitOffset = function(val) { var explicit = {relative: ''}; var parts = typeof val === 'string' && rRelative.exec(val); if (typeof val === 'number') { explicit.px = val; } else if (parts) { explicit.relative = parts[1]; explicit.px = parseFloat(parts[2]) || 0; } return explicit; }; $.smoothScroll = function(options, px) { if (options === 'options' && typeof px === 'object') { return $.extend(optionOverrides, px); } var opts, $scroller, speed, delta; var explicitOffset = getExplicitOffset(options); var scrollTargetOffset = {}; var scrollerOffset = 0; var offPos = 'offset'; var scrollDir = 'scrollTop'; var aniProps = {}; var aniOpts = {}; if (explicitOffset.px) { opts = $.extend({link: null}, $.fn.smoothScroll.defaults, optionOverrides); } else { opts = $.extend({link: null}, $.fn.smoothScroll.defaults, options || {}, optionOverrides); if (opts.scrollElement) { offPos = 'position'; if (opts.scrollElement.css('position') === 'static') { opts.scrollElement.css('position', 'relative'); } } if (px) { explicitOffset = getExplicitOffset(px); } } scrollDir = opts.direction === 'left' ? 'scrollLeft' : scrollDir; if (opts.scrollElement) { $scroller = opts.scrollElement; if (!explicitOffset.px && !(/^(?:HTML|BODY)$/).test($scroller[0].nodeName)) { scrollerOffset = $scroller[scrollDir](); } } else { $scroller = $('html, body').firstScrollable(opts.direction); } // beforeScroll callback function must fire before calculating offset opts.beforeScroll.call($scroller, opts); scrollTargetOffset = explicitOffset.px ? explicitOffset : { relative: '', px: ($(opts.scrollTarget)[offPos]() && $(opts.scrollTarget)[offPos]()[opts.direction]) || 0 }; aniProps[scrollDir] = scrollTargetOffset.relative + (scrollTargetOffset.px + scrollerOffset + opts.offset); speed = opts.speed; // automatically calculate the speed of the scroll based on distance / coefficient if (speed === 'auto') { // $scroller[scrollDir]() is position before scroll, aniProps[scrollDir] is position after // When delta is greater, speed will be greater. delta = Math.abs(aniProps[scrollDir] - $scroller[scrollDir]()); // Divide the delta by the coefficient speed = delta / opts.autoCoefficient; } aniOpts = { duration: speed, easing: opts.easing, complete: function() { opts.afterScroll.call(opts.link, opts); } }; if (opts.step) { aniOpts.step = opts.step; } if ($scroller.length) { $scroller.stop().animate(aniProps, aniOpts); } else { opts.afterScroll.call(opts.link, opts); } }; $.smoothScroll.version = version; $.smoothScroll.filterPath = function(string) { string = string || ''; return string .replace(/^\//, '') .replace(/(?:index|default).[a-zA-Z]{3,4}$/, '') .replace(/\/$/, ''); }; // default options $.fn.smoothScroll.defaults = defaults; })); /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var _BackToTop = __webpack_require__(2); var _BackToTop2 = _interopRequireDefault(_BackToTop); var _RevealOnScroll = __webpack_require__(3); var _RevealOnScroll2 = _interopRequireDefault(_RevealOnScroll); var _jquery = __webpack_require__(0); var _jquery2 = _interopRequireDefault(_jquery); var _SideNav = __webpack_require__(4); var _SideNav2 = _interopRequireDefault(_SideNav); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var backToTop = new _BackToTop2.default(); new _RevealOnScroll2.default((0, _jquery2.default)('.back-to-top')); new _RevealOnScroll2.default((0, _jquery2.default)('.social-media')); var sideNavMenu = new _SideNav2.default(); /***/ }) /******/ ]);
goog.provide('ash.fsm.EntityStateMachine'); /* * This is a state machine for an entity. The state machine manages a set of states, * each of which has a set of component providers. When the state machine changes the state, it removes * components associated with the previous state and adds components associated with the new state. */ goog.require('ash.ext.Dictionary'); goog.require('ash.fsm.EntityState'); /** * Creates an EntityStateMachine. * @constructor * @param {ash.core.Entity} */ ash.fsm.EntityStateMachine = function(_at_entity) { this.entity = _at_entity; this.states = new ash.ext.Dictionary(); } /** * @type {ash.ext.Dictionary} */ ash.fsm.EntityStateMachine.prototype.states = null; /** * The current state of the state machine. * @type {ash.fsm.EntityState} */ ash.fsm.EntityStateMachine.prototype.currentState = null; /* * The entity whose state machine this is * @type {ash.core.Entity} */ ash.fsm.EntityStateMachine.prototype.entity = null; /** * Add a state to this state machine. * * @param {string} name The name of this state - used to identify it later in the changeState method call. * @param {ash.core.Entity} state The state. * @return {ash.fsm.EntityStateMachine} This state machine, so methods can be chained. */ ash.fsm.EntityStateMachine.prototype.addState = function(name, state) { this.states[name] = state; return this; }; /** * Create a new state in this state machine. * * @param {string} name The name of the new state - used to identify it later in the changeState method call. * @return {ash.fsm.EntityState} The new ash.fsm.EntityState object that is the state. This will need to be configured with * the appropriate component providers. */ ash.fsm.EntityStateMachine.prototype.createState = function(name) { var state; state = new ash.fsm.EntityState(); this.states[name] = state; return state; }; /** * Change to a new state. The components from the old state will be removed and the components * for the new state will be added. * * @param {string} name The name of the state to change to. */ ash.fsm.EntityStateMachine.prototype.changeState = function(name) { var newState, other, toAdd, type; newState = this.states[name]; if (!newState) { throw new Error("Entity state " + name + " doesn't exist"); } if (newState === this.currentState) { newState = null; return; } if (this.currentState) { toAdd = new ash.ext.Dictionary(); for (type in newState.providers) { toAdd[type] = newState.providers[type]; } for (type in this.currentState.providers) { other = toAdd[type]; if (other && other.getIdentifier() === this.currentState.providers[type].getIdentifier()) { delete toAdd[type]; } else { this.entity.remove(type); } } } else { toAdd = newState.providers; } for (type in toAdd) { this.entity.add(toAdd[type].getComponent()); } return this.currentState = newState; };
import React from 'react'; import styled from 'styled-components'; const Container = styled.p` line-height: ${props => (props.dark ? '27px' : '40px')}; `; const Subtitle = ({ children, ...props }) => ( <Container className="is-size-6 has-text-white" {...props}> {children} </Container> ); export default Subtitle;
# # Copyright 2019 GridGain Systems, Inc. and Contributors. # # Licensed under the GridGain Community Edition License (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.gridgain.com/products/software/community-edition/gridgain-community-edition-license # # 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. # """ Named constants that represents request operation codes. These are the way of telling Ignite server what one want to do in their request. """ OP_SUCCESS = 0 OP_RESOURCE_CLOSE = 0 OP_CACHE_GET = 1000 OP_CACHE_PUT = 1001 OP_CACHE_PUT_IF_ABSENT = 1002 OP_CACHE_GET_ALL = 1003 OP_CACHE_PUT_ALL = 1004 OP_CACHE_GET_AND_PUT = 1005 OP_CACHE_GET_AND_REPLACE = 1006 OP_CACHE_GET_AND_REMOVE = 1007 OP_CACHE_GET_AND_PUT_IF_ABSENT = 1008 OP_CACHE_REPLACE = 1009 OP_CACHE_REPLACE_IF_EQUALS = 1010 OP_CACHE_CONTAINS_KEY = 1011 OP_CACHE_CONTAINS_KEYS = 1012 OP_CACHE_CLEAR = 1013 OP_CACHE_CLEAR_KEY = 1014 OP_CACHE_CLEAR_KEYS = 1015 OP_CACHE_REMOVE_KEY = 1016 OP_CACHE_REMOVE_IF_EQUALS = 1017 OP_CACHE_REMOVE_KEYS = 1018 OP_CACHE_REMOVE_ALL = 1019 OP_CACHE_GET_SIZE = 1020 OP_CACHE_GET_NAMES = 1050 OP_CACHE_CREATE_WITH_NAME = 1051 OP_CACHE_GET_OR_CREATE_WITH_NAME = 1052 OP_CACHE_CREATE_WITH_CONFIGURATION = 1053 OP_CACHE_GET_OR_CREATE_WITH_CONFIGURATION = 1054 OP_CACHE_GET_CONFIGURATION = 1055 OP_CACHE_DESTROY = 1056 OP_QUERY_SCAN = 2000 OP_QUERY_SCAN_CURSOR_GET_PAGE = 2001 OP_QUERY_SQL = 2002 OP_QUERY_SQL_CURSOR_GET_PAGE = 2003 OP_QUERY_SQL_FIELDS = 2004 OP_QUERY_SQL_FIELDS_CURSOR_GET_PAGE = 2005 P_GET_BINARY_TYPE_NAME = 3000 OP_REGISTER_BINARY_TYPE_NAME = 3001 OP_GET_BINARY_TYPE = 3002 OP_PUT_BINARY_TYPE = 3003
(function () { 'use strict'; var controllerId = 'xignals'; angular.module('app').controller(controllerId, ['api', xignals]); function xignals(api) { var vm = this; api.getSurveys(function(err, surveys){ if(err){ return console.log(err.message); } vm.xignals = surveys; }); }; })();
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); const ejs = __importStar(require("ejs")); const path_1 = require("path"); const fbi_1 = require("fbi"); const { formatName, isValidObject } = fbi_1.utils; const { version } = require('../../package.json'); class TemplateNodeBase extends fbi_1.Template { constructor(factory) { super(factory); this.factory = factory; this.id = 'node-base'; this.renderer = ejs.render; this.features = []; } async gathering(flags) { var _a, _b; const defaultName = (_b = (_a = this.data.project) === null || _a === void 0 ? void 0 : _a.name) !== null && _b !== void 0 ? _b : 'project-demo'; this.data.factoryVersion = version; this.data.project = await this.prompt([ { type: 'input', name: 'name', message: 'Project name', initial({ enquirer }) { return defaultName; }, validate(value) { const name = formatName(value); return (name && true) || 'please input a valid project name'; } }, { type: 'input', name: 'description', message: 'Project description', initial({ state }) { return `${state.answers.name} description`; } }, ...(this.features.length > 0 ? [ { type: 'MultiSelect', name: 'features', message: `Choose features for your project:`, hint: '(Use <space> to select, <return> to submit)', choices: this.features, result(names) { return this.map(names); } } ] : []) ]); this.data.project.features = this.data.project.features || {}; } async writing() { var _a, _b; const debug = !!this.context.get('debug'); const isJs = (_b = (_a = this.data.project) === null || _a === void 0 ? void 0 : _a.features) === null || _b === void 0 ? void 0 : _b.javascript; this.files = { copy: ['.gitignore', '.editorconfig', '.prettierignore', isJs ? '' : 'tsconfig.json'].filter(Boolean), render: [ 'package.json', 'mrapi.config.ts', 'mrapi.config.js', 'README.md', { from: `src${isJs ? '-js' : ''}/**/*`, to: 'src' } ].filter(Boolean), renderOptions: { async: true, debug, compileDebug: debug } }; } async installing(flags) { const { project } = this.data; this.spinner.succeed(`Created project ${this.style.cyan.bold(project.name)}`); const { dependencies, devDependencies } = require(path_1.join(this.targetDir, 'package.json')); if (isValidObject(dependencies) || isValidObject(devDependencies)) { const installSpinner = this.createSpinner(`Installing dependencies...`).start(); try { await this.installDeps(this.targetDir, flags.packageManager, false); installSpinner.succeed(`Installed dependencies`); } catch (err) { installSpinner.fail('Failed to install dependencies. You can install them manually.'); this.error(err); } } } async ending() { const { project } = this.data; const projectName = this.style.cyan.bold(project.name); if (this.errors) { this.spinner.fail(`Failed to created project ${projectName}.`); this.error(this.errors); } console.log(` Next steps:`); if (this.data.subDirectory) { console.log(` $ ${this.style.cyan('cd ' + this.data.subDirectory)}`); } if (this.id === 'service') { console.log(` $ ${this.style.cyan('yarn setup')}`); } console.log(` $ ${this.style.cyan('yarn dev')} ${this.style.dim('launch the development server')}`); console.log(` $ ${this.style.cyan('yarn build')} ${this.style.dim('build project for production')} `); } } exports.default = TemplateNodeBase;
from ssh_cmd_manager import CmdManager CmdManager().start()
import React, {useContext, useEffect} from "react" import { Link } from "gatsby" import LandingLayout from "../components/Landing/LandingLayout" import Image from "../components/image" import SEO from "../components/seo" import MainFeed from "../components/MainFeed/MainFeed.js" import { ThemeProvider } from "styled-components" import {LocalStateContext} from "../context/LocalStateContext" import * as theme from "../theme/theme.js" const Landing = () => { return( <ThemeProvider theme={theme}> <LandingLayout> </LandingLayout> </ThemeProvider> )} export default Landing
import AddHandlerForEvent from "./AddHandlerForEvent"; import EventRollUpClose from "../../widgets/tradeIn/src/Events/EventRollUpClose"; import Animations from "./Animations"; export default class ApplicationSettings { constructor(element) { this.element = element; } set element(element) { this._element = typeof element ==='string'?document.querySelector(element):element; } get element() { return this._element; } addStyle(styles) { for (let style in styles) { this.element.style[style] = styles[style]; } } addSettings(settings) { for (let setting in settings) { this.element[setting] = settings[setting]; } } addEvents(events,target) { events.forEach((item)=>{ new AddHandlerForEvent(target,item.trigger,(event)=>{ item.options.event = event; item.handler(item.options) }); }); } addAnimate(animates) { animates.forEach((item)=>{ const delay = !item.delay ? 0 :item.delay; Animations.prototype[item.title](this.element,item.options,delay); }); } addAttribute(attributes) { attributes.forEach((item)=>{ this.element.setAttribute(item.title,item.value); }); } handler(item) { if (item.class) { this.element.classList.add(item.class); } if(item.id) { this.element.setAttribute('id',item.id) } if(item.styles) { this.addStyle(item.styles); } if(item.settings) { this.addSettings(item.settings); } if(item.attributes) { this.addAttribute(item.attributes); } if(item.events) { this.addEvents(item.events,this.element); } if(item.animates) { this.addAnimate(item.animates); } return this.element; } }
/*jslint browser: true, unparam: true, todo: true*/ /*globals define: true, MutationObserver: false, requestAnimationFrame: false, performance: false, btoa: false*/ 'use strict'; export default function (self) { self.getClippingRect = function (ele) { var boundingRect = self.position(self.parentNode), eleRect = self.position(ele), s = self.scrollOffset(self.canvas), clipRect = { x: 0, y: 0, h: 0, w: 0, }, parentRect = { x: -Infinity, y: -Infinity, h: Infinity, w: Infinity, }, columnHeaderCellHeight = self.getColumnHeaderCellHeight(), rowHeaderCellWidth = self.getRowHeaderCellWidth(); boundingRect.top -= s.top; boundingRect.left -= s.left; eleRect.top -= s.top; eleRect.left -= s.left; clipRect.h = boundingRect.top + boundingRect.height - ele.offsetTop - self.style.scrollBarWidth; clipRect.w = boundingRect.left + boundingRect.width - ele.offsetLeft - self.style.scrollBarWidth; clipRect.x = boundingRect.left + eleRect.left * -1 + rowHeaderCellWidth; clipRect.y = boundingRect.top + eleRect.top * -1 + columnHeaderCellHeight; return { x: clipRect.x > parentRect.x ? clipRect.x : parentRect.x, y: clipRect.y > parentRect.y ? clipRect.y : parentRect.y, h: clipRect.h < parentRect.h ? clipRect.h : parentRect.h, w: clipRect.w < parentRect.w ? clipRect.w : parentRect.w, }; }; self.clipElement = function (ele) { var clipRect = self.getClippingRect(ele); if (clipRect.w < 0) { clipRect.w = 0; } if (clipRect.h < 0) { clipRect.h = 0; } ele.style.clip = 'rect(' + clipRect.y + 'px,' + clipRect.w + 'px,' + clipRect.h + 'px,' + clipRect.x + 'px' + ')'; // INFO https://developer.mozilla.org/en-US/docs/Web/CSS/clip // clip has been "deprecated" for clipPath. Of course nothing but chrome // supports clip path, so we'll keep using clip until someday clipPath becomes // more widely support. The code below works correctly, but setting clipPath and clip // at the same time has undesirable results. // ele.style.clipPath = 'polygon(' // + clipRect.x + 'px ' + clipRect.y + 'px,' // + clipRect.x + 'px ' + clipRect.h + 'px,' // + clipRect.w + 'px ' + clipRect.h + 'px,' // + clipRect.w + 'px ' + clipRect.y + 'px' // + ')'; }; self.scrollOffset = function (e) { var x = 0, y = 0, scrollingElement = document.scrollingElement || { scrollLeft: 0, scrollTop: 0, }; while ( e.parentNode && e.nodeName !== 'CANVAS-DATAGRID' && e !== self.intf ) { if ( e.nodeType !== 'canvas-datagrid-tree' && e.nodeType !== 'canvas-datagrid-cell' ) { x -= e.scrollLeft; y -= e.scrollTop; } e = e.parentNode; } return { left: x - scrollingElement.scrollLeft, top: y - scrollingElement.scrollTop, }; }; self.resizeEditInput = function () { if (self.input && self.input.editCell) { var pos = self.canvas.getBoundingClientRect(), s = self.scrollOffset(self.intf), bm = self.style.gridBorderCollapse === 'collapse' ? 1 : 2, borderWidth = self.style.cellBorderWidth * bm, cell = self.getVisibleCellByIndex( self.input.editCell.columnIndex, self.input.editCell.rowIndex, ) || { x: -100, y: -100, height: 0, width: 0 }; if (self.mobile) { self.input.style.left = '0'; self.input.style.top = self.height - self.style.mobileEditInputHeight - borderWidth - 1 + 'px'; self.input.style.height = self.style.mobileEditInputHeight + 'px'; self.input.style.width = self.width - borderWidth - 1 + 'px'; return; } self.input.style.left = pos.left + cell.x + self.canvasOffsetLeft - s.left + 'px'; self.input.style.top = pos.top + cell.y - self.style.cellBorderWidth + self.canvasOffsetTop - s.top + 'px'; self.input.style.height = cell.height - borderWidth + 'px'; self.input.style.width = cell.width - self.style.cellPaddingLeft + 'px'; self.clipElement(self.input); } }; self.position = function (e, ignoreScrollOffset) { var x = 0, y = 0, s = e, h, w; let calculatedTree = false; while (e.offsetParent && e.nodeName !== 'CANVAS-DATAGRID') { const isTree = e.nodeType === 'canvas-datagrid-tree'; if (!isTree || !calculatedTree) { x += e.offsetLeft; y += e.offsetTop; h = e.offsetHeight; w = e.offsetWidth; } if (isTree) calculatedTree = true; e = e.offsetParent; } if (ignoreScrollOffset) { return { left: x, top: y, height: h, width: w }; } e = s; s = self.scrollOffset(e); return { left: x + s.left, top: y + s.top, height: h, width: w }; }; self.getLayerPos = function (e) { var rect = self.canvas.getBoundingClientRect(), pos = { x: e.clientX - rect.left, y: e.clientY - rect.top, }; if (self.isChildGrid) { pos.x -= self.canvasOffsetLeft; pos.y -= self.canvasOffsetTop; } return { x: pos.x, y: pos.y, rect: rect, }; }; /** * Ends editing, optionally aborting the edit. * @memberof canvasDatagrid * @name endEdit * @method * @param {boolean} abort When true, abort the edit. */ self.endEdit = function (abort) { var cell = self.input.editCell, y = cell.rowIndex; function abortEdit() { abort = true; } if ( self.dispatchEvent('beforeendedit', { cell: cell, newValue: self.input.value, oldValue: cell.value, abort: abortEdit, input: self.input, }) ) { return false; } if (self.input.value !== cell.value && !abort) { self.changes[y] = self.changes[y] || {}; self.changes[y][cell.header.name] = self.input.value; if (!cell.data) { self.originalData[cell.boundRowIndex] = {}; cell.data = self.originalData[cell.boundRowIndex]; } cell.data[cell.header.name] = self.input.value; if (y === self.viewData.length) { if ( self.dispatchEvent('newrow', { value: self.input.value, defaultValue: cell.value, aborted: abort, cell: cell, input: self.input, }) ) { return false; } self.addRow(cell.data); self.createNewRowData(); } self.draw(true); } if (self.input.parentNode) { self.input.parentNode.removeChild(self.input); } self.intf.focus(); self.dispatchEvent('endedit', { cell: cell, value: self.input.value, aborted: abort, input: self.input, }); self.input = undefined; return true; }; /** * Begins editing at cell x, row y. * @memberof canvasDatagrid * @name beginEditAt * @method * @param {number} x The column index of the cell to edit. * @param {number} y The row index of the cell to edit. * @param {boolean} inEnterMode If true, starting to type in cell will replace the * cell's previous value instead of appending, and using the arrow keys will allow * the user to navigate to adjacent cells instead of moving the text cursor around * (default is false, and means user is in 'edit' mode). */ self.beginEditAt = function (x, y, NativeEvent, inEnterMode = false) { if (!self.attributes.editable) { return; } if (self.input) { self.endEdit(); } var cell = self.getVisibleCellByIndex(x, y), s = self.getSchema(), adjacentCells, enumItems, enu, option, valueInEnum; if (!(cell && cell.header)) { return; } //HACK for IE10, does not like literal enum enu = cell.header['enum']; if ( self.dispatchEvent('beforebeginedit', { cell: cell, NativeEvent: NativeEvent, }) ) { return false; } self.scrollIntoView(x, y); self.setActiveCell(x, y); adjacentCells = self.getAdjacentCells(); if (enu) { self.input = document.createElement('select'); } else { self.input = document.createElement( self.attributes.multiLine ? 'textarea' : 'input', ); } cell = self.getVisibleCellByIndex(x, y); //HACK on mobile devices sometimes edit can begin without the cell being in view, I don't know how. if (!cell) { return; } if (enu) { // add enums if (typeof enu === 'function') { enumItems = enu.apply(self.intf, [{ cell: cell }]); } else if (Array.isArray(enu)) { enumItems = enu; } enumItems.forEach(function (e) { var i = document.createElement('option'), val, title; if (Array.isArray(e)) { val = e[0]; title = e[1]; } else { val = e; title = e; } if (val === cell.value) { valueInEnum = true; } i.value = val; i.innerHTML = title; self.input.appendChild(i); }); if (!valueInEnum) { option = document.createElement('option'); option.value = cell.value; option.innerHTML = cell.value; self.input.appendChild(option); } self.input.addEventListener('change', function () { self.endEdit(); self.draw(true); }); } // if the user has not prevented the default action, append to the body if ( !self.dispatchEvent('appendeditinput', { cell: cell, input: self.input }) ) { document.body.appendChild(self.input); } self.createInlineStyle( self.input, self.mobile ? 'canvas-datagrid-edit-mobile-input' : 'canvas-datagrid-edit-input', ); self.input.style.position = 'absolute'; self.input.editCell = cell; self.resizeEditInput(); self.input.style.zIndex = self.style.editCellZIndex; self.input.style.fontSize = parseInt(self.style.editCellFontSize, 10) * self.scale + 'px'; var cellValueIsEmpty = [null, undefined].indexOf(cell.value) !== -1; var shouldClearCellValue = cellValueIsEmpty || inEnterMode; self.input.value = shouldClearCellValue ? '' : cell.value; self.input.focus(); self.input.addEventListener('click', self.stopPropagation); self.input.addEventListener('dblclick', self.stopPropagation); self.input.addEventListener('mouseup', self.stopPropagation); self.input.addEventListener('mousedown', self.stopPropagation); self.input.addEventListener('keydown', function (e) { var nx = cell.columnIndex, ny = cell.rowIndex; if (e.key === 'Escape') { self.endEdit(true); // end edit and abort the value change self.draw(true); } else if (e.key === 'Enter' && self.attributes.multiLine && e.altKey) { self.input.value = self.input.value + '\n'; self.input.scrollTop = self.input.scrollHeight; } else if (e.key === 'Enter') { self.endEdit(); // Move to cell in next or previous row var nextRowIndex = e.shiftKey ? Math.max(0, ny - 1) : Math.min(ny + 1, self.viewData.length - 1); if (nextRowIndex !== ny) { self.scrollIntoView(nx, nextRowIndex); self.setActiveCell(nx, nextRowIndex); } self.draw(true); } else if ( ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key) && inEnterMode ) { switch (e.key) { case 'ArrowUp': ny = Math.max(0, ny - 1); break; case 'ArrowDown': ny = Math.min(ny + 1, self.viewData.length - 1); break; case 'ArrowLeft': nx = Math.max(nx - 1, 0); break; case 'ArrowRight': nx = adjacentCells.right; break; } self.endEdit(); self.scrollIntoView(nx, ny); self.setActiveCell(nx, ny); self.draw(true); } else if (e.key === 'Tab') { e.preventDefault(); if (!self.endEdit()) { return; } if (e.shiftKey) { nx = adjacentCells.left; } else { nx = adjacentCells.right; } if (adjacentCells.left === x && e.shiftKey) { nx = adjacentCells.last; ny -= 1; } if (adjacentCells.right === x && !e.shiftKey) { nx = adjacentCells.first; ny += 1; } if (ny < 0) { ny = self.viewData.length - 1; } if (ny > self.viewData.length - 1) { ny = 0; } self.scrollIntoView(nx, ny); self.beginEditAt(nx, ny, e); } }); self.dispatchEvent('beginedit', { cell: cell, input: self.input }); }; self.createInlineStyle = function (el, className) { var css = { 'canvas-datagrid-button-wrapper': { display: 'inline-block', padding: self.style.buttonPadding, borderWidth: '1px', borderStyle: 'solid', borderColor: self.style.buttonBorderColor, cursor: 'pointer', background: self.style.buttonBackgroundColor, userSelect: 'none', }, 'canvas-datagrid-button-wrapper:hover': { borderColor: self.style.buttonBorderColor, background: self.style.buttonHoverBackgroundColor, }, 'canvas-datagrid-button-wrapper:active': { borderColor: self.style.buttonActiveBorderColor, background: self.style.buttonActiveBackgroundColor, }, 'canvas-datagrid-button-icon': { width: '18px', height: '18px', display: 'inline-block', verticalAlign: 'middle', }, 'canvas-datagrid-button-arrow': { display: 'inline-block', color: self.style.buttonArrowColor, fontSize: '9px', }, 'canvas-datagrid-button-menu-item-mobile': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, color: 'inherit', background: 'inherit', margin: self.style.contextMenuItemMargin, borderRadius: self.style.contextMenuItemBorderRadius, verticalAlign: 'middle', }, 'canvas-datagrid-button-menu-item': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, color: 'inherit', background: 'inherit', margin: self.style.contextMenuItemMargin, borderRadius: self.style.contextMenuItemBorderRadius, verticalAlign: 'middle', }, 'canvas-datagrid-button-menu-item:hover': { background: self.style.contextMenuHoverBackground, color: self.style.contextMenuHoverColor, }, 'canvas-datagrid-button-menu-label': { margin: self.style.contextMenuLabelMargin, display: self.style.contextMenuLabelDisplay, minWidth: self.style.contextMenuLabelMinWidth, maxWidth: self.style.contextMenuLabelMaxWidth, }, 'canvas-datagrid-button-menu-mobile': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextMenuBorder, padding: self.style.contextMenuPadding, borderRadius: self.style.contextMenuBorderRadius, opacity: self.style.contextMenuOpacity, overflow: 'hidden', whiteSpace: 'nowrap', }, 'canvas-datagrid-button-menu': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextMenuBorder, padding: self.style.contextMenuPadding, borderRadius: self.style.contextMenuBorderRadius, opacity: self.style.contextMenuOpacity, overflow: 'hidden', whiteSpace: 'nowrap', cursor: self.style.contextMenuCursor, }, 'canvas-datagrid-context-menu-filter-input': { height: '19px', verticalAlign: 'bottom', marginLeft: '2px', padding: '0', background: self.style.contextFilterInputBackground, color: self.style.contextFilterInputColor, border: self.style.contextFilterInputBorder, borderRadius: self.style.contextFilterInputBorderRadius, lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextFilterInputFontFamily, fontSize: self.style.contextFilterInputFontSize, }, 'canvas-datagrid-context-menu-filter-button': { height: '19px', verticalAlign: 'bottom', marginLeft: '2px', padding: '0', background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextFilterButtonBorder, borderRadius: self.style.contextFilterButtonBorderRadius, lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFilterButtonFontFamily, fontSize: self.style.contextMenuFilterButtonFontSize, }, 'canvas-datagrid-context-child-arrow': { cssFloat: 'right', color: self.style.childContextMenuArrowColor, fontSize: self.style.contextMenuChildArrowFontSize, fontFamily: self.style.contextMenuFontFamily, verticalAlign: 'middle', }, 'canvas-datagrid-autocomplete': { fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextMenuBorder, padding: self.style.contextMenuPadding, borderRadius: self.style.contextMenuBorderRadius, opacity: self.style.contextMenuOpacity, position: 'absolute', zIndex: 9999, overflow: 'hidden', }, 'canvas-datagrid-autocomplete-item': { background: self.style.contextMenuBackground, color: self.style.contextMenuColor, }, 'canvas-datagrid-autocomplete-item:hover': { background: self.style.contextMenuHoverBackground, color: self.style.contextMenuHoverColor, }, 'canvas-datagrid-canvas': { position: 'absolute', zIndex: '-1', }, 'canvas-datagrid': { display: 'block', }, 'canvas-datagrid-control-input': { position: 'fixed', top: '-5px', left: '-5px', border: 'none', opacity: '0', cursor: 'pointer', width: '1px', height: '1px', lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, }, 'canvas-datagrid-edit-mobile-input': { boxSizing: 'content-box', outline: 'none', margin: '0', padding: '0 0 0 0', lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.mobileEditFontFamily, fontSize: self.style.mobileEditFontSize, border: self.style.editCellBorder, color: self.style.editCellColor, background: self.style.editCellBackgroundColor, appearance: 'none', webkitAppearance: 'none', mozAppearance: 'none', borderRadius: '0', }, 'canvas-datagrid-edit-input': { boxSizing: 'content-box', outline: 'none', margin: '0', padding: '0 0 0 ' + self.style.editCellPaddingLeft + 'px', lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.editCellFontFamily, fontSize: self.style.editCellFontSize, boxShadow: self.style.editCellBoxShadow, border: self.style.editCellBorder, color: self.style.editCellColor, background: self.style.editCellBackgroundColor, appearance: 'none', webkitAppearance: 'none', mozAppearance: 'none', borderRadius: '0', }, 'canvas-datagrid-context-menu-item-mobile': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, color: 'inherit', background: 'inherit', margin: self.style.contextMenuItemMargin, borderRadius: self.style.contextMenuItemBorderRadius, verticalAlign: 'middle', }, 'canvas-datagrid-context-menu-item': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, color: 'inherit', background: 'inherit', margin: self.style.contextMenuItemMargin, borderRadius: self.style.contextMenuItemBorderRadius, verticalAlign: 'middle', }, 'canvas-datagrid-context-menu-item:hover': { background: self.style.contextMenuHoverBackground, color: self.style.contextMenuHoverColor, }, 'canvas-datagrid-context-menu-label': { margin: self.style.contextMenuLabelMargin, display: self.style.contextMenuLabelDisplay, minWidth: self.style.contextMenuLabelMinWidth, maxWidth: self.style.contextMenuLabelMaxWidth, }, 'canvas-datagrid-context-menu-mobile': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextMenuBorder, padding: self.style.contextMenuPadding, borderRadius: self.style.contextMenuBorderRadius, opacity: self.style.contextMenuOpacity, overflow: 'hidden', whiteSpace: 'nowrap', }, 'canvas-datagrid-context-menu': { lineHeight: 'normal', fontWeight: 'normal', fontFamily: self.style.contextMenuFontFamily, fontSize: self.style.contextMenuFontSize, background: self.style.contextMenuBackground, color: self.style.contextMenuColor, border: self.style.contextMenuBorder, padding: self.style.contextMenuPadding, borderRadius: self.style.contextMenuBorderRadius, opacity: self.style.contextMenuOpacity, overflow: 'hidden', whiteSpace: 'nowrap', cursor: self.style.contextMenuCursor, }, 'canvas-datagrid-invalid-search-regExp': { background: self.style.contextMenuFilterInvalidExpresion, }, }; if (css[className]) { Object.keys(css[className]).map(function (prop) { el.style[prop] = css[className][prop]; }); } return; }; self.appendTo = function (e) { self.parentNode = e; self.setDom(); }; self.setDom = function () { if (self.isChildGrid) { self.parentGrid = self.parentNode.parentGrid; self.ctx = self.parentGrid.context; self.canvas = self.parentGrid.canvas; self.controlInput = self.parentGrid.controlInput; self.eventParent = self.canvas; } else { self.controlInput = self.controlInput || document.createElement('input'); self.controlInput.onblur = self.intf.blur; self.createInlineStyle( self.controlInput, 'canvas-datagrid-control-input', ); self.isChildGrid = false; self.parentDOMNode = self.parentNode; self.parentIsCanvas = /^canvas$/i.test(self.parentDOMNode.tagName); if (self.parentIsCanvas) { self.canvas = self.parentDOMNode; } else { self.canvas = document.createElement('canvas'); self.parentDOMNode.appendChild(self.canvas); } document.body.appendChild(self.controlInput); self.createInlineStyle(self.canvas, 'canvas-datagrid'); self.ctx = self.canvas.getContext('2d'); self.ctx.textBaseline = 'alphabetic'; self.eventParent = self.canvas; } self.parentNodeStyle = self.canvas.style; self.controlInput.setAttribute('readonly', true); self.controlInput.addEventListener('blur', function (e) { if (e.target !== self.canvas) { self.hasFocus = false; } }); self.eventParent.addEventListener('scroll', self.resize, false); self.eventParent.addEventListener('touchstart', self.touchstart, false); self.eventParent.addEventListener('mouseup', self.mouseup, false); self.eventParent.addEventListener('mousedown', self.mousedown, false); self.eventParent.addEventListener('dblclick', self.dblclick, false); self.eventParent.addEventListener('click', self.click, false); document.body.addEventListener('mousemove', self.mousemove); self[self.isChildGrid ? 'parentGrid' : 'eventParent'].addEventListener( 'wheel', self.scrollWheel, false, ); self.canvas.addEventListener('contextmenu', self.contextmenuEvent, false); self.controlInput.addEventListener('copy', self.copy); self.controlInput.addEventListener('cut', self.cut); self.controlInput.addEventListener('paste', self.paste); self.controlInput.addEventListener('keypress', self.keypress, false); self.controlInput.addEventListener('keyup', self.keyup, false); self.controlInput.addEventListener('keydown', self.keydown, false); window.addEventListener('resize', self.resize); }; }
from typing import Any, Generic, List, TypeVar T = TypeVar("T") class ListBackedContainer(Generic[T]): def __init__(self) -> None: self._data: List[T] = [] self._iter_index = 0 def __eq__(self, other: Any) -> bool: return isinstance(other, ListBackedContainer) and self._data == other._data def __len__(self) -> int: return len(self._data) def __setitem__(self, key: int, value: T) -> None: self._data[key] = value def __getitem__(self, key: int) -> T: return self._data[key] def __contains__(self, item: T) -> bool: return item in self._data def __iter__(self) -> "ListBackedContainer[T]": self._iter_index = 0 return self def __next__(self) -> T: if self._iter_index >= len(self._data): raise StopIteration output = self._data[self._iter_index] self._iter_index += 1 return output def __repr__(self) -> str: output = f"{type(self).__name__}([" output += ", ".join(str(d) for d in self._data) output += "])" return output
/** * Copyright 2017 Intel Corporation * * 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 m = require('mithril') const _ = require('lodash') const sjcl = require('sjcl') const { createHash } = require('crypto') const secp256k1 = require('sawtooth-sdk/signing/secp256k1') const { Transaction, TransactionHeader, TransactionList } = require('sawtooth-sdk/protobuf') const modals = require('../components/modals') const api = require('../services/api') const { PayloadError } = require('../utils/errors') const ENCRYPTED_KEY = 'fish_net.encryptedKey' const TNT_FAMILY = { NAME: 'grid_track_and_trace', VERSION: '1.0', NAMESPACE: 'a43b46' } const PIKE_FAMILY = { NAME: 'pike', VERSION: '0.1', NAMESPACE: 'cad11d' } const context = new secp256k1.Secp256k1Context() let privateKey = null let signerPublicKey = null let batcherPublicKey = null const setBatcherPubkey = () => { return api.get('info') .then(({ pubkey }) => { batcherPublicKey = pubkey }) } setBatcherPubkey() const requestPassword = () => { let password = null return modals.show(modals.BasicModal, { title: 'Enter Password', acceptText: 'Submit', body: m('.container', [ m('.mb-4', 'Please confirm your password to unlock your signing key.'), m('input.form-control', { type: 'password', oninput: m.withAttr('value', value => { password = value }) }) ]) }) .then(() => password) } const createTxn = payload => { let value, family if (_.isPlainObject(payload)) { if (payload.payload !== undefined) { value = payload.payload family = (payload.family ? payload.family : TNT_FAMILY.NAME) } else { throw new PayloadError(`Payloads should be in the form { family: String, payload: Uint8Array }`) } } else { value = payload family = TNT_FAMILY.NAME } let fields switch(family) { case PIKE_FAMILY.NAME: fields = PIKE_FAMILY break default: fields = TNT_FAMILY } const header = TransactionHeader.encode({ signerPublicKey, batcherPublicKey: signerPublicKey, familyName: fields.NAME, familyVersion: fields.VERSION, inputs: [fields.NAMESPACE], outputs: [fields.NAMESPACE], nonce: (Math.random() * 10 ** 18).toString(36), payloadSha512: createHash('sha512').update(value).digest('hex'), }).finish() return Transaction.create({ value, header, headerSignature: context.sign(header, privateKey) }) } const encodeTxns = transactions => { return TransactionList.encode({ transactions }).finish() } /** * Generates a new private key, saving it it to memory and storage (encrypted). * Returns both a public key and the encrypted private key. */ const makePrivateKey = password => { privateKey = context.newRandomPrivateKey() signerPublicKey = context.getPublicKey(privateKey).asHex() const encryptedKey = sjcl.encrypt(password, privateKey.asHex()) window.localStorage.setItem(ENCRYPTED_KEY, encryptedKey) return { encryptedKey, publicKey: signerPublicKey } } /** * Saves an encrypted key to storage, and the decrypted version in memory. */ const setPrivateKey = (password, encryptedKey) => { const privateKeyHex = sjcl.decrypt(password, encryptedKey) privateKey = secp256k1.Secp256k1PrivateKey.fromHex(privateKeyHex) signerPublicKey = context.getPublicKey(privateKey).asHex() window.localStorage.setItem(ENCRYPTED_KEY, encryptedKey) return encryptedKey } /** * Clears the users private key from memory and storage. */ const clearPrivateKey = () => { const encryptedKey = window.localStorage.getItem(ENCRYPTED_KEY) window.localStorage.removeItem(ENCRYPTED_KEY) privateKey = null signerPublicKey = null return encryptedKey } /** * Returns the user's private key as promised, requesting password as needed. */ const getPrivateKey = () => { return Promise.resolve() .then(() => { if (privateKey) return privateKey.asHex() const encryptedKey = window.localStorage.getItem(ENCRYPTED_KEY) return requestPassword() .then(password => sjcl.decrypt(password, encryptedKey)) }) } /** * Re-encrypts a private key with a new password. */ const changePassword = password => { return getPrivateKey() .then(privateKey => { const encryptedKey = sjcl.encrypt(password, privateKey) window.localStorage.setItem(ENCRYPTED_KEY, encryptedKey) return encryptedKey }) } /** * Wraps a Protobuf payload in a TransactionList and submits it to the API. * Prompts user for their password if their private key is not in memory. */ const submit = (payloads, wait = false) => { if (!_.isArray(payloads)) payloads = [payloads] return Promise.resolve() .then(() => { if (privateKey) return return requestPassword() .then(password => { const encryptedKey = window.localStorage.getItem(ENCRYPTED_KEY) setPrivateKey(password, encryptedKey) }) }) .then(() => { if (batcherPublicKey) return return setBatcherPubkey() }) .then(() => { const txns = payloads.map(payload => createTxn(payload)) const txnList = encodeTxns(txns) return api.postBinary(`batches${wait ? '?wait' : ''}`, txnList, 'sawtooth') }) } module.exports = { makePrivateKey, setPrivateKey, clearPrivateKey, getPrivateKey, changePassword, submit }
import logging import os import random import time from breezypythongui import EasyFrame from battlefield import Battlefield from battlefield_ui import BattlefieldUI from battleship_client import BattleshipClient # Without this, nothing shows up... logging.basicConfig() logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) grpc_host = os.getenv('GRPC_HOST', 'localhost') grpc_port = os.getenv('GRPC_PORT', '50051') class Game(EasyFrame): SHIPS = {'A': 5, 'B': 4, 'S': 3, 's': 3, '5': 3, 'C': 3, 'D': 2, 'd': 2, 'P': 1, 'p': 1, } SHIP_NAMES = {'A': 'Aircraft Carrier', 'B': 'Battleship', 'S': 'Submarine', 's': 'Submarine', '5': 'Submarine', 'C': 'Cruiser', 'D': 'Destroyer', 'd': 'Destroyer', 'P': 'Patrol Boat', 'p': 'Patrol Boat', } def __init__(self, timeout=1.0, mirrored=False): EasyFrame.__init__(self, 'Battleships') # Get a copy of the ships self.__ships = self.SHIPS.copy() self.__mine = Battlefield(colour=193) self.__opponent = Battlefield(colour=208) self.__mine_ui = BattlefieldUI(self, width=400, height=400, size=10) self.__opponent_ui = BattlefieldUI(self, width=400, height=400, size=10, colour='lightgreen') if not mirrored: # Top fields is opponent's self.addCanvas(self.__opponent_ui, row=0) self.addCanvas(self.__mine_ui, row=1) else: # Top field is mine self.addCanvas(self.__mine_ui, row=0) self.addCanvas(self.__opponent_ui, row=1) self.__timeout = abs(timeout) self.__attack_vector = None, None self.__client = self.__create_grpc_client() self.__client.join() def __create_grpc_client(self): """ Create BattleshipClient that communicates with Game Server. """ client = BattleshipClient(grpc_host=grpc_host, grpc_port=grpc_port) # Assign event handlers client.add_event_listener('begin', self.begin) client.add_event_listener('start_turn', self.start_turn) client.add_event_listener('end_turn', self.end_turn) client.add_event_listener('hit', self.hit) client.add_event_listener('miss', self.miss) client.add_event_listener('win', self.won) client.add_event_listener('lose', self.lost) client.add_event_listener('attack', self.attacked) return client def clear(self): """ Clear all data related to the game so we can start a new game. """ self.__mine.clear() self.__mine_ui.clear() self.__opponent.clear() self.__opponent_ui.clear() def setup(self): """ Randomly place ships on the grid. """ for ship in self.__ships: size = self.__ships[ship] while True: x = random.choice('ABCDEFGHIJ') y = random.randint(1, 10) o = random.choice([False, True]) result = self.__mine.place_ship(ship, x, y, size, horizontal=o) if result is not None: for x, y in result: self.__mine_ui.update_at(x, y, ship) break def start(self): self.mainloop() def begin(self): logger.info("The game has started!") def start_turn(self): logger.info("Okay, it's my turn now.") time.sleep(self.__timeout) while True: col = random.randint(0, 9) row = random.randint(0, 9) cell = self.__opponent.get_by_col_row(col, row) if cell is None: self.__attack_vector = col, row x, y = self.__mine.to_coords(col, row) vector = f'{x}{y}' logger.info(f'Attacking on {vector}.') self.__client.attack(vector) break def end_turn(self): logger.info("Okay, my turn has ended.") def hit(self): logger.info("Success!") self.__opponent.set_by_col_row(*self.__attack_vector, 'X') self.__opponent_ui.update_at(*self.__attack_vector, '\u2716', colour='red') def miss(self): logger.info("No luck.") dot = '\u25CB' self.__opponent.set_by_col_row(*self.__attack_vector, dot) self.__opponent_ui.update_at(*self.__attack_vector, dot, colour='grey') def won(self): logger.info("I won!!!") def lost(self): logger.info("Meh. I lost.") def attacked(self, vector): logger.info(f"Oi! Getting attacked on {vector}") x, y = vector[0], int(vector[1:]) cell = self.__mine.get(x, y) if cell is None: self.__client.miss() elif cell == '@': logger.info('THIS SHOULD NOT HAPPEN!') # Voiceover: "it happened." self.__client.miss() else: logger.info("I'm hit!") self.__mine.set(x, y, 'X') col, row = self.__mine.from_coords(x, y) self.__mine_ui.update_at(col, row, '\u2716', colour='red') self.__ships[cell] -= 1 if self.__ships[cell] == 0: if cell in self.SHIP_NAMES: sunk_ship = self.SHIP_NAMES[cell] logger.info(f'Sunk {sunk_ship}!') del self.__ships[cell] if not self.__ships: self.__client.defeat() else: self.__client.hit() def main(): mirrored = os.getenv('MIRRORED', False) game = Game(timeout=0.0, mirrored=mirrored) game.setup() game.start() if __name__ == '__main__': main()
var getVariationPathFromComponentPath = require('./getVariationPathFromComponentPath'); // Regexes var PATH_REGEX = /.+\/|.+\\/gi; /** * Gets the component name from a path * * @param {string} path The component path, e.g. /folder/components/Button.js * @return {String} Only the component name, e.g. Button */ var getComponentNameFromPath = (path) => { // Step 1: Get variation path, i.e. remove file endings and index paths var variationPath = getVariationPathFromComponentPath(path); // Step 2: Remove the prefixed path var prefixedPath = variationPath.match(PATH_REGEX); if (prefixedPath !== null) { variationPath = variationPath.replace(PATH_REGEX, ''); } return variationPath; }; module.exports = getComponentNameFromPath;
$(function(){ var order_billing_state = "ON"; // ON var order_billing_country = 'CANADA'; // CANADA USA /* $('#order_billing_name').val(order_billing_name); $('#order_email').val(order_email); $('#order_tel').val(order_tel); $('#bo').val(bo); $('#oba3').val(oba3); $('#order_billing_zip').val(order_billing_zip); $('#order_billing_city').val(order_billing_city); */ var credit_card_type = 'american_express'; // visa american_express master var card_number = '379856449971009'; var exp_mon = '08'; var exp_yr = '2021'; var cvv = '0962'; $('#credit_card_type').val(credit_card_type); $('input:eq(12)').val(card_number); $('#credit_card_month').val(exp_mon); $('#credit_card_year').val(exp_yr); $('input:eq(13)').val(cvv); $('.iCheck-helper')[1].click(); // console.log($("script[type='text/x-tmpl']")[1].innerHTML); // set state $('#order_billing_state').val(order_billing_state); /* NOTE: Ignore everything above if you used autoFill */ chrome.runtime.sendMessage({type: 'stop'}, function(res){}); })
/** * Javascript implementation of basic RSA algorithms. * * @author Dave Longley * * Copyright (c) 2010-2014 Digital Bazaar, Inc. * * The only algorithm currently supported for PKI is RSA. * * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier * and a subjectPublicKey of type bit string. * * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters * for the algorithm, if any. In the case of RSA, there aren't any. * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING * } * * AlgorithmIdentifer ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL * } * * For an RSA public key, the subjectPublicKey is: * * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER -- e * } * * PrivateKeyInfo ::= SEQUENCE { * version Version, * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, * privateKey PrivateKey, * attributes [0] IMPLICIT Attributes OPTIONAL * } * * Version ::= INTEGER * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier * PrivateKey ::= OCTET STRING * Attributes ::= SET OF Attribute * * An RSA private key as the following structure: * * RSAPrivateKey ::= SEQUENCE { * version Version, * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER -- (inverse of q) mod p * } * * Version ::= INTEGER * * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 */ var forge = require('./forge'); require('./asn1'); require('./jsbn'); require('./oids'); require('./pkcs1'); require('./prime'); require('./random'); require('./util'); if(typeof BigInteger === 'undefined') { var BigInteger = forge.jsbn.BigInteger; } var _crypto = forge.util.isNodejs ? require('crypto') : null; // shortcut for asn.1 API var asn1 = forge.asn1; // shortcut for util API var util = forge.util; /* * RSA encryption and decryption, see RFC 2313. */ forge.pki = forge.pki || {}; module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; var pki = forge.pki; // for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; // validator for a PrivateKeyInfo structure var privateKeyValidator = { // PrivateKeyInfo name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'PrivateKeyInfo.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // privateKeyAlgorithm name: 'PrivateKeyInfo.privateKeyAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'privateKeyOid' }] }, { // PrivateKey name: 'PrivateKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'privateKey' }] }; // validator for an RSA private key var rsaPrivateKeyValidator = { // RSAPrivateKey name: 'RSAPrivateKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // Version (INTEGER) name: 'RSAPrivateKey.version', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyVersion' }, { // modulus (n) name: 'RSAPrivateKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyModulus' }, { // publicExponent (e) name: 'RSAPrivateKey.publicExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPublicExponent' }, { // privateExponent (d) name: 'RSAPrivateKey.privateExponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrivateExponent' }, { // prime1 (p) name: 'RSAPrivateKey.prime1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime1' }, { // prime2 (q) name: 'RSAPrivateKey.prime2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyPrime2' }, { // exponent1 (d mod (p-1)) name: 'RSAPrivateKey.exponent1', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent1' }, { // exponent2 (d mod (q-1)) name: 'RSAPrivateKey.exponent2', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyExponent2' }, { // coefficient ((inverse of q) mod p) name: 'RSAPrivateKey.coefficient', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'privateKeyCoefficient' }] }; // validator for an RSA public key var rsaPublicKeyValidator = { // RSAPublicKey name: 'RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ // modulus (n) name: 'RSAPublicKey.modulus', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyModulus' }, { // publicExponent (e) name: 'RSAPublicKey.exponent', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.INTEGER, constructed: false, capture: 'publicKeyExponent' }] }; // validator for an SubjectPublicKeyInfo structure // Note: Currently only works with an RSA public key var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { name: 'SubjectPublicKeyInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, captureAsn1: 'subjectPublicKeyInfo', value: [{ name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'AlgorithmIdentifier.algorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'publicKeyOid' }] }, { // subjectPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.BITSTRING, constructed: false, value: [{ // RSAPublicKey name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, optional: true, captureAsn1: 'rsaPublicKey' }] }] }; // validator for a DigestInfo structure var digestInfoValidator = { name: 'DigestInfo', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'DigestInfo.DigestAlgorithm', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.SEQUENCE, constructed: true, value: [{ name: 'DigestInfo.DigestAlgorithm.algorithmIdentifier', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OID, constructed: false, capture: 'algorithmIdentifier' }, { // NULL paramters name: 'DigestInfo.DigestAlgorithm.parameters', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.NULL, // captured only to check existence for md2 and md5 capture: 'parameters', optional: true, constructed: false }] }, { // digest name: 'DigestInfo.digest', tagClass: asn1.Class.UNIVERSAL, type: asn1.Type.OCTETSTRING, constructed: false, capture: 'digest' }] }; /** * Wrap digest in DigestInfo object. * * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * @param md the message digest object with the hash to sign. * * @return the encoded message (ready for RSA encrytion) */ var emsaPkcs1v15encode = function(md) { // get the oid for the algorithm var oid; if(md.algorithm in pki.oids) { oid = pki.oids[md.algorithm]; } else { var error = new Error('Unknown message digest algorithm.'); error.algorithm = md.algorithm; throw error; } var oidBytes = asn1.oidToDer(oid).getBytes(); // create the digest info var digestInfo = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); var digestAlgorithm = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); digestAlgorithm.value.push(asn1.create( asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); var digest = asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, md.digest().getBytes()); digestInfo.value.push(digestAlgorithm); digestInfo.value.push(digest); // encode digest info return asn1.toDer(digestInfo).getBytes(); }; /** * Performs x^c mod n (RSA encryption or decryption operation). * * @param x the number to raise and mod. * @param key the key to use. * @param pub true if the key is public, false if private. * * @return the result of x^c mod n. */ var _modPow = function(x, key, pub) { if(pub) { return x.modPow(key.e, key.n); } if(!key.p || !key.q) { // allow calculation without CRT params (slow) return x.modPow(key.d, key.n); } // pre-compute dP, dQ, and qInv if necessary if(!key.dP) { key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); } if(!key.dQ) { key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); } if(!key.qInv) { key.qInv = key.q.modInverse(key.p); } /* Chinese remainder theorem (CRT) states: Suppose n1, n2, ..., nk are positive integers which are pairwise coprime (n1 and n2 have no common factors other than 1). For any integers x1, x2, ..., xk there exists an integer x solving the system of simultaneous congruences (where ~= means modularly congruent so a ~= b mod n means a mod n = b mod n): x ~= x1 mod n1 x ~= x2 mod n2 ... x ~= xk mod nk This system of congruences has a single simultaneous solution x between 0 and n - 1. Furthermore, each xk solution and x itself is congruent modulo the product n = n1*n2*...*nk. So x1 mod n = x2 mod n = xk mod n = x mod n. The single simultaneous solution x can be solved with the following equation: x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. Where x is less than n, xi = x mod ni. For RSA we are only concerned with k = 2. The modulus n = pq, where p and q are coprime. The RSA decryption algorithm is: y = x^d mod n Given the above: x1 = x^d mod p r1 = n/p = q s1 = q^-1 mod p x2 = x^d mod q r2 = n/q = p s2 = p^-1 mod q So y = (x1r1s1 + x2r2s2) mod n = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n According to Fermat's Little Theorem, if the modulus P is prime, for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. Since A is not divisible by P it follows that if: N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort to calculate). In order to calculate x^d mod p more quickly the exponent d mod (p - 1) is stored in the RSA private key (the same is done for x^d mod q). These values are referred to as dP and dQ respectively. Therefore we now have: y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n Since we'll be reducing x^dP by modulo p (same for q) we can also reduce x by p (and q respectively) before hand. Therefore, let xp = ((x mod p)^dP mod p), and xq = ((x mod q)^dQ mod q), yielding: y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n This can be further reduced to a simple algorithm that only requires 1 inverse (the q inverse is used) to be used and stored. The algorithm is called Garner's algorithm. If qInv is the inverse of q, we simply calculate: y = (qInv*(xp - xq) mod p) * q + xq However, there are two further complications. First, we need to ensure that xp > xq to prevent signed BigIntegers from being used so we add p until this is true (since we will be mod'ing with p anyway). Then, there is a known timing attack on algorithms using the CRT. To mitigate this risk, "cryptographic blinding" should be used. This requires simply generating a random number r between 0 and n-1 and its inverse and multiplying x by r^e before calculating y and then multiplying y by r^-1 afterwards. Note that r must be coprime with n (gcd(r, n) === 1) in order to have an inverse. */ // cryptographic blinding var r; do { r = new BigInteger( forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), 16); } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); // calculate xp and xq var xp = x.mod(key.p).modPow(key.dP, key.p); var xq = x.mod(key.q).modPow(key.dQ, key.q); // xp must be larger than xq to avoid signed bit usage while(xp.compareTo(xq) < 0) { xp = xp.add(key.p); } // do last step var y = xp.subtract(xq) .multiply(key.qInv).mod(key.p) .multiply(key.q).add(xq); // remove effect of random for cryptographic blinding y = y.multiply(r.modInverse(key.n)).mod(key.n); return y; }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or * 'encrypt' on a public key object instead. * * Performs RSA encryption. * * The parameter bt controls whether to put padding bytes before the * message passed in. Set bt to either true or false to disable padding * completely (in order to handle e.g. EMSA-PSS encoding seperately before), * signaling whether the encryption operation is a public key operation * (i.e. encrypting data) or not, i.e. private key operation (data signing). * * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 * (for signing) or 0x02 (for encryption). The key operation mode (private * or public) is derived from this flag in that case). * * @param m the message to encrypt as a byte string. * @param key the RSA key to use. * @param bt for PKCS#1 v1.5 padding, the block type to use * (0x01 for private key, 0x02 for public), * to disable padding: true = public key, false = private key. * * @return the encrypted bytes as a string. */ pki.rsa.encrypt = function(m, key, bt) { var pub = bt; var eb; // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); if(bt !== false && bt !== true) { // legacy, default to PKCS#1 v1.5 padding pub = (bt === 0x02); eb = _encodePkcs1_v1_5(m, key, bt); } else { eb = forge.util.createBuffer(); eb.putBytes(m); } // load encryption block as big integer 'x' // FIXME: hex conversion inefficient, get BigInteger w/byte strings var x = new BigInteger(eb.toHex(), 16); // do RSA encryption var y = _modPow(x, key, pub); // convert y into the encrypted data byte string, if y is shorter in // bytes than k, then prepend zero bytes to fill up ed // FIXME: hex conversion inefficient, get BigInteger w/byte strings var yhex = y.toString(16); var ed = forge.util.createBuffer(); var zeros = k - Math.ceil(yhex.length / 2); while(zeros > 0) { ed.putByte(0x00); --zeros; } ed.putBytes(forge.util.hexToBytes(yhex)); return ed.getBytes(); }; /** * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or * 'verify' on a public key object instead. * * Performs RSA decryption. * * The parameter ml controls whether to apply PKCS#1 v1.5 padding * or not. Set ml = false to disable padding removal completely * (in order to handle e.g. EMSA-PSS later on) and simply pass back * the RSA encryption block. * * @param ed the encrypted data to decrypt in as a byte string. * @param key the RSA key to use. * @param pub true for a public key operation, false for private. * @param ml the message length, if known, false to disable padding. * * @return the decrypted message as a byte string. */ pki.rsa.decrypt = function(ed, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); // error if the length of the encrypted data ED is not k if(ed.length !== k) { var error = new Error('Encrypted message length is invalid.'); error.length = ed.length; error.expected = k; throw error; } // convert encrypted data into a big integer // FIXME: hex conversion inefficient, get BigInteger w/byte strings var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); // y must be less than the modulus or it wasn't the result of // a previous mod operation (encryption) using that modulus if(y.compareTo(key.n) >= 0) { throw new Error('Encrypted message is invalid.'); } // do RSA decryption var x = _modPow(y, key, pub); // create the encryption block, if x is shorter in bytes than k, then // prepend zero bytes to fill up eb // FIXME: hex conversion inefficient, get BigInteger w/byte strings var xhex = x.toString(16); var eb = forge.util.createBuffer(); var zeros = k - Math.ceil(xhex.length / 2); while(zeros > 0) { eb.putByte(0x00); --zeros; } eb.putBytes(forge.util.hexToBytes(xhex)); if(ml !== false) { // legacy, default to PKCS#1 v1.5 padding return _decodePkcs1_v1_5(eb.getBytes(), key, pub); } // return message return eb.getBytes(); }; /** * Creates an RSA key-pair generation state object. It is used to allow * key-generation to be performed in steps. It also allows for a UI to * display progress updates. * * @param bits the size for the private key in bits, defaults to 2048. * @param e the public exponent to use, defaults to 65537 (0x10001). * @param [options] the options to use. * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". * algorithm the algorithm to use (default: 'PRIMEINC'). * * @return the state object to use to generate the key-pair. */ pki.rsa.createKeyPairGenerationState = function(bits, e, options) { // TODO: migrate step-based prime generation code to forge.prime // set default bits if(typeof(bits) === 'string') { bits = parseInt(bits, 10); } bits = bits || 2048; // create prng with api that matches BigInteger secure random options = options || {}; var prng = options.prng || forge.random; var rng = { // x is an array to fill with bytes nextBytes: function(x) { var b = prng.getBytesSync(x.length); for(var i = 0; i < x.length; ++i) { x[i] = b.charCodeAt(i); } } }; var algorithm = options.algorithm || 'PRIMEINC'; // create PRIMEINC algorithm state var rval; if(algorithm === 'PRIMEINC') { rval = { algorithm: algorithm, state: 0, bits: bits, rng: rng, eInt: e || 65537, e: new BigInteger(null), p: null, q: null, qBits: bits >> 1, pBits: bits - (bits >> 1), pqState: 0, num: null, keys: null }; rval.e.fromInt(rval.eInt); } else { throw new Error('Invalid key generation algorithm: ' + algorithm); } return rval; }; /** * Attempts to runs the key-generation algorithm for at most n seconds * (approximately) using the given state. When key-generation has completed, * the keys will be stored in state.keys. * * To use this function to update a UI while generating a key or to prevent * causing browser lockups/warnings, set "n" to a value other than 0. A * simple pattern for generating a key and showing a progress indicator is: * * var state = pki.rsa.createKeyPairGenerationState(2048); * var step = function() { * // step key-generation, run algorithm for 100 ms, repeat * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { * setTimeout(step, 1); * } else { * // key-generation complete * // TODO: turn off progress indicator here * // TODO: use the generated key-pair in "state.keys" * } * }; * // TODO: turn on progress indicator here * setTimeout(step, 0); * * @param state the state to use. * @param n the maximum number of milliseconds to run the algorithm for, 0 * to run the algorithm to completion. * * @return true if the key-generation completed, false if not. */ pki.rsa.stepKeyPairGenerationState = function(state, n) { // set default algorithm if not set if(!('algorithm' in state)) { state.algorithm = 'PRIMEINC'; } // TODO: migrate step-based prime generation code to forge.prime // TODO: abstract as PRIMEINC algorithm // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) // with some minor optimizations and designed to run in steps // local state vars var THIRTY = new BigInteger(null); THIRTY.fromInt(30); var deltaIdx = 0; var op_or = function(x, y) {return x | y;}; // keep stepping until time limit is reached or done var t1 = +new Date(); var t2; var total = 0; while(state.keys === null && (n <= 0 || total < n)) { // generate p or q if(state.state === 0) { /* Note: All primes are of the form: 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i When we generate a random number, we always align it at 30k + 1. Each time the number is determined not to be prime we add to get to the next 'i', eg: if the number was at 30k + 1 we add 6. */ var bits = (state.p === null) ? state.pBits : state.qBits; var bits1 = bits - 1; // get a random number if(state.pqState === 0) { state.num = new BigInteger(bits, state.rng); // force MSB set if(!state.num.testBit(bits1)) { state.num.bitwiseTo( BigInteger.ONE.shiftLeft(bits1), op_or, state.num); } // align number on 30k+1 boundary state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); deltaIdx = 0; ++state.pqState; } else if(state.pqState === 1) { // try to make the number a prime if(state.num.bitLength() > bits) { // overflow, try again state.pqState = 0; // do primality test } else if(state.num.isProbablePrime( _getMillerRabinTests(state.num.bitLength()))) { ++state.pqState; } else { // get next potential prime state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); } } else if(state.pqState === 2) { // ensure number is coprime with e state.pqState = (state.num.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) === 0) ? 3 : 0; } else if(state.pqState === 3) { // store p or q state.pqState = 0; if(state.p === null) { state.p = state.num; } else { state.q = state.num; } // advance state if both p and q are ready if(state.p !== null && state.q !== null) { ++state.state; } state.num = null; } } else if(state.state === 1) { // ensure p is larger than q (swap them if not) if(state.p.compareTo(state.q) < 0) { state.num = state.p; state.p = state.q; state.q = state.num; } ++state.state; } else if(state.state === 2) { // compute phi: (p - 1)(q - 1) (Euler's totient function) state.p1 = state.p.subtract(BigInteger.ONE); state.q1 = state.q.subtract(BigInteger.ONE); state.phi = state.p1.multiply(state.q1); ++state.state; } else if(state.state === 3) { // ensure e and phi are coprime if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { // phi and e are coprime, advance ++state.state; } else { // phi and e aren't coprime, so generate a new p and q state.p = null; state.q = null; state.state = 0; } } else if(state.state === 4) { // create n, ensure n is has the right number of bits state.n = state.p.multiply(state.q); // ensure n is right number of bits if(state.n.bitLength() === state.bits) { // success, advance ++state.state; } else { // failed, get new q state.q = null; state.state = 0; } } else if(state.state === 5) { // set keys var d = state.e.modInverse(state.phi); state.keys = { privateKey: pki.rsa.setPrivateKey( state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), publicKey: pki.rsa.setPublicKey(state.n, state.e) }; } // update timing t2 = +new Date(); total += t2 - t1; t1 = t2; } return state.keys !== null; }; /** * Generates an RSA public-private key pair in a single call. * * To generate a key-pair in steps (to allow for progress updates and to * prevent blocking or warnings in slow browsers) then use the key-pair * generation state functions. * * To generate a key-pair asynchronously (either through web-workers, if * available, or by breaking up the work on the main thread), pass a * callback function. * * @param [bits] the size for the private key in bits, defaults to 2048. * @param [e] the public exponent to use, defaults to 65537. * @param [options] options for key-pair generation, if given then 'bits' * and 'e' must *not* be given: * bits the size for the private key in bits, (default: 2048). * e the public exponent to use, (default: 65537 (0x10001)). * workerScript the worker script URL. * workers the number of web workers (if supported) to use, * (default: 2). * workLoad the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * prng a custom crypto-secure pseudo-random number generator to use, * that must define "getBytesSync". Disables use of native APIs. * algorithm the algorithm to use (default: 'PRIMEINC'). * @param [callback(err, keypair)] called once the operation completes. * * @return an object with privateKey and publicKey properties. */ pki.rsa.generateKeyPair = function(bits, e, options, callback) { // (bits), (options), (callback) if(arguments.length === 1) { if(typeof bits === 'object') { options = bits; bits = undefined; } else if(typeof bits === 'function') { callback = bits; bits = undefined; } } else if(arguments.length === 2) { // (bits, e), (bits, options), (bits, callback), (options, callback) if(typeof bits === 'number') { if(typeof e === 'function') { callback = e; e = undefined; } else if(typeof e !== 'number') { options = e; e = undefined; } } else { options = bits; callback = e; bits = undefined; e = undefined; } } else if(arguments.length === 3) { // (bits, e, options), (bits, e, callback), (bits, options, callback) if(typeof e === 'number') { if(typeof options === 'function') { callback = options; options = undefined; } } else { callback = options; options = e; e = undefined; } } options = options || {}; if(bits === undefined) { bits = options.bits || 2048; } if(e === undefined) { e = options.e || 0x10001; } // use native code if permitted, available, and parameters are acceptable if(!forge.options.usePureJavaScript && !options.prng && bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { if(callback) { // try native async if(_detectNodeCrypto('generateKeyPair')) { return _crypto.generateKeyPair('rsa', { modulusLength: bits, publicExponent: e, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }, function(err, pub, priv) { if(err) { return callback(err); } callback(null, { privateKey: pki.privateKeyFromPem(priv), publicKey: pki.publicKeyFromPem(pub) }); }); } if(_detectSubtleCrypto('generateKey') && _detectSubtleCrypto('exportKey')) { // use standard native generateKey return util.globalScope.crypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']) .then(function(pair) { return util.globalScope.crypto.subtle.exportKey( 'pkcs8', pair.privateKey); // avoiding catch(function(err) {...}) to support IE <= 8 }).then(undefined, function(err) { callback(err); }).then(function(pkcs8) { if(pkcs8) { var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); } }); } if(_detectSubtleMsCrypto('generateKey') && _detectSubtleMsCrypto('exportKey')) { var genOp = util.globalScope.msCrypto.subtle.generateKey({ name: 'RSASSA-PKCS1-v1_5', modulusLength: bits, publicExponent: _intToUint8Array(e), hash: {name: 'SHA-256'} }, true /* key can be exported*/, ['sign', 'verify']); genOp.oncomplete = function(e) { var pair = e.target.result; var exportOp = util.globalScope.msCrypto.subtle.exportKey( 'pkcs8', pair.privateKey); exportOp.oncomplete = function(e) { var pkcs8 = e.target.result; var privateKey = pki.privateKeyFromAsn1( asn1.fromDer(forge.util.createBuffer(pkcs8))); callback(null, { privateKey: privateKey, publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) }); }; exportOp.onerror = function(err) { callback(err); }; }; genOp.onerror = function(err) { callback(err); }; return; } } else { // try native sync if(_detectNodeCrypto('generateKeyPairSync')) { var keypair = _crypto.generateKeyPairSync('rsa', { modulusLength: bits, publicExponent: e, publicKeyEncoding: { type: 'spki', format: 'pem' }, privateKeyEncoding: { type: 'pkcs8', format: 'pem' } }); return { privateKey: pki.privateKeyFromPem(keypair.privateKey), publicKey: pki.publicKeyFromPem(keypair.publicKey) }; } } } // use JavaScript implementation var state = pki.rsa.createKeyPairGenerationState(bits, e, options); if(!callback) { pki.rsa.stepKeyPairGenerationState(state, 0); return state.keys; } _generateKeyPair(state, options, callback); }; /** * Sets an RSA public key from BigIntegers modulus and exponent. * * @param n the modulus. * @param e the exponent. * * @return the public key. */ pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { var key = { n: n, e: e }; /** * Encrypts the given data with this public key. Newer applications * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for * legacy applications. * * @param data the byte string to encrypt. * @param scheme the encryption scheme to use: * 'RSAES-PKCS1-V1_5' (default), * 'RSA-OAEP', * 'RAW', 'NONE', or null to perform raw RSA encryption, * an object with an 'encode' property set to a function * with the signature 'function(data, key)' that returns * a binary-encoded string representing the encoded data. * @param schemeOptions any scheme-specific options. * * @return the encrypted byte string. */ key.encrypt = function(data, scheme, schemeOptions) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSAES-PKCS1-V1_5'; } if(scheme === 'RSAES-PKCS1-V1_5') { scheme = { encode: function(m, key, pub) { return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); } }; } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { scheme = { encode: function(m, key) { return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); } }; } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { scheme = {encode: function(e) {return e;}}; } else if(typeof scheme === 'string') { throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } // do scheme-based encoding then rsa encryption var e = scheme.encode(data, key, true); return pki.rsa.encrypt(e, key, true); }; /** * Verifies the given signature against the given digest. * * PKCS#1 supports multiple (currently two) signature schemes: * RSASSA-PKCS1-V1_5 and RSASSA-PSS. * * By default this implementation uses the "old scheme", i.e. * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the * signature is an OCTET STRING that holds a DigestInfo. * * DigestInfo ::= SEQUENCE { * digestAlgorithm DigestAlgorithmIdentifier, * digest Digest * } * DigestAlgorithmIdentifier ::= AlgorithmIdentifier * Digest ::= OCTET STRING * * To perform PSS signature verification, provide an instance * of Forge PSS object as the scheme parameter. * * @param digest the message digest hash to compare against the signature, * as a binary-encoded string. * @param signature the signature to verify, as a binary-encoded string. * @param scheme signature verification scheme to use: * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, * a Forge PSS object for RSASSA-PSS, * 'NONE' or null for none, DigestInfo will not be expected, but * PKCS#1 v1.5 padding will still be used. * @param options optional verify options * _parseAllDigestBytes testing flag to control parsing of all * digest bytes. Unsupported and not for general usage. * (default: true) * * @return true if the signature was verified, false if not. */ key.verify = function(digest, signature, scheme, options) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSASSA-PKCS1-V1_5'; } if(options === undefined) { options = { _parseAllDigestBytes: true }; } if(!('_parseAllDigestBytes' in options)) { options._parseAllDigestBytes = true; } if(scheme === 'RSASSA-PKCS1-V1_5') { scheme = { verify: function(digest, d) { // remove padding d = _decodePkcs1_v1_5(d, key, true); // d is ASN.1 BER-encoded DigestInfo var obj = asn1.fromDer(d, { parseAllBytes: options._parseAllDigestBytes }); // validate DigestInfo var capture = {}; var errors = []; if(!asn1.validate(obj, digestInfoValidator, capture, errors)) { var error = new Error( 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + 'DigestInfo value.'); error.errors = errors; throw error; } // check hash algorithm identifier // see PKCS1-v1-5DigestAlgorithms in RFC 8017 // FIXME: add support to vaidator for strict value choices var oid = asn1.derToOid(capture.algorithmIdentifier); if(!(oid === forge.oids.md2 || oid === forge.oids.md5 || oid === forge.oids.sha1 || oid === forge.oids.sha224 || oid === forge.oids.sha256 || oid === forge.oids.sha384 || oid === forge.oids.sha512 || oid === forge.oids['sha512-224'] || oid === forge.oids['sha512-256'])) { var error = new Error( 'Unknown RSASSA-PKCS1-v1_5 DigestAlgorithm identifier.'); error.oid = oid; throw error; } // special check for md2 and md5 that NULL parameters exist if(oid === forge.oids.md2 || oid === forge.oids.md5) { if(!('parameters' in capture)) { throw new Error( 'ASN.1 object does not contain a valid RSASSA-PKCS1-v1_5 ' + 'DigestInfo value. ' + 'Missing algorithm identifer NULL parameters.'); } } // compare the given digest to the decrypted one return digest === capture.digest; } }; } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { scheme = { verify: function(digest, d) { // remove padding d = _decodePkcs1_v1_5(d, key, true); return digest === d; } }; } // do rsa decryption w/o any decoding, then verify -- which does decoding var d = pki.rsa.decrypt(signature, key, true, false); return scheme.verify(digest, d, key.n.bitLength()); }; return key; }; /** * Sets an RSA private key from BigIntegers modulus, exponent, primes, * prime exponents, and modular multiplicative inverse. * * @param n the modulus. * @param e the public exponent. * @param d the private exponent ((inverse of e) mod n). * @param p the first prime. * @param q the second prime. * @param dP exponent1 (d mod (p-1)). * @param dQ exponent2 (d mod (q-1)). * @param qInv ((inverse of q) mod p) * * @return the private key. */ pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( n, e, d, p, q, dP, dQ, qInv) { var key = { n: n, e: e, d: d, p: p, q: q, dP: dP, dQ: dQ, qInv: qInv }; /** * Decrypts the given data with this private key. The decryption scheme * must match the one used to encrypt the data. * * @param data the byte string to decrypt. * @param scheme the decryption scheme to use: * 'RSAES-PKCS1-V1_5' (default), * 'RSA-OAEP', * 'RAW', 'NONE', or null to perform raw RSA decryption. * @param schemeOptions any scheme-specific options. * * @return the decrypted byte string. */ key.decrypt = function(data, scheme, schemeOptions) { if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } else if(scheme === undefined) { scheme = 'RSAES-PKCS1-V1_5'; } // do rsa decryption w/o any decoding var d = pki.rsa.decrypt(data, key, false, false); if(scheme === 'RSAES-PKCS1-V1_5') { scheme = {decode: _decodePkcs1_v1_5}; } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { scheme = { decode: function(d, key) { return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); } }; } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { scheme = {decode: function(d) {return d;}}; } else { throw new Error('Unsupported encryption scheme: "' + scheme + '".'); } // decode according to scheme return scheme.decode(d, key, false); }; /** * Signs the given digest, producing a signature. * * PKCS#1 supports multiple (currently two) signature schemes: * RSASSA-PKCS1-V1_5 and RSASSA-PSS. * * By default this implementation uses the "old scheme", i.e. * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide * an instance of Forge PSS object as the scheme parameter. * * @param md the message digest object with the hash to sign. * @param scheme the signature scheme to use: * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, * a Forge PSS object for RSASSA-PSS, * 'NONE' or null for none, DigestInfo will not be used but * PKCS#1 v1.5 padding will still be used. * * @return the signature as a byte string. */ key.sign = function(md, scheme) { /* Note: The internal implementation of RSA operations is being transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy code like the use of an encoding block identifier 'bt' will eventually be removed. */ // private key operation var bt = false; if(typeof scheme === 'string') { scheme = scheme.toUpperCase(); } if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { scheme = {encode: emsaPkcs1v15encode}; bt = 0x01; } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { scheme = {encode: function() {return md;}}; bt = 0x01; } // encode and then encrypt var d = scheme.encode(md, key.n.bitLength()); return pki.rsa.encrypt(d, key, bt); }; return key; }; /** * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. * * @param rsaKey the ASN.1 RSAPrivateKey. * * @return the ASN.1 PrivateKeyInfo. */ pki.wrapRsaPrivateKey = function(rsaKey) { // PrivateKeyInfo return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version (0) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), // privateKeyAlgorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ asn1.create( asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // PrivateKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, asn1.toDer(rsaKey).getBytes()) ]); }; /** * Converts a private key from an ASN.1 object. * * @param obj the ASN.1 representation of a PrivateKeyInfo containing an * RSAPrivateKey or an RSAPrivateKey. * * @return the private key. */ pki.privateKeyFromAsn1 = function(obj) { // get PrivateKeyInfo var capture = {}; var errors = []; if(asn1.validate(obj, privateKeyValidator, capture, errors)) { obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); } // get RSAPrivateKey capture = {}; errors = []; if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { var error = new Error('Cannot read private key. ' + 'ASN.1 object does not contain an RSAPrivateKey.'); error.errors = errors; throw error; } // Note: Version is currently ignored. // capture.privateKeyVersion // FIXME: inefficient, get a BigInteger that uses byte strings var n, e, d, p, q, dP, dQ, qInv; n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); // set private key return pki.setRsaPrivateKey( new BigInteger(n, 16), new BigInteger(e, 16), new BigInteger(d, 16), new BigInteger(p, 16), new BigInteger(q, 16), new BigInteger(dP, 16), new BigInteger(dQ, 16), new BigInteger(qInv, 16)); }; /** * Converts a private key to an ASN.1 RSAPrivateKey. * * @param key the private key. * * @return the ASN.1 representation of an RSAPrivateKey. */ pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { // RSAPrivateKey return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // version (0 = only 2 primes, 1 multiple primes) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, asn1.integerToDer(0).getBytes()), // modulus (n) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), // publicExponent (e) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)), // privateExponent (d) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.d)), // privateKeyPrime1 (p) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.p)), // privateKeyPrime2 (q) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.q)), // privateKeyExponent1 (dP) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dP)), // privateKeyExponent2 (dQ) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.dQ)), // coefficient (qInv) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.qInv)) ]); }; /** * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. * * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. * * @return the public key. */ pki.publicKeyFromAsn1 = function(obj) { // get SubjectPublicKeyInfo var capture = {}; var errors = []; if(asn1.validate(obj, publicKeyValidator, capture, errors)) { // get oid var oid = asn1.derToOid(capture.publicKeyOid); if(oid !== pki.oids.rsaEncryption) { var error = new Error('Cannot read public key. Unknown OID.'); error.oid = oid; throw error; } obj = capture.rsaPublicKey; } // get RSA params errors = []; if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { var error = new Error('Cannot read public key. ' + 'ASN.1 object does not contain an RSAPublicKey.'); error.errors = errors; throw error; } // FIXME: inefficient, get a BigInteger that uses byte strings var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); // set public key return pki.setRsaPublicKey( new BigInteger(n, 16), new BigInteger(e, 16)); }; /** * Converts a public key to an ASN.1 SubjectPublicKeyInfo. * * @param key the public key. * * @return the asn1 representation of a SubjectPublicKeyInfo. */ pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { // SubjectPublicKeyInfo return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // AlgorithmIdentifier asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // algorithm asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), // parameters (null) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') ]), // subjectPublicKey asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ pki.publicKeyToRSAPublicKey(key) ]) ]); }; /** * Converts a public key to an ASN.1 RSAPublicKey. * * @param key the public key. * * @return the asn1 representation of a RSAPublicKey. */ pki.publicKeyToRSAPublicKey = function(key) { // RSAPublicKey return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ // modulus (n) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.n)), // publicExponent (e) asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, _bnToBytes(key.e)) ]); }; /** * Encodes a message using PKCS#1 v1.5 padding. * * @param m the message to encode. * @param key the RSA key to use. * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 * (for encryption). * * @return the padded byte buffer. */ function _encodePkcs1_v1_5(m, key, bt) { var eb = forge.util.createBuffer(); // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); /* use PKCS#1 v1.5 padding */ if(m.length > (k - 11)) { var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); error.length = m.length; error.max = k - 11; throw error; } /* A block type BT, a padding string PS, and the data D shall be formatted into an octet string EB, the encryption block: EB = 00 || BT || PS || 00 || D The block type BT shall be a single octet indicating the structure of the encryption block. For this version of the document it shall have value 00, 01, or 02. For a private-key operation, the block type shall be 00 or 01. For a public-key operation, it shall be 02. The padding string PS shall consist of k-3-||D|| octets. For block type 00, the octets shall have value 00; for block type 01, they shall have value FF; and for block type 02, they shall be pseudorandomly generated and nonzero. This makes the length of the encryption block EB equal to k. */ // build the encryption block eb.putByte(0x00); eb.putByte(bt); // create the padding var padNum = k - 3 - m.length; var padByte; // private key op if(bt === 0x00 || bt === 0x01) { padByte = (bt === 0x00) ? 0x00 : 0xFF; for(var i = 0; i < padNum; ++i) { eb.putByte(padByte); } } else { // public key op // pad with random non-zero values while(padNum > 0) { var numZeros = 0; var padBytes = forge.random.getBytes(padNum); for(var i = 0; i < padNum; ++i) { padByte = padBytes.charCodeAt(i); if(padByte === 0) { ++numZeros; } else { eb.putByte(padByte); } } padNum = numZeros; } } // zero followed by message eb.putByte(0x00); eb.putBytes(m); return eb; } /** * Decodes a message using PKCS#1 v1.5 padding. * * @param em the message to decode. * @param key the RSA key to use. * @param pub true if the key is a public key, false if it is private. * @param ml the message length, if specified. * * @return the decoded bytes. */ function _decodePkcs1_v1_5(em, key, pub, ml) { // get the length of the modulus in bytes var k = Math.ceil(key.n.bitLength() / 8); /* It is an error if any of the following conditions occurs: 1. The encryption block EB cannot be parsed unambiguously. 2. The padding string PS consists of fewer than eight octets or is inconsisent with the block type BT. 3. The decryption process is a public-key operation and the block type BT is not 00 or 01, or the decryption process is a private-key operation and the block type is not 02. */ // parse the encryption block var eb = forge.util.createBuffer(em); var first = eb.getByte(); var bt = eb.getByte(); if(first !== 0x00 || (pub && bt !== 0x00 && bt !== 0x01) || (!pub && bt != 0x02) || (pub && bt === 0x00 && typeof(ml) === 'undefined')) { throw new Error('Encryption block is invalid.'); } var padNum = 0; if(bt === 0x00) { // check all padding bytes for 0x00 padNum = k - 3 - ml; for(var i = 0; i < padNum; ++i) { if(eb.getByte() !== 0x00) { throw new Error('Encryption block is invalid.'); } } } else if(bt === 0x01) { // find the first byte that isn't 0xFF, should be after all padding padNum = 0; while(eb.length() > 1) { if(eb.getByte() !== 0xFF) { --eb.read; break; } ++padNum; } } else if(bt === 0x02) { // look for 0x00 byte padNum = 0; while(eb.length() > 1) { if(eb.getByte() === 0x00) { --eb.read; break; } ++padNum; } } // zero must be 0x00 and padNum must be (k - 3 - message length) var zero = eb.getByte(); if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { throw new Error('Encryption block is invalid.'); } return eb.getBytes(); } /** * Runs the key-generation algorithm asynchronously, either in the background * via Web Workers, or using the main thread and setImmediate. * * @param state the key-pair generation state. * @param [options] options for key-pair generation: * workerScript the worker script URL. * workers the number of web workers (if supported) to use, * (default: 2, -1 to use estimated cores minus one). * workLoad the size of the work load, ie: number of possible prime * numbers for each web worker to check per work assignment, * (default: 100). * @param callback(err, keypair) called once the operation completes. */ function _generateKeyPair(state, options, callback) { if(typeof options === 'function') { callback = options; options = {}; } options = options || {}; var opts = { algorithm: { name: options.algorithm || 'PRIMEINC', options: { workers: options.workers || 2, workLoad: options.workLoad || 100, workerScript: options.workerScript } } }; if('prng' in options) { opts.prng = options.prng; } generate(); function generate() { // find p and then q (done in series to simplify) getPrime(state.pBits, function(err, num) { if(err) { return callback(err); } state.p = num; if(state.q !== null) { return finish(err, state.q); } getPrime(state.qBits, finish); }); } function getPrime(bits, callback) { forge.prime.generateProbablePrime(bits, opts, callback); } function finish(err, num) { if(err) { return callback(err); } // set q state.q = num; // ensure p is larger than q (swap them if not) if(state.p.compareTo(state.q) < 0) { var tmp = state.p; state.p = state.q; state.q = tmp; } // ensure p is coprime with e if(state.p.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) !== 0) { state.p = null; generate(); return; } // ensure q is coprime with e if(state.q.subtract(BigInteger.ONE).gcd(state.e) .compareTo(BigInteger.ONE) !== 0) { state.q = null; getPrime(state.qBits, finish); return; } // compute phi: (p - 1)(q - 1) (Euler's totient function) state.p1 = state.p.subtract(BigInteger.ONE); state.q1 = state.q.subtract(BigInteger.ONE); state.phi = state.p1.multiply(state.q1); // ensure e and phi are coprime if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { // phi and e aren't coprime, so generate a new p and q state.p = state.q = null; generate(); return; } // create n, ensure n is has the right number of bits state.n = state.p.multiply(state.q); if(state.n.bitLength() !== state.bits) { // failed, get new q state.q = null; getPrime(state.qBits, finish); return; } // set keys var d = state.e.modInverse(state.phi); state.keys = { privateKey: pki.rsa.setPrivateKey( state.n, state.e, d, state.p, state.q, d.mod(state.p1), d.mod(state.q1), state.q.modInverse(state.p)), publicKey: pki.rsa.setPublicKey(state.n, state.e) }; callback(null, state.keys); } } /** * Converts a positive BigInteger into 2's-complement big-endian bytes. * * @param b the big integer to convert. * * @return the bytes. */ function _bnToBytes(b) { // prepend 0x00 if first byte >= 0x80 var hex = b.toString(16); if(hex[0] >= '8') { hex = '00' + hex; } var bytes = forge.util.hexToBytes(hex); // ensure integer is minimally-encoded if(bytes.length > 1 && // leading 0x00 for positive integer ((bytes.charCodeAt(0) === 0 && (bytes.charCodeAt(1) & 0x80) === 0) || // leading 0xFF for negative integer (bytes.charCodeAt(0) === 0xFF && (bytes.charCodeAt(1) & 0x80) === 0x80))) { return bytes.substr(1); } return bytes; } /** * Returns the required number of Miller-Rabin tests to generate a * prime with an error probability of (1/2)^80. * * See Handbook of Applied Cryptography Chapter 4, Table 4.4. * * @param bits the bit size. * * @return the required number of iterations. */ function _getMillerRabinTests(bits) { if(bits <= 100) return 27; if(bits <= 150) return 18; if(bits <= 200) return 15; if(bits <= 250) return 12; if(bits <= 300) return 9; if(bits <= 350) return 8; if(bits <= 400) return 7; if(bits <= 500) return 6; if(bits <= 600) return 5; if(bits <= 800) return 4; if(bits <= 1250) return 3; return 2; } /** * Performs feature detection on the Node crypto interface. * * @param fn the feature (function) to detect. * * @return true if detected, false if not. */ function _detectNodeCrypto(fn) { return forge.util.isNodejs && typeof _crypto[fn] === 'function'; } /** * Performs feature detection on the SubtleCrypto interface. * * @param fn the feature (function) to detect. * * @return true if detected, false if not. */ function _detectSubtleCrypto(fn) { return (typeof util.globalScope !== 'undefined' && typeof util.globalScope.crypto === 'object' && typeof util.globalScope.crypto.subtle === 'object' && typeof util.globalScope.crypto.subtle[fn] === 'function'); } /** * Performs feature detection on the deprecated Microsoft Internet Explorer * outdated SubtleCrypto interface. This function should only be used after * checking for the modern, standard SubtleCrypto interface. * * @param fn the feature (function) to detect. * * @return true if detected, false if not. */ function _detectSubtleMsCrypto(fn) { return (typeof util.globalScope !== 'undefined' && typeof util.globalScope.msCrypto === 'object' && typeof util.globalScope.msCrypto.subtle === 'object' && typeof util.globalScope.msCrypto.subtle[fn] === 'function'); } function _intToUint8Array(x) { var bytes = forge.util.hexToBytes(x.toString(16)); var buffer = new Uint8Array(bytes.length); for(var i = 0; i < bytes.length; ++i) { buffer[i] = bytes.charCodeAt(i); } return buffer; } function _privateKeyFromJwk(jwk) { if(jwk.kty !== 'RSA') { throw new Error( 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); } return pki.setRsaPrivateKey( _base64ToBigInt(jwk.n), _base64ToBigInt(jwk.e), _base64ToBigInt(jwk.d), _base64ToBigInt(jwk.p), _base64ToBigInt(jwk.q), _base64ToBigInt(jwk.dp), _base64ToBigInt(jwk.dq), _base64ToBigInt(jwk.qi)); } function _publicKeyFromJwk(jwk) { if(jwk.kty !== 'RSA') { throw new Error('Key algorithm must be "RSA".'); } return pki.setRsaPublicKey( _base64ToBigInt(jwk.n), _base64ToBigInt(jwk.e)); } function _base64ToBigInt(b64) { return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); }
//>>built define("dojox/lang/oo/aop",["dijit","dojo","dojox","dojo/require!dojox/lang/oo/Decorator,dojox/lang/oo/general"],function(k,b,h){b.provide("dojox.lang.oo.aop");b.require("dojox.lang.oo.Decorator");b.require("dojox.lang.oo.general");(function(){var a=h.lang.oo,e=a.makeDecorator,g=a.general,a=a.aop,f=b.isFunction;a.before=g.before;a.around=g.wrap;a.afterReturning=e(function(a,d,c){return f(c)?function(){var a=c.apply(this,arguments);d.call(this,a);return a}:function(){d.call(this)}});a.afterThrowing= e(function(a,d,c){return f(c)?function(){var a;try{a=c.apply(this,arguments)}catch(b){throw d.call(this,b),b;}return a}:c});a.after=e(function(a,b,c){return f(c)?function(){var a;try{a=c.apply(this,arguments)}finally{b.call(this)}return a}:function(){b.call(this)}})})()});
""" LoPy LoRaWAN Nano Gateway configuration options """ import machine import ubinascii WIFI_MAC = ubinascii.hexlify(machine.unique_id()).upper() # Set the Gateway ID to be the first 3 bytes of MAC address + 'FFFE' + last 3 bytes of MAC address GATEWAY_ID = WIFI_MAC[:6] + "FFFE" + WIFI_MAC[6:12] SERVER = 'router.eu.thethings.network' PORT = 1700 NTP = "pool.ntp.org" NTP_PERIOD_S = 3600 WIFI_SSID = 'my-wifi' WIFI_PASS = 'my-wifi-password' # for EU868 LORA_FREQUENCY = 868100000 LORA_GW_DR = "SF7BW125" # DR_5 LORA_NODE_DR = 5 # for US915 # LORA_FREQUENCY = 903900000 # LORA_GW_DR = "SF7BW125" # DR_3 # LORA_NODE_DR = 3
from typing import Optional import mpmath as mp import numpy as np from numpy.core._multiarray_umath import tanh, sinh from scipy.constants import codata F = codata.physical_constants['Faraday constant'][0] Rg = codata.physical_constants['molar gas constant'][0] def sinh(x): """ As numpy gives errors when sinh becomes very large, above 10^250, this functions is used instead of np/mp.sinh() """ return (1 - np.exp(-2*x))/(2*np.exp(-x)) def coth(x): """ As numpy gives errors when coth becomes very large, above 10^250, this functions is used instead of np/mp.coth() """ return (1 + np.exp(-2*x))/(1 - np.exp(-2*x)) def elem_L(w, L): """ Simulation Function: -L- Returns the impedance of an inductor Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] L = Inductance [ohm * s] """ return 1j*w*L def elem_C(w,C): """ Simulation Function: -C- Inputs ---------- w = Angular frequency [1/s] C = Capacitance [F] """ return 1/(C*(w*1j)) def elem_Q(w,Q,n): """ Simulation Function: -Q- Inputs ---------- w = Angular frequency [1/s] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return 1/(Q*(w*1j)**n) def cir_RsC(w, Rs, C): """ Simulation Function: -Rs-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] C = Capacitance [F] """ return Rs + 1/(C*(w*1j)) def cir_RsQ(w, Rs, Q, n): """ Simulation Function: -Rs-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] """ return Rs + 1/(Q*(w*1j)**n) def cir_RQ(w, R: Optional[float] = None, Q: Optional[float] = None, n: Optional[float] = None, fs: Optional[float] = None): """ Simulation Function: -RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R is None: R = (1/(Q*(2*np.pi*fs)**n)) elif Q is None: Q = (1/(R*(2*np.pi*fs)**n)) elif n is None: n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) return R / (1+R*Q*(w*1j)**n) def cir_RsRQ(w, Rs='none', R='none', Q='none', n='none', fs='none'): """ Simulation Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] Rs = Series resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase elelment exponent [-] fs = Summit frequency of RQ circuit [Hz] """ if R == 'none': R = (1/(Q*(2*np.pi*fs)**n)) elif Q == 'none': Q = (1/(R*(2*np.pi*fs)**n)) elif n == 'none': n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) return Rs + (R/(1+R*Q*(w*1j)**n)) def cir_RC(w, C='none', R='none', fs='none'): """ Simulation Function: -RC- Returns the impedance of an RC circuit, using RQ definations where n=1. see cir_RQ() for details Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] R = Resistance [Ohm] C = Capacitance [F] fs = Summit frequency of RC circuit [Hz] """ return cir_RQ(w, R=R, Q=C, n=1, fs=fs) def cir_RsRQRQ(w, Rs, R='none', Q='none', n='none', fs='none', R2='none', Q2='none', n2='none', fs2='none'): """ Simulation Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RQ_fit() Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [Ohm] R = Resistance [Ohm] Q = Constant phase element [s^n/ohm] n = Constant phase element exponent [-] fs = Summit frequency of RQ circuit [Hz] R2 = Resistance [Ohm] Q2 = Constant phase element [s^n/ohm] n2 = Constant phase element exponent [-] fs2 = Summit frequency of RQ circuit [Hz] """ if R == 'none': R = (1/(Q*(2*np.pi*fs)**n)) elif Q == 'none': Q = (1/(R*(2*np.pi*fs)**n)) elif n == 'none': n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if R2 == 'none': R2 = (1/(Q2*(2*np.pi*fs2)**n2)) elif Q2 == 'none': Q2 = (1/(R2*(2*np.pi*fs2)**n2)) elif n2 == 'none': n2 = np.log(Q2*R2)/np.log(1/(2*np.pi*fs2)) return Rs + (R/(1+R*Q*(w*1j)**n)) + (R2/(1+R2*Q2*(w*1j)**n2)) # L-Rs-RQ-RQ def cir_LRsRQRQ(w, Rs, L, R1: Optional[float] = None, Q1: Optional[float] = None, n1: Optional[float] = None, fs1: Optional[float] = None, R2: Optional[float] = None, Q2: Optional[float] = None, n2: Optional[float] = None, fs2: Optional[float] = None,): """ Simulation Function: L-Rs-RQ-RQ-RQ Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [Ohm] L = Series Impedence R1 = Resistance [Ohm] Q1 = Constant phase element [s^n/ohm] n1 = Constant phase element exponent [-] fs1 = Summit frequency of RQ circuit [Hz] R2 = Resistance [Ohm] Q2 = Constant phase element [s^n/ohm] n2 = Constant phase element exponent [-] fs2 = Summit frequency of RQ circuit [Hz] """ return elem_L(w, L) + Rs + cir_RQ(w, R1, Q1, n1, fs1) + cir_RQ(w, R2, Q2, n2, fs2) def cir_LRsRQRQ_fit(params, w): return cir_LRsRQRQ(w, params['Rs'], params['L'], R1=params.get('R1'), Q1=params.get('Q1'), n1=params.get('n1'), fs1=params.get('fs1'), R2=params.get('R2'), Q2=params.get('Q2'), n2=params.get('n2'), fs2=params.get('fs2')) # L-Rs-RQ-RQ-RQ def cir_LRsRQRQRQ(w, Rs, L, R1: Optional[float] = None, Q1: Optional[float] = None, n1: Optional[float] = None, fs1: Optional[float] = None, R2: Optional[float] = None, Q2: Optional[float] = None, n2: Optional[float] = None, fs2: Optional[float] = None, R3: Optional[float] = None, Q3: Optional[float] = None, n3: Optional[float] = None, fs3: Optional[float] = None,): """ Simulation Function: L-Rs-RQ-RQ-RQ Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [Ohm] L = Series Impedence R1 = Resistance [Ohm] Q1 = Constant phase element [s^n/ohm] n1 = Constant phase element exponent [-] fs1 = Summit frequency of RQ circuit [Hz] R2 = Resistance [Ohm] Q2 = Constant phase element [s^n/ohm] n2 = Constant phase element exponent [-] fs2 = Summit frequency of RQ circuit [Hz] R3 = Resistance [Ohm] Q3 = Constant phase element [s^n/ohm] n3 = Constant phase element exponent [-] fs3 = Summit frequency of RQ circuit [Hz] """ return elem_L(w, L) + Rs + cir_RQ(w, R1, Q1, n1, fs1) + \ cir_RQ(w, R2, Q2, n2, fs2) + \ cir_RQ(w, R3, Q3, n3, fs3) def cir_LRsRQRQRQ_fit(params, w): return cir_LRsRQRQRQ(w, params['Rs'], params['L'], R1=params.get('R1'), Q1=params.get('Q1'), n1=params.get('n1'), fs1=params.get('fs1'), R2=params.get('R2'), Q2=params.get('Q2'), n2=params.get('n2'), fs2=params.get('fs2'), R3=params.get('R3'), Q3=params.get('Q3'), n3=params.get('n3'), fs3=params.get('fs3')) # L-R-Q(R)-Q(R-Q(R))-Q(R) def cir_LRQRQRQRQR(w, Rs, L, R1=None, Q1=None, n1=None, fs1=None, R2=None, Q2=None, n2=None, R3=None, Q3=None, n3=None, fs3=None, R4=None, Q4=None, n4=None, fs4=None): mid_element = (1/elem_Q(w, Q2, n2) + 1/(R2 + cir_RQ(w, R3, Q3, n3, fs3)))**-1 return elem_L(w, L) + Rs + cir_RQ(w, R1, Q1, n1, fs1) + mid_element + cir_RQ(w, R4, Q4, n4, fs4) def cir_LRQRQRQRQR_fit(params, w): return cir_LRQRQRQRQR(w, params['Rs'], params['L'], R1=params.get('R1'), Q1=params.get('Q1'), n1=params.get('n1'), fs1=params.get('fs1'), R2=params.get('R2'), Q2=params.get('Q2'), n2=params.get('n2'), R3=params.get('R3'), Q3=params.get('Q3'), n3=params.get('n3'), fs3=params.get('fs3'), R4=params.get('R4'), Q4=params.get('Q4'), n4=params.get('n4'), fs4=params.get('fs4')) def cir_RsRQQ(w, Rs, Q, n, R1='none', Q1='none', n1='none', fs1='none'): """ Simulation Function: -Rs-RQ-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = Summit frequency of RQ circuit [Hz] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_Q(w,Q,n) def cir_RsRQC(w, Rs, C, R1='none', Q1='none', n1='none', fs1='none'): """ Simulation Function: -Rs-RQ-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] Q1 = Constant phase element in (RQ) circuit [s^n/ohm] n1 = Constant phase elelment exponent in (RQ) circuit [-] fs1 = summit frequency of RQ circuit [Hz] C = Constant phase element of series Q [s^n/ohm] """ return Rs + cir_RQ(w, R=R1, Q=Q1, n=n1, fs=fs1) + elem_C(w, C=C) def cir_RsRCC(w, Rs, R1, C1, C): """ Simulation Function: -Rs-RC-C- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] C = Capacitance of series C [s^n/ohm] """ return Rs + cir_RC(w, C=C1, R=R1, fs='none') + elem_C(w, C=C) def cir_RsRCQ(w, Rs, R1, C1, Q, n): """ Simulation Function: -Rs-RC-Q- Inputs ---------- w = Angular frequency [1/s] Rs = Series Resistance [ohm] R1 = Resistance in (RQ) circuit [ohm] C1 = Constant phase element in (RQ) circuit [s^n/ohm] Q = Constant phase element of series Q [s^n/ohm] n = Constant phase elelment exponent of series Q [-] """ return Rs + cir_RC(w, C=C1, R=R1, fs='none') + elem_Q(w,Q,n) def Randles_coeff(w, n_electron, A, E='none', E0='none', D_red='none', D_ox='none', C_red='none', C_ox='none', Rg=Rg, F=F, T=298.15): """ Returns the Randles coefficient sigma [ohm/s^1/2]. Two cases: a) ox and red are both present in solution here both Cred and Dred are defined, b) In the particular case where initially only Ox species are present in the solution with bulk concentration C*_ox, the surface concentrations may be calculated as function of the electrode potential following Nernst equation. Here C_red and D_red == 'none' Ref.: - Lasia, A.L., ISBN: 978-1-4614-8932-0, "Electrochemical Impedance Spectroscopy and its Applications" - Bard A.J., ISBN: 0-471-04372-9, Faulkner L. R. (2001) "Electrochemical methods: Fundamentals and applications". New York: Wiley. Kristian B. Knudsen (kknu@berkeley.edu // kristianbknudsen@gmail.com) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Bulk concetration of oxidized specie [mol/cm3] C_red = Bulk concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = formal potential [V] if reduced specie is absent == 'none' Returns ---------- Randles coefficient [ohm/s^1/2] """ if C_red != 'none' and D_red != 'none': sigma = ((Rg*T) / ((n_electron**2) * A * (F**2) * (2**(1/2)))) * ((1/(D_ox**(1/2) * C_ox)) + (1/(D_red**(1/2) * C_red))) elif C_red == 'none' and D_red == 'none' and E!='none' and E0!= 'none': f = F/(Rg*T) x = (n_electron*f*(E-E0))/2 func_cosh2 = (np.cosh(2*x)+1)/2 sigma = ((4*Rg*T) / ((n_electron**2) * A * (F**2) * C_ox * ((2*D_ox)**(1/2)) )) * func_cosh2 else: print('define E and E0') Z_Aw = sigma*(w**(-0.5))-1j*sigma*(w**(-0.5)) return Z_Aw def cir_Randles(w, n_electron, D_red, D_ox, C_red, C_ox, Rs, Rct, n, E, A, Q='none', fs='none', E0=0, F=F, Rg=Rg, T=298.15): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with full complity of the warbug constant NOTE: This Randles circuit is only meant for semi-infinate linear diffusion Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ---------- n_electron = number of e- [-] A = geometrical surface area [cm2] D_ox = Diffusion coefficent of oxidized specie [cm2/s] D_red = Diffusion coefficent of reduced specie [cm2/s] C_ox = Concetration of oxidized specie [mol/cm3] C_red = Concetration of reduced specie [mol/cm3] T = Temperature [K] Rg = Gas constant [J/molK] F = Faradays consntat [C/mol] E = Potential [V] if reduced specie is absent == 'none' E0 = Formal potential [V] if reduced specie is absent == 'none' Rs = Series resistance [ohm] Rct = charge-transfer resistance [ohm] Q = Constant phase element used to model the double-layer capacitance [F] n = expononent of the CPE [-] Returns ---------- The real and imaginary impedance of a Randles circuit [ohm] """ Z_Rct = Rct Z_Q = elem_Q(w,Q,n) Z_w = Randles_coeff(w, n_electron=n_electron, E=E, E0=E0, D_red=D_red, D_ox=D_ox, C_red=C_red, C_ox=C_ox, A=A, T=T, Rg=Rg, F=F) return Rs + 1/(1/Z_Q + 1/(Z_Rct+Z_w)) def cir_Randles_simplified(w, Rs, R, n, sigma, Q='none', fs='none'): """ Simulation Function: Randles -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit with a simplified NOTE: This Randles circuit is only meant for semi-infinate linear diffusion Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ if R == 'none': R = (1/(Q*(2*np.pi*fs)**n)) elif Q == 'none': Q = (1/(R*(2*np.pi*fs)**n)) elif n == 'none': n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) Z_Q = 1/(Q*(w*1j)**n) Z_R = R Z_w = sigma*(w**(-0.5))-1j*sigma*(w**(-0.5)) return Rs + 1/(1/Z_Q + 1/(Z_R+Z_w)) def cir_C_RC_C(w, Ce, Cb='none', Rb='none', fsb='none'): """ Simulation Function: -C-(RC)-C- This circuit is often used for modeling blocking electrodes with a polymeric electrolyte, which exhibts a immobile ionic species in bulk that gives a capacitance contribution to the otherwise resistive electrolyte Ref: - MacCallum J.R., and Vincent, C.A. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London, Bruce, P. "Electrical Measurements on Polymer Electrolytes" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] Ce = Interfacial capacitance [F] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = summit frequency of bulk (RC) circuit [Hz] """ Z_C = elem_C(w,C=Ce) Z_RC = cir_RC(w, C=Cb, R=Rb, fs=fsb) return Z_C + Z_RC def cir_Q_RQ_Q(w, Qe, ne, Qb='none', Rb='none', fsb='none', nb='none'): """ Simulation Function: -Q-(RQ)-Q- Modified cir_C_RC_C() circuits that can be used if electrodes and bulk are not behaving like ideal capacitors Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] Qe = Interfacial capacitance modeled with a CPE [F] ne = Interfacial constant phase element exponent [-] Rb = Bulk/series resistance [Ohm] Qb = Bulk capacitance modeled with a CPE [s^n/ohm] nb = Bulk constant phase element exponent [-] fsb = summit frequency of bulk (RQ) circuit [Hz] """ Z_Q = elem_Q(w,Q=Qe,n=ne) Z_RQ = cir_RQ(w, Q=Qb, R=Rb, fs=fsb, n=nb) return Z_Q + Z_RQ def tanh(x): """ As numpy gives errors when tanh becomes very large, above 10^250, this functions is used for np.tanh """ return (1-np.exp(-2*x))/(1+np.exp(-2*x)) def cir_RCRCZD(w, L, D_s, u1, u2, Cb='none', Rb='none', fsb='none', Ce='none', Re='none', fse='none'): """ Simulation Function: -RC_b-RC_e-Z_D This circuit has been used to study non-blocking electrodes with an ioniocally conducting electrolyte with a mobile and immobile ionic specie in bulk, this is mixed with a ionically conducting salt. This behavior yields in a impedance response, that consists of the interfacial impendaces -(RC_e)-, the ionically conducitng polymer -(RC_e)-, and the diffusional impedance from the dissolved salt. Refs.: - Sørensen, P.R. and Jacobsen T., Electrochimica Acta, 27, 1671-1675, 1982, "Conductivity, Charge Transfer and Transport number - An AC-Investigation of the Polymer Electrolyte LiSCN-Poly(ethyleneoxide)" - MacCallum J.R., and Vincent, C.A. "Polymer Electrolyte Reviews - 1" Elsevier Applied Science Publishers LTD, London Bruce, P. "Electrical Measurements on Polymer Electrolytes" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ---------- w = Angular frequency [1/s] L = Thickness of electrode [cm] D_s = Diffusion coefficient of dissolved salt [cm2/s] u1 = Mobility of the ion reacting at the electrode interface u2 = Mobility of other ion Re = Interfacial resistance [Ohm] Ce = Interfacial capacitance [F] fse = Summit frequency of the interfacial (RC) circuit [Hz] Rb = Bulk/series resistance [Ohm] Cb = Bulk capacitance [F] fsb = Summit frequency of the bulk (RC) circuit [Hz] """ Z_RCb = cir_RC(w, C=Cb, R=Rb, fs=fsb) Z_RCe = cir_RC(w, C=Ce, R=Re, fs=fse) alpha = ((w*1j*L**2)/D_s)**(1/2) Z_D = Rb * (u2/u1) * (tanh(x=alpha)/alpha) return Z_RCb + Z_RCe + Z_D def cir_RsTLsQ(w, Rs, L, Ri, Q='none', n='none'): """ Simulation Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = exponent for the interfacial capacitance [-] """ Phi = 1/(Q*(w*1j)**n) X1 = Ri # ohm/cm Lam = (Phi/X1)**(1/2) #np.sqrt(Phi/X1) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_TLsQ def cir_RsRQTLsQ(w, Rs, R1, fs1, n1, L, Ri, Q, n, Q1='none'): """ Simulation Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance(Q) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] Q = Interfacial capacitance of non-faradaic interface [F/cm] n = Exponent for the interfacial capacitance [-] Output ----------- Impdance of Rs-(RQ)1-TLsQ """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = 1/(Q*(w*1j)**n) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs(w, Rs, L, Ri, R='none', Q='none', n='none', fs='none'): """ Simulation Function: -Rs-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ----------- Rs = Series resistance [ohm] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R = Interfacial Charge transfer resistance [ohm*cm] fs = Summit frequency of interfacial RQ circuit [Hz] n = Exponent for interfacial RQ circuit [-] Q = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-TLs(RQ) """ Phi = cir_RQ(w, R, Q, n, fs) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs(w, Rs, L, Ri, R1, n1, fs1, R2, n2, fs2, Q1='none', Q2='none'): """ Simulation Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) The simplified transmission line assumes that Ri is much greater than Rel (electrode resistance). Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) Inputs ----------- Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = Exponent for RQ circuit [-] Q1 = Constant phase element of RQ circuit [s^n/(ohm * cm)] L = Length/Thickness of porous electrode [cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] R2 = Interfacial Charge transfer resistance [ohm*cm] fs2 = Summit frequency of interfacial RQ circuit [Hz] n2 = Exponent for interfacial RQ circuit [-] Q2 = Constant phase element of interfacial capacitance [s^n/Ohm] Output ----------- Impedance of Rs-(RQ)1-TLs(RQ)2 """ Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) Phi = cir_RQ(w=w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs def cir_RsTLQ(w, L, Rs, Q, n, Rel, Ri): """ Simulation Function: -R-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ(w, L, Rs, Q, n, Rel, Ri, R1, n1, fs1, Q1='none'): """ Simulation Function: -R-RQ-TLQ- (interfacial non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] Q = Constant phase element for the interfacial capacitance [s^n/ohm] n = exponenet for interfacial RQ element [-] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ #The impedance of the series resistance Z_Rs = Rs #The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL(w, L, Rs, R, fs, n, Rel, Ri, Q='none'): """ Simulation Function: -R-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] R = Interfacial charge transfer resistance [ohm * cm] fs = Summit frequency for the interfacial RQ element [Hz] n = Exponenet for interfacial RQ element [-] Q = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = Electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = Thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R, Q=Q, n=n, fs=fs) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL(w, L, Rs, R1, fs1, n1, R2, fs2, n2, Rel, Ri, Q1='none', Q2='none'): """ Simulation Function: -R-RQ-TL- (interfacial reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel Ref.: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] R1 = Charge transfer resistance of RQ circuit [ohm] fs1 = Summit frequency for RQ circuit [Hz] n1 = exponent for RQ circuit [-] Q1 = constant phase element of RQ circuit [s^n/(ohm * cm)] R2 = interfacial charge transfer resistance [ohm * cm] fs2 = Summit frequency for the interfacial RQ element [Hz] n2 = exponenet for interfacial RQ element [-] Q2 = Constant phase element for the interfacial capacitance [s^n/ohm] Rel = electronic resistance of electrode [ohm/cm] Ri = Ionic resistance inside of flodded pores [ohm/cm] L = thickness of porous electrode [cm] Output -------------- Impedance of Rs-TL """ #The impedance of the series resistance Z_Rs = Rs #The (RQ) circuit in series with the transmission line Z_RQ1 = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) # The Interfacial impedance is given by an -(RQ)- circuit Phi = cir_RQ(w, R=R2, Q=Q2, n=n2, fs=fs2) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_1Dsolid(w, L, D, radius, Rs, R, Q, n, R_w, n_w, Rel, Ri): """ Simulation Function: -R-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Illig, J., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] R = particle charge transfer resistance [ohm*cm^2] Q = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output -------------- Impedance of Rs-TL(Q(RW)) """ #The impedance of the series resistance Z_Rs = Rs #The impedance of a 1D Warburg Element time_const = (radius**2)/D x = (time_const*w*1j)**n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) Z_w = R_w * np.array(warburg_coth_mp)/x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w,Q=Q,n=n) Z_Randles = 1/(1/Z_Q + 1/(Z_Rct+Z_w)) #Ohm # The Impedance of the Transmission Line lamb = (Z_Randles/(Rel+Ri))**(1/2) x = L/lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/sinh(x))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid(w, L, D, radius, Rs, R1, fs1, n1, R2, Q2, n2, R_w, n_w, Rel, Ri, Q1='none'): """ Simulation Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel Warburg element is specific for 1D solid-state diffusion Refs: - De Levie R., and Delahay P., Advances in Electrochemistry and Electrochemical Engineering, p. 329, Wiley-Interscience, New York (1973) - Bisquert J. Electrochemistry Communications 1, 1999, 429-435, "Anamalous transport effects in the impedance of porous film electrodes" - Bisquert J. J. Phys. Chem. B., 2000, 104, 2287-2298, "Doubling exponent models for the analysis of porous film electrodes by impedance. Relaxation of TiO2 nanoporous in aqueous solution" - Illig, J., Physically based Impedance Modelling of Lithium-ion Cells, KIT Scientific Publishing (2014) - Scipioni, et al., ECS Transactions, 69 (18) 71-80 (2015) David Brown (demoryb@berkeley.edu) Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------------ Rs = Series resistance [ohm] R1 = charge transfer resistance of the interfacial RQ element [ohm*cm^2] fs1 = max frequency peak of the interfacial RQ element[Hz] n1 = exponenet for interfacial RQ element R2 = particle charge transfer resistance [ohm*cm^2] Q2 = Summit frequency peak of RQ element in the modified randles element of a particle [Hz] n2 = exponenet for internal RQ element in the modified randles element of a particle [-] Rel = electronic resistance of electrode [ohm/cm] Ri = ionic resistance of solution in flooded pores of electrode [ohm/cm] R_w = polarization resistance of finite diffusion Warburg element [ohm] n_w = exponent for Warburg element [-] L = thickness of porous electrode [cm] D = solid-state diffusion coefficient [cm^2/s] radius = average particle radius [cm] Output ------------------ Impedance of R-RQ-TL(Q(RW)) """ #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Z_RQ = cir_RQ(w=w, R=R1, Q=Q1, n=n1, fs=fs1) #The impedance of a 1D Warburg Element time_const = (radius**2)/D x = (time_const*w*1j)**n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) Z_w = R_w * np.array(warburg_coth_mp)/x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w,Q=Q2,n=n2) Z_Randles = 1/(1/Z_Q + 1/(Z_Rct+Z_w)) #Ohm # The Impedance of the Transmission Line lamb = (Z_Randles/(Rel+Ri))**(1/2) x = L/lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/sinh(x))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ + Z_TL ###################################### FITS #################################################### def elem_C_fit(params, w): """ Fit Function: -C- """ C = params['C'] return 1/(C*(w*1j)) def elem_Q_fit(params, w): """ Fit Function: -Q- Constant Phase Element for Fitting """ Q = params['Q'] n = params['n'] return 1/(Q*(w*1j)**n) def cir_RsC_fit(params, w): """ Fit Function: -Rs-C- """ Rs = params['Rs'] C = params['C'] return Rs + 1/(C*(w*1j)) def cir_RsQ_fit(params, w): """ Fit Function: -Rs-Q- """ Rs = params['Rs'] Q = params['Q'] n = params['n'] return Rs + 1/(Q*(w*1j)**n) def cir_RC_fit(params, w): """ Fit Function: -RC- Returns the impedance of an RC circuit, using RQ definitions where n=1 """ n=1 if str(params.keys())[10:].find("R") == -1: #if R == 'none': Q = params['C'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("C") == -1: #elif Q == 'none': R = params['R'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) # if str(params.keys())[10:].find("n") == -1: #elif n == 'none': # R = params['R'] # Q = params['C'] # fs = params['fs'] # n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("fs") == -1: #elif fs == 'none': R = params['R'] Q = params['C'] return cir_RQ(w, R=R, Q=Q, n=1, fs=fs) def cir_RQ_fit(params, w): """ Fit Function: -RQ- Return the impedance of an RQ circuit: Z(w) = R / (1+ R*Q * (2w)^n) See Explanation of equations under cir_RQ() The params.keys()[10:] finds the names of the user defined parameters that should be interated over if X == -1, if the paramter is not given, it becomes equal to 'none' Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ if str(params.keys())[10:].find("R") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("Q") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("n") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("fs") == -1: #elif fs == 'none': R = params['R'] n = params['n'] Q = params['Q'] return R/(1+R*Q*(w*1j)**n) def cir_RsRQ_fit(params, w): """ Fit Function: -Rs-RQ- Return the impedance of an Rs-RQ circuit. See details for RQ under cir_RsRQ_fit() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ if str(params.keys())[10:].find("R") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("Q") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("n") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("fs") == -1: #elif fs == 'none': R = params['R'] Q = params['Q'] n = params['n'] Rs = params['Rs'] return Rs + (R/(1+R*Q*(w*1j)**n)) def cir_RsRQRQ_fit(params, w): """ Fit Function: -Rs-RQ-RQ- Return the impedance of an Rs-RQ circuit. See details under cir_RsRQRQ() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ if str(params.keys())[10:].find("'R'") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("'Q'") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("'n'") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("'fs'") == -1: #elif fs == 'none': R = params['R'] Q = params['Q'] n = params['n'] if str(params.keys())[10:].find("'R2'") == -1: #if R == 'none': Q2 = params['Q2'] n2 = params['n2'] fs2 = params['fs2'] R2 = (1/(Q2*(2*np.pi*fs2)**n2)) if str(params.keys())[10:].find("'Q2'") == -1: #elif Q == 'none': R2 = params['R2'] n2 = params['n2'] fs2 = params['fs2'] Q2 = (1/(R2*(2*np.pi*fs2)**n2)) if str(params.keys())[10:].find("'n2'") == -1: #elif n == 'none': R2 = params['R2'] Q2 = params['Q2'] fs2 = params['fs2'] n2 = np.log(Q2*R2)/np.log(1/(2*np.pi*fs2)) if str(params.keys())[10:].find("'fs2'") == -1: #elif fs == 'none': R2 = params['R2'] Q2 = params['Q2'] n2 = params['n2'] Rs = params['Rs'] return Rs + (R/(1+R*Q*(w*1j)**n)) + (R2/(1+R2*Q2*(w*1j)**n2)) def cir_Randles_simplified_Fit(params, w): """ Fit Function: Randles simplified -Rs-(Q-(RW)-)- Return the impedance of a Randles circuit. See more under cir_Randles_simplified() NOTE: This Randles circuit is only meant for semi-infinate linear diffusion Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ if str(params.keys())[10:].find("'R'") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("'Q'") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("'n'") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("'fs'") == -1: #elif fs == 'none': R = params['R'] Q = params['Q'] n = params['n'] Rs = params['Rs'] sigma = params['sigma'] Z_Q = 1/(Q*(w*1j)**n) Z_R = R Z_w = sigma*(w**(-0.5))-1j*sigma*(w**(-0.5)) return Rs + 1/(1/Z_Q + 1/(Z_R+Z_w)) def cir_RsRQQ_fit(params, w): """ Fit Function: -Rs-RQ-Q- See cir_RsRQQ() for details """ Rs = params['Rs'] Q = params['Q'] n = params['n'] Z_Q = 1/(Q*(w*1j)**n) if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) if str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ = (R1/(1+R1*Q1*(w*1j)**n1)) return Rs + Z_RQ + Z_Q def cir_RsRQC_fit(params, w): """ Fit Function: -Rs-RQ-C- See cir_RsRQC() for details """ Rs = params['Rs'] C = params['C'] Z_C = 1/(C*(w*1j)) if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) if str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ = (R1/(1+R1*Q1*(w*1j)**n1)) return Rs + Z_RQ + Z_C def cir_RsRCC_fit(params, w): """ Fit Function: -Rs-RC-C- See cir_RsRCC() for details """ Rs = params['Rs'] R1 = params['R1'] C1 = params['C1'] C = params['C'] return Rs + cir_RC(w, C=C1, R=R1, fs='none') + elem_C(w, C=C) def cir_RsRCQ_fit(params, w): """ Fit Function: -Rs-RC-Q- See cir_RsRCQ() for details """ Rs = params['Rs'] R1 = params['R1'] C1 = params['C1'] Q = params['Q'] n = params['n'] return Rs + cir_RC(w, C=C1, R=R1, fs='none') + elem_Q(w,Q,n) def cir_C_RC_C_fit(params, w): """ Fit Function: -C-(RC)-C- See cir_C_RC_C() for details Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ # Interfacial impedance Ce = params['Ce'] Z_C = 1/(Ce*(w*1j)) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: #if R == 'none': Cb = params['Cb'] fsb = params['fsb'] Rb = (1/(Cb*(2*np.pi*fsb))) if str(params.keys())[10:].find("Cb") == -1: #elif Q == 'none': Rb = params['Rb'] fsb = params['fsb'] Cb = (1/(Rb*(2*np.pi*fsb))) if str(params.keys())[10:].find("fsb") == -1: #elif fs == 'none': Rb = params['Rb'] Cb = params['Cb'] Z_RC = (Rb/(1+Rb*Cb*(w*1j))) return Z_C + Z_RC def cir_Q_RQ_Q_Fit(params, w): """ Fit Function: -Q-(RQ)-Q- See cir_Q_RQ_Q() for details Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ # Interfacial impedance Qe = params['Qe'] ne = params['ne'] Z_Q = 1/(Qe*(w*1j)**ne) # Bulk impedance if str(params.keys())[10:].find("Rb") == -1: #if R == 'none': Qb = params['Qb'] nb = params['nb'] fsb = params['fsb'] Rb = (1/(Qb*(2*np.pi*fsb)**nb)) if str(params.keys())[10:].find("Qb") == -1: #elif Q == 'none': Rb = params['Rb'] nb = params['nb'] fsb = params['fsb'] Qb = (1/(Rb*(2*np.pi*fsb)**nb)) if str(params.keys())[10:].find("nb") == -1: #elif n == 'none': Rb = params['Rb'] Qb = params['Qb'] fsb = params['fsb'] nb = np.log(Qb*Rb)/np.log(1/(2*np.pi*fsb)) if str(params.keys())[10:].find("fsb") == -1: #elif fs == 'none': Rb = params['Rb'] nb = params['nb'] Qb = params['Qb'] Z_RQ = Rb/(1+Rb*Qb*(w*1j)**nb) return Z_Q + Z_RQ def cir_RCRCZD_fit(params, w): """ Fit Function: -RC_b-RC_e-Z_D See cir_RCRCZD() for details Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ # Interfacial impendace if str(params.keys())[10:].find("Re") == -1: #if R == 'none': Ce = params['Ce'] fse = params['fse'] Re = (1/(Ce*(2*np.pi*fse))) if str(params.keys())[10:].find("Ce") == -1: #elif Q == 'none': Re = params['Rb'] fse = params['fsb'] Ce = (1/(Re*(2*np.pi*fse))) if str(params.keys())[10:].find("fse") == -1: #elif fs == 'none': Re = params['Re'] Ce = params['Ce'] Z_RCe = (Re/(1+Re*Ce*(w*1j))) # Bulk impendance if str(params.keys())[10:].find("Rb") == -1: #if R == 'none': Cb = params['Cb'] fsb = params['fsb'] Rb = (1/(Cb*(2*np.pi*fsb))) if str(params.keys())[10:].find("Cb") == -1: #elif Q == 'none': Rb = params['Rb'] fsb = params['fsb'] Cb = (1/(Rb*(2*np.pi*fsb))) if str(params.keys())[10:].find("fsb") == -1: #elif fs == 'none': Rb = params['Rb'] Cb = params['Cb'] Z_RCb = (Rb/(1+Rb*Cb*(w*1j))) # Mass transport impendance L = params['L'] D_s = params['D_s'] u1 = params['u1'] u2 = params['u2'] alpha = ((w*1j*L**2)/D_s)**(1/2) Z_D = Rb * (u2/u1) * (tanh(alpha)/alpha) return Z_RCb + Z_RCe + Z_D def cir_RsTLsQ_fit(params, w): """ Fit Function: -Rs-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsTLsQ() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Q = params['Q'] n = params['n'] Phi = 1/(Q*(w*1j)**n) X1 = Ri # ohm/cm Lam = (Phi/X1)**(1/2) #np.sqrt(Phi/X1) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # # Z_TLsQ = Lam * X1 * coth_mp Z_TLsQ = Lam * X1 * coth(x) return Rs + Z_TLsQ def cir_RsRQTLsQ_Fit(params, w): """ Fit Function: -Rs-RQ-TLsQ- TLs = Simplified Transmission Line, with a non-faradaic interfacial impedance (Q) See more under cir_RsRQTLsQ Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Q = params['Q'] n = params['n'] if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) if str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ = (R1/(1+R1*Q1*(w*1j)**n1)) Phi = 1/(Q*(w*1j)**n) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLsQ = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLsQ def cir_RsTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line, with a faradaic interfacial impedance (RQ) See mor under cir_RsTLs() Kristian B. Knudsen (kknu@berkeley.edu / kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] if str(params.keys())[10:].find("R") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("Q") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("n") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("fs") == -1: #elif fs == 'none': R = params['R'] n = params['n'] Q = params['Q'] Phi = R/(1+R*Q*(w*1j)**n) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_TLs def cir_RsRQTLs_Fit(params, w): """ Fit Function: -Rs-RQ-TLs- TLs = Simplified Transmission Line with a faradaic interfacial impedance (RQ) See more under cir_RsRQTLs() Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) if str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ = (R1/(1+R1*Q1*(w*1j)**n1)) if str(params.keys())[10:].find("R2") == -1: #if R == 'none': Q2 = params['Q2'] n2 = params['n2'] fs2 = params['fs2'] R2 = (1/(Q2*(2*np.pi*fs2)**n2)) if str(params.keys())[10:].find("Q2") == -1: #elif Q == 'none': R2 = params['R2'] n2 = params['n2'] fs2 = params['fs2'] Q2 = (1/(R2*(2*np.pi*fs2)**n1)) if str(params.keys())[10:].find("n2") == -1: #elif n == 'none': R2 = params['R2'] Q2 = params['Q2'] fs2 = params['fs2'] n2 = np.log(Q2*R2)/np.log(1/(2*np.pi*fs2)) if str(params.keys())[10:].find("fs2") == -1: #elif fs == 'none': R2 = params['R2'] n2 = params['n2'] Q2 = params['Q2'] Phi = (R2/(1+R2*Q2*(w*1j)**n2)) X1 = Ri Lam = (Phi/X1)**(1/2) x = L/Lam x_mp = mp.matrix(x) #x in mp.math format coth_mp = [] for i in range(len(Lam)): coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers Z_TLs = Lam * X1 * coth_mp return Rs + Z_RQ + Z_TLs def cir_RsTLQ_fit(params, w): """ Fit Function: -R-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Rel = params['Rel'] Q = params['Q'] n = params['n'] #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTLQ_fit(params, w): """ Fit Function: -R-RQ-TLQ- (interface non-reacting, i.e. blocking electrode) Transmission line w/ full complexity, which both includes Ri and Rel Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Rel = params['Rel'] Q = params['Q'] n = params['n'] #The impedance of the series resistance Z_Rs = Rs #The (RQ) circuit in series with the transmission line if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) if str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) if str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ1 = (R1/(1+R1*Q1*(w*1j)**n1)) # The Interfacial impedance is given by an -(RQ)- circuit Phi = elem_Q(w, Q=Q, n=n) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_Fit(params, w): """ Fit Function: -R-TLQ- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity, which both includes Ri and Rel See cir_RsTL() for details Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Rel = params['Rel'] #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R") == -1: #if R == 'none': Q = params['Q'] n = params['n'] fs = params['fs'] R = (1/(Q*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("Q") == -1: #elif Q == 'none': R = params['R'] n = params['n'] fs = params['fs'] Q = (1/(R*(2*np.pi*fs)**n)) if str(params.keys())[10:].find("n") == -1: #elif n == 'none': R = params['R'] Q = params['Q'] fs = params['fs'] n = np.log(Q*R)/np.log(1/(2*np.pi*fs)) if str(params.keys())[10:].find("fs") == -1: #elif fs == 'none': R = params['R'] n = params['n'] Q = params['Q'] Phi = (R/(1+R*Q*(w*1j)**n)) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float(mp.sinh(x_mp[i]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_fit(params, w): """ Fit Function: -R-RQ-TL- (interface reacting, i.e. non-blocking) Transmission line w/ full complexity including both includes Ri and Rel Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] Rel = params['Rel'] #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) elif str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) elif str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) elif str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ1 = (R1/(1+R1*Q1*(w*1j)**n1)) # # # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R2") == -1: #if R == 'none': Q2 = params['Q2'] n2 = params['n2'] fs2 = params['fs2'] R2 = (1/(Q2*(2*np.pi*fs2)**n2)) elif str(params.keys())[10:].find("Q2") == -1: #elif Q == 'none': R2 = params['R2'] n2 = params['n2'] fs2 = params['fs2'] Q2 = (1/(R2*(2*np.pi*fs2)**n1)) elif str(params.keys())[10:].find("n2") == -1: #elif n == 'none': R2 = params['R2'] Q2 = params['Q2'] fs2 = params['fs2'] n2 = np.log(Q2*R2)/np.log(1/(2*np.pi*fs2)) elif str(params.keys())[10:].find("fs2") == -1: #elif fs == 'none': R2 = params['R2'] n2 = params['n2'] Q2 = params['Q2'] Phi = (R2/(1+R2*Q2*(w*1j)**n2)) X1 = Ri X2 = Rel Lam = (Phi/(X1+X2))**(1/2) x = L/Lam # x_mp = mp.matrix(x) #x in mp.math format # coth_mp = [] # sinh_mp = [] # for i in range(len(Lam)): # coth_mp.append(float(mp.coth(x_mp[i]).real)+float((mp.coth(x_mp[i]).imag))*1j) #Handles coth with x having very large or very small numbers # sinh_mp.append(float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real) + float(((1-mp.exp(-2*x_mp[i]))/(2*mp.exp(-x_mp[i]))).real)*1j) # sinh_mp.append(float(mp.sinh(x_mp[i]).real)+float((mp.sinh(x_mp[i]).imag))*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/np.array(sinh_mp))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*Lam)/sinh(x))) + Lam * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ1 + Z_TL def cir_RsTL_1Dsolid_fit(params, w): """ Fit Function: -R-TL(Q(RW))- Transmission line w/ full complexity See cir_RsTL_1Dsolid() for details David Brown (demoryb@berkeley.edu) Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] radius = params['radius'] D = params['D'] R = params['R'] Q = params['Q'] n = params['n'] R_w = params['R_w'] n_w = params['n_w'] Rel = params['Rel'] Ri = params['Ri'] #The impedance of the series resistance Z_Rs = Rs #The impedance of a 1D Warburg Element time_const = (radius**2)/D x = (time_const*w*1j)**n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) Z_w = R_w * np.array(warburg_coth_mp)/x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R Z_Q = elem_Q(w=w, Q=Q, n=n) Z_Randles = 1/(1/Z_Q + 1/(Z_Rct+Z_w)) #Ohm # The Impedance of the Transmission Line lamb = (Z_Randles/(Rel+Ri))**(1/2) x = L/lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/sinh(x))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_TL def cir_RsRQTL_1Dsolid_fit(params, w): """ Fit Function: -R-RQ-TL(Q(RW))- Transmission line w/ full complexity, which both includes Ri and Rel. The Warburg element is specific for 1D solid-state diffusion See cir_RsRQTL_1Dsolid() for details David Brown (demoryb@berkeley.edu) Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) """ Rs = params['Rs'] L = params['L'] Ri = params['Ri'] radius = params['radius'] D = params['D'] R2 = params['R2'] Q2 = params['Q2'] n2 = params['n2'] R_w = params['R_w'] n_w = params['n_w'] Rel = params['Rel'] Ri = params['Ri'] #The impedance of the series resistance Z_Rs = Rs # The Interfacial impedance is given by an -(RQ)- circuit if str(params.keys())[10:].find("R1") == -1: #if R == 'none': Q1 = params['Q1'] n1 = params['n1'] fs1 = params['fs1'] R1 = (1/(Q1*(2*np.pi*fs1)**n1)) elif str(params.keys())[10:].find("Q1") == -1: #elif Q == 'none': R1 = params['R1'] n1 = params['n1'] fs1 = params['fs1'] Q1 = (1/(R1*(2*np.pi*fs1)**n1)) elif str(params.keys())[10:].find("n1") == -1: #elif n == 'none': R1 = params['R1'] Q1 = params['Q1'] fs1 = params['fs1'] n1 = np.log(Q1*R1)/np.log(1/(2*np.pi*fs1)) elif str(params.keys())[10:].find("fs1") == -1: #elif fs == 'none': R1 = params['R1'] n1 = params['n1'] Q1 = params['Q1'] Z_RQ1 = (R1/(1+R1*Q1*(w*1j)**n1)) #The impedance of a 1D Warburg Element time_const = (radius**2)/D x = (time_const*w*1j)**n_w x_mp = mp.matrix(x) warburg_coth_mp = [] for i in range(len(w)): warburg_coth_mp.append(float(mp.coth(x_mp[i]).real)+float(mp.coth(x_mp[i]).imag)*1j) Z_w = R_w * np.array(warburg_coth_mp)/x # The Interfacial impedance is given by a Randles Equivalent circuit with the finite space warburg element in series with R2 Z_Rct = R2 Z_Q = elem_Q(w,Q=Q2,n=n2) Z_Randles = 1/(1/Z_Q + 1/(Z_Rct+Z_w)) #Ohm # The Impedance of the Transmission Line lamb = (Z_Randles/(Rel+Ri))**(1/2) x = L/lamb # lamb_mp = mp.matrix(x) # sinh_mp = [] # coth_mp = [] # for j in range(len(lamb_mp)): # sinh_mp.append(float(mp.sinh(lamb_mp[j]).real)+float((mp.sinh(lamb_mp[j]).imag))*1j) # coth_mp.append(float(mp.coth(lamb_mp[j]).real)+float(mp.coth(lamb_mp[j]).imag)*1j) # # Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/np.array(sinh_mp))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * np.array(coth_mp) Z_TL = ((Rel*Ri)/(Rel+Ri)) * (L+((2*lamb)/sinh(x))) + lamb * ((Rel**2 + Ri**2)/(Rel+Ri)) * coth(x) return Z_Rs + Z_RQ1 + Z_TL # For the outside world CIRCUIT_DICT = { 'C': elem_C_fit, 'Q': elem_Q_fit, 'R-C': cir_RsC_fit, 'R-Q': cir_RsQ_fit, 'RC': cir_RC_fit, 'RQ': cir_RQ_fit, 'R-RQ': cir_RsRQ_fit, 'R-RQ-RQ': cir_RsRQRQ_fit, 'L-R-RQ-RQ': cir_LRsRQRQ_fit, 'L-R-RQ-RQ-RQ': cir_LRsRQRQRQ_fit, 'L-R-Q(R)-Q(R-Q(R))-Q(R)': cir_LRQRQRQRQR_fit, 'R-RC-C': cir_RsRCC_fit, 'R-RC-Q': cir_RsRCQ_fit, 'R-RQ-Q': cir_RsRQQ_fit, 'R-RQ-C': cir_RsRQC_fit, 'R-(Q(RW))': cir_Randles_simplified_Fit, # 'R-(Q(RM))': cir_Randles_uelectrode_fit, 'C-RC-C': cir_C_RC_C_fit, 'Q-RQ-Q': cir_Q_RQ_Q_Fit, 'RC-RC-ZD': cir_RCRCZD_fit, 'R-TLsQ': cir_RsRQTLsQ_Fit, 'R-RQ-TLsQ': cir_RsRQTLsQ_Fit, 'R-TLs': cir_RsTLs_Fit, 'R-RQ-TLs': cir_RsRQTLs_Fit, 'R-TLQ': cir_RsTLQ_fit, 'R-RQ-TLQ': cir_RsRQTLQ_fit, 'R-Tl': cir_RsTL_Fit, 'R-RQ-TL': cir_RsRQTL_fit, 'R-TL1Dsolid': cir_RsTL_1Dsolid_fit, 'R-RQ-TL1Dsolid': cir_RsRQTL_1Dsolid_fit, } def leastsq_errorfunc(params, w, re, im, circuit, weight_func): """ Sum of squares error function for the complex non-linear least-squares fitting procedure (CNLS). The fitting function (lmfit) will use this function to iterate over until the total sum of errors is minimized. During the minimization the fit is weighed, and currently three different weigh options are avaliable: - modulus - unity - proportional Modulus is generially recommended as random errors and a bias can exist in the experimental data. Kristian B. Knudsen (kknu@berkeley.edu || kristianbknudsen@gmail.com) Inputs ------------ - params: parameters needed for CNLS - re: real impedance - im: Imaginary impedance - circuit: The avaliable circuits are the keys of CIRCUIT_DICT - weight_func Weight function - modulus - unity - proportional """ if circuit in list(CIRCUIT_DICT.keys()): re_fit = CIRCUIT_DICT[circuit](params, w).real im_fit = -CIRCUIT_DICT[circuit](params, w).imag else: raise ValueError(f'circuit {circuit} is not one of the supported circuit strings') # sum of squares error = [(re-re_fit)**2, (im-im_fit)**2] # Different Weighing options, see Lasia if weight_func == 'modulus': weight = [1/((re_fit**2 + im_fit**2)**(1/2)), 1/((re_fit**2 + im_fit**2)**(1/2))] elif weight_func == 'proportional': weight = [1/(re_fit**2), 1/(im_fit**2)] elif weight_func == 'unity': unity_1s = [] for k in range(len(re)): # makes an array of [1]'s, so that the weighing is == 1 * sum of squres. unity_1s.append(1) weight = [unity_1s, unity_1s] else: raise ValueError('weight not defined in leastsq_errorfunc()') # weighted sum of squares S = np.array(weight) * error return S
# Copyright 2015 gRPC authors. # # 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. # AUTO-GENERATED FROM `$REPO_ROOT/templates/src/python/grpcio/grpc_core_dependencies.py.template`!!! CORE_SOURCE_FILES = [ 'src/core/ext/filters/census/grpc_context.cc', 'src/core/ext/filters/client_channel/backend_metric.cc', 'src/core/ext/filters/client_channel/backup_poller.cc', 'src/core/ext/filters/client_channel/channel_connectivity.cc', 'src/core/ext/filters/client_channel/client_channel.cc', 'src/core/ext/filters/client_channel/client_channel_channelz.cc', 'src/core/ext/filters/client_channel/client_channel_factory.cc', 'src/core/ext/filters/client_channel/client_channel_plugin.cc', 'src/core/ext/filters/client_channel/config_selector.cc', 'src/core/ext/filters/client_channel/dynamic_filters.cc', 'src/core/ext/filters/client_channel/global_subchannel_pool.cc', 'src/core/ext/filters/client_channel/health/health_check_client.cc', 'src/core/ext/filters/client_channel/http_connect_handshaker.cc', 'src/core/ext/filters/client_channel/http_proxy.cc', 'src/core/ext/filters/client_channel/lb_policy.cc', 'src/core/ext/filters/client_channel/lb_policy/address_filtering.cc', 'src/core/ext/filters/client_channel/lb_policy/child_policy_handler.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/client_load_reporting_filter.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_balancer_addresses.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_channel_secure.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/grpclb_client_stats.cc', 'src/core/ext/filters/client_channel/lb_policy/grpclb/load_balancer_api.cc', 'src/core/ext/filters/client_channel/lb_policy/pick_first/pick_first.cc', 'src/core/ext/filters/client_channel/lb_policy/priority/priority.cc', 'src/core/ext/filters/client_channel/lb_policy/ring_hash/ring_hash.cc', 'src/core/ext/filters/client_channel/lb_policy/round_robin/round_robin.cc', 'src/core/ext/filters/client_channel/lb_policy/weighted_target/weighted_target.cc', 'src/core/ext/filters/client_channel/lb_policy/xds/cds.cc', 'src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_impl.cc', 'src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_manager.cc', 'src/core/ext/filters/client_channel/lb_policy/xds/xds_cluster_resolver.cc', 'src/core/ext/filters/client_channel/lb_policy_registry.cc', 'src/core/ext/filters/client_channel/local_subchannel_pool.cc', 'src/core/ext/filters/client_channel/proxy_mapper_registry.cc', 'src/core/ext/filters/client_channel/resolver.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/dns_resolver_ares.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_event_engine.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_posix.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_ev_driver_windows.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_event_engine.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_posix.cc', 'src/core/ext/filters/client_channel/resolver/dns/c_ares/grpc_ares_wrapper_windows.cc', 'src/core/ext/filters/client_channel/resolver/dns/dns_resolver_selection.cc', 'src/core/ext/filters/client_channel/resolver/dns/native/dns_resolver.cc', 'src/core/ext/filters/client_channel/resolver/fake/fake_resolver.cc', 'src/core/ext/filters/client_channel/resolver/google_c2p/google_c2p_resolver.cc', 'src/core/ext/filters/client_channel/resolver/sockaddr/sockaddr_resolver.cc', 'src/core/ext/filters/client_channel/resolver/xds/xds_resolver.cc', 'src/core/ext/filters/client_channel/resolver_registry.cc', 'src/core/ext/filters/client_channel/resolver_result_parsing.cc', 'src/core/ext/filters/client_channel/retry_filter.cc', 'src/core/ext/filters/client_channel/retry_service_config.cc', 'src/core/ext/filters/client_channel/retry_throttle.cc', 'src/core/ext/filters/client_channel/server_address.cc', 'src/core/ext/filters/client_channel/service_config_channel_arg_filter.cc', 'src/core/ext/filters/client_channel/subchannel.cc', 'src/core/ext/filters/client_channel/subchannel_pool_interface.cc', 'src/core/ext/filters/client_idle/client_idle_filter.cc', 'src/core/ext/filters/client_idle/idle_filter_state.cc', 'src/core/ext/filters/deadline/deadline_filter.cc', 'src/core/ext/filters/fault_injection/fault_injection_filter.cc', 'src/core/ext/filters/fault_injection/service_config_parser.cc', 'src/core/ext/filters/http/client/http_client_filter.cc', 'src/core/ext/filters/http/client_authority_filter.cc', 'src/core/ext/filters/http/http_filters_plugin.cc', 'src/core/ext/filters/http/message_compress/message_compress_filter.cc', 'src/core/ext/filters/http/message_compress/message_decompress_filter.cc', 'src/core/ext/filters/http/server/http_server_filter.cc', 'src/core/ext/filters/max_age/max_age_filter.cc', 'src/core/ext/filters/message_size/message_size_filter.cc', 'src/core/ext/filters/workarounds/workaround_cronet_compression_filter.cc', 'src/core/ext/filters/workarounds/workaround_utils.cc', 'src/core/ext/service_config/service_config.cc', 'src/core/ext/service_config/service_config_parser.cc', 'src/core/ext/transport/chttp2/alpn/alpn.cc', 'src/core/ext/transport/chttp2/client/chttp2_connector.cc', 'src/core/ext/transport/chttp2/client/insecure/channel_create.cc', 'src/core/ext/transport/chttp2/client/insecure/channel_create_posix.cc', 'src/core/ext/transport/chttp2/client/secure/secure_channel_create.cc', 'src/core/ext/transport/chttp2/server/chttp2_server.cc', 'src/core/ext/transport/chttp2/server/insecure/server_chttp2.cc', 'src/core/ext/transport/chttp2/server/insecure/server_chttp2_posix.cc', 'src/core/ext/transport/chttp2/server/secure/server_secure_chttp2.cc', 'src/core/ext/transport/chttp2/transport/bin_decoder.cc', 'src/core/ext/transport/chttp2/transport/bin_encoder.cc', 'src/core/ext/transport/chttp2/transport/chttp2_plugin.cc', 'src/core/ext/transport/chttp2/transport/chttp2_transport.cc', 'src/core/ext/transport/chttp2/transport/context_list.cc', 'src/core/ext/transport/chttp2/transport/flow_control.cc', 'src/core/ext/transport/chttp2/transport/frame_data.cc', 'src/core/ext/transport/chttp2/transport/frame_goaway.cc', 'src/core/ext/transport/chttp2/transport/frame_ping.cc', 'src/core/ext/transport/chttp2/transport/frame_rst_stream.cc', 'src/core/ext/transport/chttp2/transport/frame_settings.cc', 'src/core/ext/transport/chttp2/transport/frame_window_update.cc', 'src/core/ext/transport/chttp2/transport/hpack_encoder.cc', 'src/core/ext/transport/chttp2/transport/hpack_encoder_table.cc', 'src/core/ext/transport/chttp2/transport/hpack_parser.cc', 'src/core/ext/transport/chttp2/transport/hpack_parser_table.cc', 'src/core/ext/transport/chttp2/transport/hpack_utils.cc', 'src/core/ext/transport/chttp2/transport/http2_settings.cc', 'src/core/ext/transport/chttp2/transport/huffsyms.cc', 'src/core/ext/transport/chttp2/transport/parsing.cc', 'src/core/ext/transport/chttp2/transport/stream_lists.cc', 'src/core/ext/transport/chttp2/transport/stream_map.cc', 'src/core/ext/transport/chttp2/transport/varint.cc', 'src/core/ext/transport/chttp2/transport/writing.cc', 'src/core/ext/transport/inproc/inproc_plugin.cc', 'src/core/ext/transport/inproc/inproc_transport.cc', 'src/core/ext/upb-generated/envoy/admin/v3/config_dump.upb.c', 'src/core/ext/upb-generated/envoy/annotations/deprecation.upb.c', 'src/core/ext/upb-generated/envoy/annotations/resource.upb.c', 'src/core/ext/upb-generated/envoy/config/accesslog/v3/accesslog.upb.c', 'src/core/ext/upb-generated/envoy/config/bootstrap/v3/bootstrap.upb.c', 'src/core/ext/upb-generated/envoy/config/cluster/v3/circuit_breaker.upb.c', 'src/core/ext/upb-generated/envoy/config/cluster/v3/cluster.upb.c', 'src/core/ext/upb-generated/envoy/config/cluster/v3/filter.upb.c', 'src/core/ext/upb-generated/envoy/config/cluster/v3/outlier_detection.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/address.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/backoff.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/base.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/config_source.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/event_service_config.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/extension.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/grpc_service.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/health_check.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/http_uri.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/protocol.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/proxy_protocol.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/resolver.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/socket_option.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/substitution_format_string.upb.c', 'src/core/ext/upb-generated/envoy/config/core/v3/udp_socket_config.upb.c', 'src/core/ext/upb-generated/envoy/config/endpoint/v3/endpoint.upb.c', 'src/core/ext/upb-generated/envoy/config/endpoint/v3/endpoint_components.upb.c', 'src/core/ext/upb-generated/envoy/config/endpoint/v3/load_report.upb.c', 'src/core/ext/upb-generated/envoy/config/listener/v3/api_listener.upb.c', 'src/core/ext/upb-generated/envoy/config/listener/v3/listener.upb.c', 'src/core/ext/upb-generated/envoy/config/listener/v3/listener_components.upb.c', 'src/core/ext/upb-generated/envoy/config/listener/v3/quic_config.upb.c', 'src/core/ext/upb-generated/envoy/config/listener/v3/udp_listener_config.upb.c', 'src/core/ext/upb-generated/envoy/config/metrics/v3/stats.upb.c', 'src/core/ext/upb-generated/envoy/config/overload/v3/overload.upb.c', 'src/core/ext/upb-generated/envoy/config/rbac/v3/rbac.upb.c', 'src/core/ext/upb-generated/envoy/config/route/v3/route.upb.c', 'src/core/ext/upb-generated/envoy/config/route/v3/route_components.upb.c', 'src/core/ext/upb-generated/envoy/config/route/v3/scoped_route.upb.c', 'src/core/ext/upb-generated/envoy/config/trace/v3/http_tracer.upb.c', 'src/core/ext/upb-generated/envoy/extensions/clusters/aggregate/v3/cluster.upb.c', 'src/core/ext/upb-generated/envoy/extensions/filters/common/fault/v3/fault.upb.c', 'src/core/ext/upb-generated/envoy/extensions/filters/http/fault/v3/fault.upb.c', 'src/core/ext/upb-generated/envoy/extensions/filters/http/router/v3/router.upb.c', 'src/core/ext/upb-generated/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.upb.c', 'src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/cert.upb.c', 'src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/common.upb.c', 'src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/secret.upb.c', 'src/core/ext/upb-generated/envoy/extensions/transport_sockets/tls/v3/tls.upb.c', 'src/core/ext/upb-generated/envoy/service/cluster/v3/cds.upb.c', 'src/core/ext/upb-generated/envoy/service/discovery/v3/ads.upb.c', 'src/core/ext/upb-generated/envoy/service/discovery/v3/discovery.upb.c', 'src/core/ext/upb-generated/envoy/service/endpoint/v3/eds.upb.c', 'src/core/ext/upb-generated/envoy/service/listener/v3/lds.upb.c', 'src/core/ext/upb-generated/envoy/service/load_stats/v3/lrs.upb.c', 'src/core/ext/upb-generated/envoy/service/route/v3/rds.upb.c', 'src/core/ext/upb-generated/envoy/service/route/v3/srds.upb.c', 'src/core/ext/upb-generated/envoy/service/status/v3/csds.upb.c', 'src/core/ext/upb-generated/envoy/type/http/v3/path_transformation.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/metadata.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/node.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/number.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/path.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/regex.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/string.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/struct.upb.c', 'src/core/ext/upb-generated/envoy/type/matcher/v3/value.upb.c', 'src/core/ext/upb-generated/envoy/type/metadata/v3/metadata.upb.c', 'src/core/ext/upb-generated/envoy/type/tracing/v3/custom_tag.upb.c', 'src/core/ext/upb-generated/envoy/type/v3/http.upb.c', 'src/core/ext/upb-generated/envoy/type/v3/percent.upb.c', 'src/core/ext/upb-generated/envoy/type/v3/range.upb.c', 'src/core/ext/upb-generated/envoy/type/v3/semantic_version.upb.c', 'src/core/ext/upb-generated/google/api/annotations.upb.c', 'src/core/ext/upb-generated/google/api/expr/v1alpha1/checked.upb.c', 'src/core/ext/upb-generated/google/api/expr/v1alpha1/syntax.upb.c', 'src/core/ext/upb-generated/google/api/http.upb.c', 'src/core/ext/upb-generated/google/protobuf/any.upb.c', 'src/core/ext/upb-generated/google/protobuf/descriptor.upb.c', 'src/core/ext/upb-generated/google/protobuf/duration.upb.c', 'src/core/ext/upb-generated/google/protobuf/empty.upb.c', 'src/core/ext/upb-generated/google/protobuf/struct.upb.c', 'src/core/ext/upb-generated/google/protobuf/timestamp.upb.c', 'src/core/ext/upb-generated/google/protobuf/wrappers.upb.c', 'src/core/ext/upb-generated/google/rpc/status.upb.c', 'src/core/ext/upb-generated/src/proto/grpc/gcp/altscontext.upb.c', 'src/core/ext/upb-generated/src/proto/grpc/gcp/handshaker.upb.c', 'src/core/ext/upb-generated/src/proto/grpc/gcp/transport_security_common.upb.c', 'src/core/ext/upb-generated/src/proto/grpc/health/v1/health.upb.c', 'src/core/ext/upb-generated/src/proto/grpc/lb/v1/load_balancer.upb.c', 'src/core/ext/upb-generated/udpa/annotations/migrate.upb.c', 'src/core/ext/upb-generated/udpa/annotations/security.upb.c', 'src/core/ext/upb-generated/udpa/annotations/sensitive.upb.c', 'src/core/ext/upb-generated/udpa/annotations/status.upb.c', 'src/core/ext/upb-generated/udpa/annotations/versioning.upb.c', 'src/core/ext/upb-generated/udpa/data/orca/v1/orca_load_report.upb.c', 'src/core/ext/upb-generated/udpa/type/v1/typed_struct.upb.c', 'src/core/ext/upb-generated/validate/validate.upb.c', 'src/core/ext/upb-generated/xds/core/v3/authority.upb.c', 'src/core/ext/upb-generated/xds/core/v3/collection_entry.upb.c', 'src/core/ext/upb-generated/xds/core/v3/context_params.upb.c', 'src/core/ext/upb-generated/xds/core/v3/resource.upb.c', 'src/core/ext/upb-generated/xds/core/v3/resource_locator.upb.c', 'src/core/ext/upb-generated/xds/core/v3/resource_name.upb.c', 'src/core/ext/upbdefs-generated/envoy/admin/v3/config_dump.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/annotations/deprecation.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/annotations/resource.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/accesslog/v3/accesslog.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/bootstrap/v3/bootstrap.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/cluster/v3/circuit_breaker.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/cluster/v3/cluster.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/cluster/v3/filter.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/cluster/v3/outlier_detection.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/address.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/backoff.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/base.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/config_source.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/event_service_config.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/extension.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/grpc_service.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/health_check.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/http_uri.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/protocol.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/proxy_protocol.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/resolver.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/socket_option.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/substitution_format_string.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/core/v3/udp_socket_config.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/endpoint/v3/endpoint.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/endpoint/v3/endpoint_components.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/endpoint/v3/load_report.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/listener/v3/api_listener.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/listener/v3/listener.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/listener/v3/listener_components.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/listener/v3/quic_config.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/listener/v3/udp_listener_config.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/metrics/v3/stats.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/overload/v3/overload.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/route/v3/route.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/route/v3/route_components.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/route/v3/scoped_route.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/config/trace/v3/http_tracer.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/clusters/aggregate/v3/cluster.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/filters/common/fault/v3/fault.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/filters/http/fault/v3/fault.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/filters/http/router/v3/router.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/filters/network/http_connection_manager/v3/http_connection_manager.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/cert.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/common.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/secret.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/extensions/transport_sockets/tls/v3/tls.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/cluster/v3/cds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/discovery/v3/ads.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/discovery/v3/discovery.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/endpoint/v3/eds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/listener/v3/lds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/load_stats/v3/lrs.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/route/v3/rds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/route/v3/srds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/service/status/v3/csds.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/http/v3/path_transformation.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/metadata.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/node.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/number.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/path.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/regex.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/string.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/struct.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/matcher/v3/value.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/metadata/v3/metadata.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/tracing/v3/custom_tag.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/v3/http.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/v3/percent.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/v3/range.upbdefs.c', 'src/core/ext/upbdefs-generated/envoy/type/v3/semantic_version.upbdefs.c', 'src/core/ext/upbdefs-generated/google/api/annotations.upbdefs.c', 'src/core/ext/upbdefs-generated/google/api/http.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/any.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/descriptor.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/duration.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/empty.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/struct.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/timestamp.upbdefs.c', 'src/core/ext/upbdefs-generated/google/protobuf/wrappers.upbdefs.c', 'src/core/ext/upbdefs-generated/google/rpc/status.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/annotations/migrate.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/annotations/security.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/annotations/sensitive.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/annotations/status.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/annotations/versioning.upbdefs.c', 'src/core/ext/upbdefs-generated/udpa/type/v1/typed_struct.upbdefs.c', 'src/core/ext/upbdefs-generated/validate/validate.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/authority.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/collection_entry.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/context_params.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/resource.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/resource_locator.upbdefs.c', 'src/core/ext/upbdefs-generated/xds/core/v3/resource_name.upbdefs.c', 'src/core/ext/xds/certificate_provider_registry.cc', 'src/core/ext/xds/certificate_provider_store.cc', 'src/core/ext/xds/file_watcher_certificate_provider_factory.cc', 'src/core/ext/xds/xds_api.cc', 'src/core/ext/xds/xds_bootstrap.cc', 'src/core/ext/xds/xds_certificate_provider.cc', 'src/core/ext/xds/xds_client.cc', 'src/core/ext/xds/xds_client_stats.cc', 'src/core/ext/xds/xds_http_fault_filter.cc', 'src/core/ext/xds/xds_http_filters.cc', 'src/core/ext/xds/xds_server_config_fetcher.cc', 'src/core/lib/address_utils/parse_address.cc', 'src/core/lib/address_utils/sockaddr_utils.cc', 'src/core/lib/avl/avl.cc', 'src/core/lib/backoff/backoff.cc', 'src/core/lib/channel/channel_args.cc', 'src/core/lib/channel/channel_stack.cc', 'src/core/lib/channel/channel_stack_builder.cc', 'src/core/lib/channel/channel_trace.cc', 'src/core/lib/channel/channelz.cc', 'src/core/lib/channel/channelz_registry.cc', 'src/core/lib/channel/connected_channel.cc', 'src/core/lib/channel/handshaker.cc', 'src/core/lib/channel/handshaker_registry.cc', 'src/core/lib/channel/status_util.cc', 'src/core/lib/compression/compression.cc', 'src/core/lib/compression/compression_args.cc', 'src/core/lib/compression/compression_internal.cc', 'src/core/lib/compression/message_compress.cc', 'src/core/lib/compression/stream_compression.cc', 'src/core/lib/compression/stream_compression_gzip.cc', 'src/core/lib/compression/stream_compression_identity.cc', 'src/core/lib/config/core_configuration.cc', 'src/core/lib/debug/stats.cc', 'src/core/lib/debug/stats_data.cc', 'src/core/lib/debug/trace.cc', 'src/core/lib/event_engine/endpoint_config.cc', 'src/core/lib/event_engine/event_engine.cc', 'src/core/lib/event_engine/sockaddr.cc', 'src/core/lib/gpr/alloc.cc', 'src/core/lib/gpr/atm.cc', 'src/core/lib/gpr/cpu_iphone.cc', 'src/core/lib/gpr/cpu_linux.cc', 'src/core/lib/gpr/cpu_posix.cc', 'src/core/lib/gpr/cpu_windows.cc', 'src/core/lib/gpr/env_linux.cc', 'src/core/lib/gpr/env_posix.cc', 'src/core/lib/gpr/env_windows.cc', 'src/core/lib/gpr/log.cc', 'src/core/lib/gpr/log_android.cc', 'src/core/lib/gpr/log_linux.cc', 'src/core/lib/gpr/log_posix.cc', 'src/core/lib/gpr/log_windows.cc', 'src/core/lib/gpr/murmur_hash.cc', 'src/core/lib/gpr/string.cc', 'src/core/lib/gpr/string_posix.cc', 'src/core/lib/gpr/string_util_windows.cc', 'src/core/lib/gpr/string_windows.cc', 'src/core/lib/gpr/sync.cc', 'src/core/lib/gpr/sync_abseil.cc', 'src/core/lib/gpr/sync_posix.cc', 'src/core/lib/gpr/sync_windows.cc', 'src/core/lib/gpr/time.cc', 'src/core/lib/gpr/time_posix.cc', 'src/core/lib/gpr/time_precise.cc', 'src/core/lib/gpr/time_windows.cc', 'src/core/lib/gpr/tmpfile_msys.cc', 'src/core/lib/gpr/tmpfile_posix.cc', 'src/core/lib/gpr/tmpfile_windows.cc', 'src/core/lib/gpr/wrap_memcpy.cc', 'src/core/lib/gprpp/arena.cc', 'src/core/lib/gprpp/examine_stack.cc', 'src/core/lib/gprpp/fork.cc', 'src/core/lib/gprpp/global_config_env.cc', 'src/core/lib/gprpp/host_port.cc', 'src/core/lib/gprpp/mpscq.cc', 'src/core/lib/gprpp/stat_posix.cc', 'src/core/lib/gprpp/stat_windows.cc', 'src/core/lib/gprpp/status_helper.cc', 'src/core/lib/gprpp/thd_posix.cc', 'src/core/lib/gprpp/thd_windows.cc', 'src/core/lib/gprpp/time_util.cc', 'src/core/lib/http/format_request.cc', 'src/core/lib/http/httpcli.cc', 'src/core/lib/http/httpcli_security_connector.cc', 'src/core/lib/http/parser.cc', 'src/core/lib/iomgr/buffer_list.cc', 'src/core/lib/iomgr/call_combiner.cc', 'src/core/lib/iomgr/cfstream_handle.cc', 'src/core/lib/iomgr/combiner.cc', 'src/core/lib/iomgr/dualstack_socket_posix.cc', 'src/core/lib/iomgr/endpoint.cc', 'src/core/lib/iomgr/endpoint_cfstream.cc', 'src/core/lib/iomgr/endpoint_pair_event_engine.cc', 'src/core/lib/iomgr/endpoint_pair_posix.cc', 'src/core/lib/iomgr/endpoint_pair_windows.cc', 'src/core/lib/iomgr/error.cc', 'src/core/lib/iomgr/error_cfstream.cc', 'src/core/lib/iomgr/ev_apple.cc', 'src/core/lib/iomgr/ev_epoll1_linux.cc', 'src/core/lib/iomgr/ev_epollex_linux.cc', 'src/core/lib/iomgr/ev_poll_posix.cc', 'src/core/lib/iomgr/ev_posix.cc', 'src/core/lib/iomgr/ev_windows.cc', 'src/core/lib/iomgr/event_engine/closure.cc', 'src/core/lib/iomgr/event_engine/endpoint.cc', 'src/core/lib/iomgr/event_engine/iomgr.cc', 'src/core/lib/iomgr/event_engine/pollset.cc', 'src/core/lib/iomgr/event_engine/resolved_address_internal.cc', 'src/core/lib/iomgr/event_engine/resolver.cc', 'src/core/lib/iomgr/event_engine/tcp.cc', 'src/core/lib/iomgr/event_engine/timer.cc', 'src/core/lib/iomgr/exec_ctx.cc', 'src/core/lib/iomgr/executor.cc', 'src/core/lib/iomgr/executor/mpmcqueue.cc', 'src/core/lib/iomgr/executor/threadpool.cc', 'src/core/lib/iomgr/fork_posix.cc', 'src/core/lib/iomgr/fork_windows.cc', 'src/core/lib/iomgr/gethostname_fallback.cc', 'src/core/lib/iomgr/gethostname_host_name_max.cc', 'src/core/lib/iomgr/gethostname_sysconf.cc', 'src/core/lib/iomgr/grpc_if_nametoindex_posix.cc', 'src/core/lib/iomgr/grpc_if_nametoindex_unsupported.cc', 'src/core/lib/iomgr/internal_errqueue.cc', 'src/core/lib/iomgr/iocp_windows.cc', 'src/core/lib/iomgr/iomgr.cc', 'src/core/lib/iomgr/iomgr_custom.cc', 'src/core/lib/iomgr/iomgr_internal.cc', 'src/core/lib/iomgr/iomgr_posix.cc', 'src/core/lib/iomgr/iomgr_posix_cfstream.cc', 'src/core/lib/iomgr/iomgr_windows.cc', 'src/core/lib/iomgr/is_epollexclusive_available.cc', 'src/core/lib/iomgr/load_file.cc', 'src/core/lib/iomgr/lockfree_event.cc', 'src/core/lib/iomgr/polling_entity.cc', 'src/core/lib/iomgr/pollset.cc', 'src/core/lib/iomgr/pollset_custom.cc', 'src/core/lib/iomgr/pollset_set.cc', 'src/core/lib/iomgr/pollset_set_custom.cc', 'src/core/lib/iomgr/pollset_set_windows.cc', 'src/core/lib/iomgr/pollset_windows.cc', 'src/core/lib/iomgr/resolve_address.cc', 'src/core/lib/iomgr/resolve_address_custom.cc', 'src/core/lib/iomgr/resolve_address_posix.cc', 'src/core/lib/iomgr/resolve_address_windows.cc', 'src/core/lib/iomgr/resource_quota.cc', 'src/core/lib/iomgr/socket_factory_posix.cc', 'src/core/lib/iomgr/socket_mutator.cc', 'src/core/lib/iomgr/socket_utils_common_posix.cc', 'src/core/lib/iomgr/socket_utils_linux.cc', 'src/core/lib/iomgr/socket_utils_posix.cc', 'src/core/lib/iomgr/socket_utils_windows.cc', 'src/core/lib/iomgr/socket_windows.cc', 'src/core/lib/iomgr/tcp_client.cc', 'src/core/lib/iomgr/tcp_client_cfstream.cc', 'src/core/lib/iomgr/tcp_client_custom.cc', 'src/core/lib/iomgr/tcp_client_posix.cc', 'src/core/lib/iomgr/tcp_client_windows.cc', 'src/core/lib/iomgr/tcp_custom.cc', 'src/core/lib/iomgr/tcp_posix.cc', 'src/core/lib/iomgr/tcp_server.cc', 'src/core/lib/iomgr/tcp_server_custom.cc', 'src/core/lib/iomgr/tcp_server_posix.cc', 'src/core/lib/iomgr/tcp_server_utils_posix_common.cc', 'src/core/lib/iomgr/tcp_server_utils_posix_ifaddrs.cc', 'src/core/lib/iomgr/tcp_server_utils_posix_noifaddrs.cc', 'src/core/lib/iomgr/tcp_server_windows.cc', 'src/core/lib/iomgr/tcp_windows.cc', 'src/core/lib/iomgr/time_averaged_stats.cc', 'src/core/lib/iomgr/timer.cc', 'src/core/lib/iomgr/timer_custom.cc', 'src/core/lib/iomgr/timer_generic.cc', 'src/core/lib/iomgr/timer_heap.cc', 'src/core/lib/iomgr/timer_manager.cc', 'src/core/lib/iomgr/unix_sockets_posix.cc', 'src/core/lib/iomgr/unix_sockets_posix_noop.cc', 'src/core/lib/iomgr/wakeup_fd_eventfd.cc', 'src/core/lib/iomgr/wakeup_fd_nospecial.cc', 'src/core/lib/iomgr/wakeup_fd_pipe.cc', 'src/core/lib/iomgr/wakeup_fd_posix.cc', 'src/core/lib/iomgr/work_serializer.cc', 'src/core/lib/json/json_reader.cc', 'src/core/lib/json/json_util.cc', 'src/core/lib/json/json_writer.cc', 'src/core/lib/matchers/matchers.cc', 'src/core/lib/profiling/basic_timers.cc', 'src/core/lib/profiling/stap_timers.cc', 'src/core/lib/security/authorization/authorization_policy_provider_vtable.cc', 'src/core/lib/security/authorization/evaluate_args.cc', 'src/core/lib/security/authorization/sdk_server_authz_filter.cc', 'src/core/lib/security/context/security_context.cc', 'src/core/lib/security/credentials/alts/alts_credentials.cc', 'src/core/lib/security/credentials/alts/check_gcp_environment.cc', 'src/core/lib/security/credentials/alts/check_gcp_environment_linux.cc', 'src/core/lib/security/credentials/alts/check_gcp_environment_no_op.cc', 'src/core/lib/security/credentials/alts/check_gcp_environment_windows.cc', 'src/core/lib/security/credentials/alts/grpc_alts_credentials_client_options.cc', 'src/core/lib/security/credentials/alts/grpc_alts_credentials_options.cc', 'src/core/lib/security/credentials/alts/grpc_alts_credentials_server_options.cc', 'src/core/lib/security/credentials/composite/composite_credentials.cc', 'src/core/lib/security/credentials/credentials.cc', 'src/core/lib/security/credentials/credentials_metadata.cc', 'src/core/lib/security/credentials/external/aws_external_account_credentials.cc', 'src/core/lib/security/credentials/external/aws_request_signer.cc', 'src/core/lib/security/credentials/external/external_account_credentials.cc', 'src/core/lib/security/credentials/external/file_external_account_credentials.cc', 'src/core/lib/security/credentials/external/url_external_account_credentials.cc', 'src/core/lib/security/credentials/fake/fake_credentials.cc', 'src/core/lib/security/credentials/google_default/credentials_generic.cc', 'src/core/lib/security/credentials/google_default/google_default_credentials.cc', 'src/core/lib/security/credentials/iam/iam_credentials.cc', 'src/core/lib/security/credentials/insecure/insecure_credentials.cc', 'src/core/lib/security/credentials/jwt/json_token.cc', 'src/core/lib/security/credentials/jwt/jwt_credentials.cc', 'src/core/lib/security/credentials/jwt/jwt_verifier.cc', 'src/core/lib/security/credentials/local/local_credentials.cc', 'src/core/lib/security/credentials/oauth2/oauth2_credentials.cc', 'src/core/lib/security/credentials/plugin/plugin_credentials.cc', 'src/core/lib/security/credentials/ssl/ssl_credentials.cc', 'src/core/lib/security/credentials/tls/grpc_tls_certificate_distributor.cc', 'src/core/lib/security/credentials/tls/grpc_tls_certificate_provider.cc', 'src/core/lib/security/credentials/tls/grpc_tls_credentials_options.cc', 'src/core/lib/security/credentials/tls/tls_credentials.cc', 'src/core/lib/security/credentials/tls/tls_utils.cc', 'src/core/lib/security/credentials/xds/xds_credentials.cc', 'src/core/lib/security/security_connector/alts/alts_security_connector.cc', 'src/core/lib/security/security_connector/fake/fake_security_connector.cc', 'src/core/lib/security/security_connector/insecure/insecure_security_connector.cc', 'src/core/lib/security/security_connector/load_system_roots_fallback.cc', 'src/core/lib/security/security_connector/load_system_roots_linux.cc', 'src/core/lib/security/security_connector/local/local_security_connector.cc', 'src/core/lib/security/security_connector/security_connector.cc', 'src/core/lib/security/security_connector/ssl/ssl_security_connector.cc', 'src/core/lib/security/security_connector/ssl_utils.cc', 'src/core/lib/security/security_connector/ssl_utils_config.cc', 'src/core/lib/security/security_connector/tls/tls_security_connector.cc', 'src/core/lib/security/transport/client_auth_filter.cc', 'src/core/lib/security/transport/secure_endpoint.cc', 'src/core/lib/security/transport/security_handshaker.cc', 'src/core/lib/security/transport/server_auth_filter.cc', 'src/core/lib/security/transport/tsi_error.cc', 'src/core/lib/security/util/json_util.cc', 'src/core/lib/slice/b64.cc', 'src/core/lib/slice/percent_encoding.cc', 'src/core/lib/slice/slice.cc', 'src/core/lib/slice/slice_api.cc', 'src/core/lib/slice/slice_buffer.cc', 'src/core/lib/slice/slice_intern.cc', 'src/core/lib/slice/slice_refcount.cc', 'src/core/lib/slice/slice_split.cc', 'src/core/lib/slice/slice_string_helpers.cc', 'src/core/lib/slice/static_slice.cc', 'src/core/lib/surface/api_trace.cc', 'src/core/lib/surface/builtins.cc', 'src/core/lib/surface/byte_buffer.cc', 'src/core/lib/surface/byte_buffer_reader.cc', 'src/core/lib/surface/call.cc', 'src/core/lib/surface/call_details.cc', 'src/core/lib/surface/call_log_batch.cc', 'src/core/lib/surface/channel.cc', 'src/core/lib/surface/channel_init.cc', 'src/core/lib/surface/channel_ping.cc', 'src/core/lib/surface/channel_stack_type.cc', 'src/core/lib/surface/completion_queue.cc', 'src/core/lib/surface/completion_queue_factory.cc', 'src/core/lib/surface/event_string.cc', 'src/core/lib/surface/init.cc', 'src/core/lib/surface/init_secure.cc', 'src/core/lib/surface/lame_client.cc', 'src/core/lib/surface/metadata_array.cc', 'src/core/lib/surface/server.cc', 'src/core/lib/surface/validate_metadata.cc', 'src/core/lib/surface/version.cc', 'src/core/lib/transport/bdp_estimator.cc', 'src/core/lib/transport/byte_stream.cc', 'src/core/lib/transport/connectivity_state.cc', 'src/core/lib/transport/error_utils.cc', 'src/core/lib/transport/metadata.cc', 'src/core/lib/transport/metadata_batch.cc', 'src/core/lib/transport/pid_controller.cc', 'src/core/lib/transport/static_metadata.cc', 'src/core/lib/transport/status_conversion.cc', 'src/core/lib/transport/status_metadata.cc', 'src/core/lib/transport/timeout_encoding.cc', 'src/core/lib/transport/transport.cc', 'src/core/lib/transport/transport_op_string.cc', 'src/core/lib/uri/uri_parser.cc', 'src/core/plugin_registry/grpc_plugin_registry.cc', 'src/core/tsi/alts/crypt/aes_gcm.cc', 'src/core/tsi/alts/crypt/gsec.cc', 'src/core/tsi/alts/frame_protector/alts_counter.cc', 'src/core/tsi/alts/frame_protector/alts_crypter.cc', 'src/core/tsi/alts/frame_protector/alts_frame_protector.cc', 'src/core/tsi/alts/frame_protector/alts_record_protocol_crypter_common.cc', 'src/core/tsi/alts/frame_protector/alts_seal_privacy_integrity_crypter.cc', 'src/core/tsi/alts/frame_protector/alts_unseal_privacy_integrity_crypter.cc', 'src/core/tsi/alts/frame_protector/frame_handler.cc', 'src/core/tsi/alts/handshaker/alts_handshaker_client.cc', 'src/core/tsi/alts/handshaker/alts_shared_resource.cc', 'src/core/tsi/alts/handshaker/alts_tsi_handshaker.cc', 'src/core/tsi/alts/handshaker/alts_tsi_utils.cc', 'src/core/tsi/alts/handshaker/transport_security_common_api.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_integrity_only_record_protocol.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_privacy_integrity_record_protocol.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_grpc_record_protocol_common.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_iovec_record_protocol.cc', 'src/core/tsi/alts/zero_copy_frame_protector/alts_zero_copy_grpc_protector.cc', 'src/core/tsi/fake_transport_security.cc', 'src/core/tsi/local_transport_security.cc', 'src/core/tsi/ssl/session_cache/ssl_session_boringssl.cc', 'src/core/tsi/ssl/session_cache/ssl_session_cache.cc', 'src/core/tsi/ssl/session_cache/ssl_session_openssl.cc', 'src/core/tsi/ssl_transport_security.cc', 'src/core/tsi/transport_security.cc', 'src/core/tsi/transport_security_grpc.cc', 'third_party/abseil-cpp/absl/base/internal/cycleclock.cc', 'third_party/abseil-cpp/absl/base/internal/exponential_biased.cc', 'third_party/abseil-cpp/absl/base/internal/low_level_alloc.cc', 'third_party/abseil-cpp/absl/base/internal/raw_logging.cc', 'third_party/abseil-cpp/absl/base/internal/spinlock.cc', 'third_party/abseil-cpp/absl/base/internal/spinlock_wait.cc', 'third_party/abseil-cpp/absl/base/internal/sysinfo.cc', 'third_party/abseil-cpp/absl/base/internal/thread_identity.cc', 'third_party/abseil-cpp/absl/base/internal/throw_delegate.cc', 'third_party/abseil-cpp/absl/base/internal/unscaledcycleclock.cc', 'third_party/abseil-cpp/absl/base/log_severity.cc', 'third_party/abseil-cpp/absl/container/internal/hashtablez_sampler.cc', 'third_party/abseil-cpp/absl/container/internal/hashtablez_sampler_force_weak_definition.cc', 'third_party/abseil-cpp/absl/container/internal/raw_hash_set.cc', 'third_party/abseil-cpp/absl/debugging/internal/address_is_readable.cc', 'third_party/abseil-cpp/absl/debugging/internal/demangle.cc', 'third_party/abseil-cpp/absl/debugging/internal/elf_mem_image.cc', 'third_party/abseil-cpp/absl/debugging/internal/vdso_support.cc', 'third_party/abseil-cpp/absl/debugging/stacktrace.cc', 'third_party/abseil-cpp/absl/debugging/symbolize.cc', 'third_party/abseil-cpp/absl/hash/internal/city.cc', 'third_party/abseil-cpp/absl/hash/internal/hash.cc', 'third_party/abseil-cpp/absl/hash/internal/wyhash.cc', 'third_party/abseil-cpp/absl/numeric/int128.cc', 'third_party/abseil-cpp/absl/status/status.cc', 'third_party/abseil-cpp/absl/status/status_payload_printer.cc', 'third_party/abseil-cpp/absl/status/statusor.cc', 'third_party/abseil-cpp/absl/strings/ascii.cc', 'third_party/abseil-cpp/absl/strings/charconv.cc', 'third_party/abseil-cpp/absl/strings/cord.cc', 'third_party/abseil-cpp/absl/strings/escaping.cc', 'third_party/abseil-cpp/absl/strings/internal/charconv_bigint.cc', 'third_party/abseil-cpp/absl/strings/internal/charconv_parse.cc', 'third_party/abseil-cpp/absl/strings/internal/cord_internal.cc', 'third_party/abseil-cpp/absl/strings/internal/cord_rep_ring.cc', 'third_party/abseil-cpp/absl/strings/internal/escaping.cc', 'third_party/abseil-cpp/absl/strings/internal/memutil.cc', 'third_party/abseil-cpp/absl/strings/internal/ostringstream.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/arg.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/bind.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/extension.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/float_conversion.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/output.cc', 'third_party/abseil-cpp/absl/strings/internal/str_format/parser.cc', 'third_party/abseil-cpp/absl/strings/internal/utf8.cc', 'third_party/abseil-cpp/absl/strings/match.cc', 'third_party/abseil-cpp/absl/strings/numbers.cc', 'third_party/abseil-cpp/absl/strings/str_cat.cc', 'third_party/abseil-cpp/absl/strings/str_replace.cc', 'third_party/abseil-cpp/absl/strings/str_split.cc', 'third_party/abseil-cpp/absl/strings/string_view.cc', 'third_party/abseil-cpp/absl/strings/substitute.cc', 'third_party/abseil-cpp/absl/synchronization/barrier.cc', 'third_party/abseil-cpp/absl/synchronization/blocking_counter.cc', 'third_party/abseil-cpp/absl/synchronization/internal/create_thread_identity.cc', 'third_party/abseil-cpp/absl/synchronization/internal/graphcycles.cc', 'third_party/abseil-cpp/absl/synchronization/internal/per_thread_sem.cc', 'third_party/abseil-cpp/absl/synchronization/internal/waiter.cc', 'third_party/abseil-cpp/absl/synchronization/mutex.cc', 'third_party/abseil-cpp/absl/synchronization/notification.cc', 'third_party/abseil-cpp/absl/time/civil_time.cc', 'third_party/abseil-cpp/absl/time/clock.cc', 'third_party/abseil-cpp/absl/time/duration.cc', 'third_party/abseil-cpp/absl/time/format.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/civil_time_detail.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_fixed.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_format.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_if.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_impl.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_info.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_libc.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_lookup.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/time_zone_posix.cc', 'third_party/abseil-cpp/absl/time/internal/cctz/src/zone_info_source.cc', 'third_party/abseil-cpp/absl/time/time.cc', 'third_party/abseil-cpp/absl/types/bad_optional_access.cc', 'third_party/abseil-cpp/absl/types/bad_variant_access.cc', 'third_party/address_sorting/address_sorting.c', 'third_party/address_sorting/address_sorting_posix.c', 'third_party/address_sorting/address_sorting_windows.c', 'third_party/boringssl-with-bazel/err_data.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_bitstr.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_bool.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_d2i_fp.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_dup.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_enum.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_gentm.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_i2d_fp.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_int.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_mbstr.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_object.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_octet.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_print.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_strex.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_strnid.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_time.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_type.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_utctm.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/a_utf8.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/asn1_lib.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/asn1_par.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/asn_pack.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/f_enum.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/f_int.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/f_string.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_dec.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_enc.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_fre.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_new.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_typ.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/tasn_utl.c', 'third_party/boringssl-with-bazel/src/crypto/asn1/time_support.c', 'third_party/boringssl-with-bazel/src/crypto/base64/base64.c', 'third_party/boringssl-with-bazel/src/crypto/bio/bio.c', 'third_party/boringssl-with-bazel/src/crypto/bio/bio_mem.c', 'third_party/boringssl-with-bazel/src/crypto/bio/connect.c', 'third_party/boringssl-with-bazel/src/crypto/bio/fd.c', 'third_party/boringssl-with-bazel/src/crypto/bio/file.c', 'third_party/boringssl-with-bazel/src/crypto/bio/hexdump.c', 'third_party/boringssl-with-bazel/src/crypto/bio/pair.c', 'third_party/boringssl-with-bazel/src/crypto/bio/printf.c', 'third_party/boringssl-with-bazel/src/crypto/bio/socket.c', 'third_party/boringssl-with-bazel/src/crypto/bio/socket_helper.c', 'third_party/boringssl-with-bazel/src/crypto/blake2/blake2.c', 'third_party/boringssl-with-bazel/src/crypto/bn_extra/bn_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/bn_extra/convert.c', 'third_party/boringssl-with-bazel/src/crypto/buf/buf.c', 'third_party/boringssl-with-bazel/src/crypto/bytestring/asn1_compat.c', 'third_party/boringssl-with-bazel/src/crypto/bytestring/ber.c', 'third_party/boringssl-with-bazel/src/crypto/bytestring/cbb.c', 'third_party/boringssl-with-bazel/src/crypto/bytestring/cbs.c', 'third_party/boringssl-with-bazel/src/crypto/bytestring/unicode.c', 'third_party/boringssl-with-bazel/src/crypto/chacha/chacha.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/cipher_extra.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/derive_key.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_aesccm.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_aesctrhmac.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_aesgcmsiv.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_chacha20poly1305.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_null.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_rc2.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_rc4.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/e_tls.c', 'third_party/boringssl-with-bazel/src/crypto/cipher_extra/tls_cbc.c', 'third_party/boringssl-with-bazel/src/crypto/cmac/cmac.c', 'third_party/boringssl-with-bazel/src/crypto/conf/conf.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-aarch64-fuchsia.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-aarch64-linux.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-aarch64-win.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-arm-linux.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-arm.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-intel.c', 'third_party/boringssl-with-bazel/src/crypto/cpu-ppc64le.c', 'third_party/boringssl-with-bazel/src/crypto/crypto.c', 'third_party/boringssl-with-bazel/src/crypto/curve25519/curve25519.c', 'third_party/boringssl-with-bazel/src/crypto/curve25519/spake25519.c', 'third_party/boringssl-with-bazel/src/crypto/dh_extra/dh_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/dh_extra/params.c', 'third_party/boringssl-with-bazel/src/crypto/digest_extra/digest_extra.c', 'third_party/boringssl-with-bazel/src/crypto/dsa/dsa.c', 'third_party/boringssl-with-bazel/src/crypto/dsa/dsa_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/ec_extra/ec_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/ec_extra/ec_derive.c', 'third_party/boringssl-with-bazel/src/crypto/ec_extra/hash_to_curve.c', 'third_party/boringssl-with-bazel/src/crypto/ecdh_extra/ecdh_extra.c', 'third_party/boringssl-with-bazel/src/crypto/ecdsa_extra/ecdsa_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/engine/engine.c', 'third_party/boringssl-with-bazel/src/crypto/err/err.c', 'third_party/boringssl-with-bazel/src/crypto/evp/digestsign.c', 'third_party/boringssl-with-bazel/src/crypto/evp/evp.c', 'third_party/boringssl-with-bazel/src/crypto/evp/evp_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/evp_ctx.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_dsa_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_ec.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_ec_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_ed25519.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_ed25519_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_rsa.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_rsa_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_x25519.c', 'third_party/boringssl-with-bazel/src/crypto/evp/p_x25519_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/evp/pbkdf.c', 'third_party/boringssl-with-bazel/src/crypto/evp/print.c', 'third_party/boringssl-with-bazel/src/crypto/evp/scrypt.c', 'third_party/boringssl-with-bazel/src/crypto/evp/sign.c', 'third_party/boringssl-with-bazel/src/crypto/ex_data.c', 'third_party/boringssl-with-bazel/src/crypto/fipsmodule/bcm.c', 'third_party/boringssl-with-bazel/src/crypto/fipsmodule/fips_shared_support.c', 'third_party/boringssl-with-bazel/src/crypto/hkdf/hkdf.c', 'third_party/boringssl-with-bazel/src/crypto/hpke/hpke.c', 'third_party/boringssl-with-bazel/src/crypto/hrss/hrss.c', 'third_party/boringssl-with-bazel/src/crypto/lhash/lhash.c', 'third_party/boringssl-with-bazel/src/crypto/mem.c', 'third_party/boringssl-with-bazel/src/crypto/obj/obj.c', 'third_party/boringssl-with-bazel/src/crypto/obj/obj_xref.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_all.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_info.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_lib.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_oth.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_pk8.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_pkey.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_x509.c', 'third_party/boringssl-with-bazel/src/crypto/pem/pem_xaux.c', 'third_party/boringssl-with-bazel/src/crypto/pkcs7/pkcs7.c', 'third_party/boringssl-with-bazel/src/crypto/pkcs7/pkcs7_x509.c', 'third_party/boringssl-with-bazel/src/crypto/pkcs8/p5_pbev2.c', 'third_party/boringssl-with-bazel/src/crypto/pkcs8/pkcs8.c', 'third_party/boringssl-with-bazel/src/crypto/pkcs8/pkcs8_x509.c', 'third_party/boringssl-with-bazel/src/crypto/poly1305/poly1305.c', 'third_party/boringssl-with-bazel/src/crypto/poly1305/poly1305_arm.c', 'third_party/boringssl-with-bazel/src/crypto/poly1305/poly1305_vec.c', 'third_party/boringssl-with-bazel/src/crypto/pool/pool.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/deterministic.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/forkunsafe.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/fuchsia.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/passive.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/rand_extra.c', 'third_party/boringssl-with-bazel/src/crypto/rand_extra/windows.c', 'third_party/boringssl-with-bazel/src/crypto/rc4/rc4.c', 'third_party/boringssl-with-bazel/src/crypto/refcount_c11.c', 'third_party/boringssl-with-bazel/src/crypto/refcount_lock.c', 'third_party/boringssl-with-bazel/src/crypto/rsa_extra/rsa_asn1.c', 'third_party/boringssl-with-bazel/src/crypto/rsa_extra/rsa_print.c', 'third_party/boringssl-with-bazel/src/crypto/siphash/siphash.c', 'third_party/boringssl-with-bazel/src/crypto/stack/stack.c', 'third_party/boringssl-with-bazel/src/crypto/thread.c', 'third_party/boringssl-with-bazel/src/crypto/thread_none.c', 'third_party/boringssl-with-bazel/src/crypto/thread_pthread.c', 'third_party/boringssl-with-bazel/src/crypto/thread_win.c', 'third_party/boringssl-with-bazel/src/crypto/trust_token/pmbtoken.c', 'third_party/boringssl-with-bazel/src/crypto/trust_token/trust_token.c', 'third_party/boringssl-with-bazel/src/crypto/trust_token/voprf.c', 'third_party/boringssl-with-bazel/src/crypto/x509/a_digest.c', 'third_party/boringssl-with-bazel/src/crypto/x509/a_sign.c', 'third_party/boringssl-with-bazel/src/crypto/x509/a_verify.c', 'third_party/boringssl-with-bazel/src/crypto/x509/algorithm.c', 'third_party/boringssl-with-bazel/src/crypto/x509/asn1_gen.c', 'third_party/boringssl-with-bazel/src/crypto/x509/by_dir.c', 'third_party/boringssl-with-bazel/src/crypto/x509/by_file.c', 'third_party/boringssl-with-bazel/src/crypto/x509/i2d_pr.c', 'third_party/boringssl-with-bazel/src/crypto/x509/name_print.c', 'third_party/boringssl-with-bazel/src/crypto/x509/rsa_pss.c', 'third_party/boringssl-with-bazel/src/crypto/x509/t_crl.c', 'third_party/boringssl-with-bazel/src/crypto/x509/t_req.c', 'third_party/boringssl-with-bazel/src/crypto/x509/t_x509.c', 'third_party/boringssl-with-bazel/src/crypto/x509/t_x509a.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_att.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_cmp.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_d2.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_def.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_ext.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_lu.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_obj.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_req.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_set.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_trs.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_txt.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_v3.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_vfy.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509_vpm.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509cset.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509name.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509rset.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x509spki.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_algor.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_all.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_attrib.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_crl.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_exten.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_info.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_name.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_pkey.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_pubkey.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_req.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_sig.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_spki.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_val.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_x509.c', 'third_party/boringssl-with-bazel/src/crypto/x509/x_x509a.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_cache.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_data.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_lib.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_map.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_node.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/pcy_tree.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_akey.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_akeya.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_alt.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_bcons.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_bitst.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_conf.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_cpols.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_crld.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_enum.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_extku.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_genn.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_ia5.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_info.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_int.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_lib.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_ncons.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_ocsp.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_pci.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_pcia.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_pcons.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_pmaps.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_prn.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_purp.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_skey.c', 'third_party/boringssl-with-bazel/src/crypto/x509v3/v3_utl.c', 'third_party/boringssl-with-bazel/src/ssl/bio_ssl.cc', 'third_party/boringssl-with-bazel/src/ssl/d1_both.cc', 'third_party/boringssl-with-bazel/src/ssl/d1_lib.cc', 'third_party/boringssl-with-bazel/src/ssl/d1_pkt.cc', 'third_party/boringssl-with-bazel/src/ssl/d1_srtp.cc', 'third_party/boringssl-with-bazel/src/ssl/dtls_method.cc', 'third_party/boringssl-with-bazel/src/ssl/dtls_record.cc', 'third_party/boringssl-with-bazel/src/ssl/encrypted_client_hello.cc', 'third_party/boringssl-with-bazel/src/ssl/extensions.cc', 'third_party/boringssl-with-bazel/src/ssl/handoff.cc', 'third_party/boringssl-with-bazel/src/ssl/handshake.cc', 'third_party/boringssl-with-bazel/src/ssl/handshake_client.cc', 'third_party/boringssl-with-bazel/src/ssl/handshake_server.cc', 'third_party/boringssl-with-bazel/src/ssl/s3_both.cc', 'third_party/boringssl-with-bazel/src/ssl/s3_lib.cc', 'third_party/boringssl-with-bazel/src/ssl/s3_pkt.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_aead_ctx.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_asn1.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_buffer.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_cert.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_cipher.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_file.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_key_share.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_lib.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_privkey.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_session.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_stat.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_transcript.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_versions.cc', 'third_party/boringssl-with-bazel/src/ssl/ssl_x509.cc', 'third_party/boringssl-with-bazel/src/ssl/t1_enc.cc', 'third_party/boringssl-with-bazel/src/ssl/tls13_both.cc', 'third_party/boringssl-with-bazel/src/ssl/tls13_client.cc', 'third_party/boringssl-with-bazel/src/ssl/tls13_enc.cc', 'third_party/boringssl-with-bazel/src/ssl/tls13_server.cc', 'third_party/boringssl-with-bazel/src/ssl/tls_method.cc', 'third_party/boringssl-with-bazel/src/ssl/tls_record.cc', 'third_party/cares/cares/ares__close_sockets.c', 'third_party/cares/cares/ares__get_hostent.c', 'third_party/cares/cares/ares__read_line.c', 'third_party/cares/cares/ares__timeval.c', 'third_party/cares/cares/ares_cancel.c', 'third_party/cares/cares/ares_create_query.c', 'third_party/cares/cares/ares_data.c', 'third_party/cares/cares/ares_destroy.c', 'third_party/cares/cares/ares_expand_name.c', 'third_party/cares/cares/ares_expand_string.c', 'third_party/cares/cares/ares_fds.c', 'third_party/cares/cares/ares_free_hostent.c', 'third_party/cares/cares/ares_free_string.c', 'third_party/cares/cares/ares_getenv.c', 'third_party/cares/cares/ares_gethostbyaddr.c', 'third_party/cares/cares/ares_gethostbyname.c', 'third_party/cares/cares/ares_getnameinfo.c', 'third_party/cares/cares/ares_getopt.c', 'third_party/cares/cares/ares_getsock.c', 'third_party/cares/cares/ares_init.c', 'third_party/cares/cares/ares_library_init.c', 'third_party/cares/cares/ares_llist.c', 'third_party/cares/cares/ares_mkquery.c', 'third_party/cares/cares/ares_nowarn.c', 'third_party/cares/cares/ares_options.c', 'third_party/cares/cares/ares_parse_a_reply.c', 'third_party/cares/cares/ares_parse_aaaa_reply.c', 'third_party/cares/cares/ares_parse_mx_reply.c', 'third_party/cares/cares/ares_parse_naptr_reply.c', 'third_party/cares/cares/ares_parse_ns_reply.c', 'third_party/cares/cares/ares_parse_ptr_reply.c', 'third_party/cares/cares/ares_parse_soa_reply.c', 'third_party/cares/cares/ares_parse_srv_reply.c', 'third_party/cares/cares/ares_parse_txt_reply.c', 'third_party/cares/cares/ares_platform.c', 'third_party/cares/cares/ares_process.c', 'third_party/cares/cares/ares_query.c', 'third_party/cares/cares/ares_search.c', 'third_party/cares/cares/ares_send.c', 'third_party/cares/cares/ares_strcasecmp.c', 'third_party/cares/cares/ares_strdup.c', 'third_party/cares/cares/ares_strerror.c', 'third_party/cares/cares/ares_strsplit.c', 'third_party/cares/cares/ares_timeout.c', 'third_party/cares/cares/ares_version.c', 'third_party/cares/cares/ares_writev.c', 'third_party/cares/cares/bitncmp.c', 'third_party/cares/cares/inet_net_pton.c', 'third_party/cares/cares/inet_ntop.c', 'third_party/cares/cares/windows_port.c', 'third_party/re2/re2/bitstate.cc', 'third_party/re2/re2/compile.cc', 'third_party/re2/re2/dfa.cc', 'third_party/re2/re2/filtered_re2.cc', 'third_party/re2/re2/mimics_pcre.cc', 'third_party/re2/re2/nfa.cc', 'third_party/re2/re2/onepass.cc', 'third_party/re2/re2/parse.cc', 'third_party/re2/re2/perl_groups.cc', 'third_party/re2/re2/prefilter.cc', 'third_party/re2/re2/prefilter_tree.cc', 'third_party/re2/re2/prog.cc', 'third_party/re2/re2/re2.cc', 'third_party/re2/re2/regexp.cc', 'third_party/re2/re2/set.cc', 'third_party/re2/re2/simplify.cc', 'third_party/re2/re2/stringpiece.cc', 'third_party/re2/re2/tostring.cc', 'third_party/re2/re2/unicode_casefold.cc', 'third_party/re2/re2/unicode_groups.cc', 'third_party/re2/util/pcre.cc', 'third_party/re2/util/rune.cc', 'third_party/re2/util/strutil.cc', 'third_party/upb/upb/decode.c', 'third_party/upb/upb/decode_fast.c', 'third_party/upb/upb/def.c', 'third_party/upb/upb/encode.c', 'third_party/upb/upb/msg.c', 'third_party/upb/upb/reflection.c', 'third_party/upb/upb/table.c', 'third_party/upb/upb/text_encode.c', 'third_party/upb/upb/upb.c', 'third_party/zlib/adler32.c', 'third_party/zlib/compress.c', 'third_party/zlib/crc32.c', 'third_party/zlib/deflate.c', 'third_party/zlib/gzclose.c', 'third_party/zlib/gzlib.c', 'third_party/zlib/gzread.c', 'third_party/zlib/gzwrite.c', 'third_party/zlib/infback.c', 'third_party/zlib/inffast.c', 'third_party/zlib/inflate.c', 'third_party/zlib/inftrees.c', 'third_party/zlib/trees.c', 'third_party/zlib/uncompr.c', 'third_party/zlib/zutil.c', ] ASM_SOURCE_FILES = { 'crypto_ios_aarch64': [ 'third_party/boringssl-with-bazel/ios-aarch64/crypto/chacha/chacha-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/aesv8-armx64.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/armv8-mont.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/ghash-neon-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/ghashv8-armx64.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/sha1-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/sha256-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/sha512-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/fipsmodule/vpaes-armv8.S', 'third_party/boringssl-with-bazel/ios-aarch64/crypto/test/trampoline-armv8.S', ], 'crypto_ios_arm': [ 'third_party/boringssl-with-bazel/ios-arm/crypto/chacha/chacha-armv4.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/aesv8-armx32.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/armv4-mont.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/bsaes-armv7.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/ghash-armv4.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/ghashv8-armx32.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/sha1-armv4-large.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/sha256-armv4.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/sha512-armv4.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/fipsmodule/vpaes-armv7.S', 'third_party/boringssl-with-bazel/ios-arm/crypto/test/trampoline-armv4.S', ], 'crypto_linux_aarch64': [ 'third_party/boringssl-with-bazel/linux-aarch64/crypto/chacha/chacha-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/aesv8-armx64.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/armv8-mont.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/ghash-neon-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/ghashv8-armx64.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/sha1-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/sha256-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/sha512-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/fipsmodule/vpaes-armv8.S', 'third_party/boringssl-with-bazel/linux-aarch64/crypto/test/trampoline-armv8.S', ], 'crypto_linux_arm': [ 'third_party/boringssl-with-bazel/linux-arm/crypto/chacha/chacha-armv4.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/aesv8-armx32.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/armv4-mont.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/bsaes-armv7.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/ghash-armv4.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/ghashv8-armx32.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/sha1-armv4-large.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/sha256-armv4.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/sha512-armv4.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/fipsmodule/vpaes-armv7.S', 'third_party/boringssl-with-bazel/linux-arm/crypto/test/trampoline-armv4.S', 'third_party/boringssl-with-bazel/src/crypto/curve25519/asm/x25519-asm-arm.S', 'third_party/boringssl-with-bazel/src/crypto/poly1305/poly1305_arm_asm.S', ], 'crypto_linux_ppc64le': [ 'third_party/boringssl-with-bazel/linux-ppc64le/crypto/fipsmodule/aesp8-ppc.S', 'third_party/boringssl-with-bazel/linux-ppc64le/crypto/fipsmodule/ghashp8-ppc.S', 'third_party/boringssl-with-bazel/linux-ppc64le/crypto/test/trampoline-ppc.S', ], 'crypto_linux_x86': [ 'third_party/boringssl-with-bazel/linux-x86/crypto/chacha/chacha-x86.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/aesni-x86.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/bn-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/co-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/ghash-ssse3-x86.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/ghash-x86.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/md5-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/sha1-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/sha256-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/sha512-586.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/vpaes-x86.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/fipsmodule/x86-mont.S', 'third_party/boringssl-with-bazel/linux-x86/crypto/test/trampoline-x86.S', ], 'crypto_linux_x86_64': [ 'third_party/boringssl-with-bazel/linux-x86_64/crypto/chacha/chacha-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/aesni-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/ghash-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/md5-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/p256-x86_64-asm.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/rdrand-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/rsaz-avx2.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/sha1-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/sha256-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/sha512-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/vpaes-x86_64.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/x86_64-mont.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/fipsmodule/x86_64-mont5.S', 'third_party/boringssl-with-bazel/linux-x86_64/crypto/test/trampoline-x86_64.S', 'third_party/boringssl-with-bazel/src/crypto/hrss/asm/poly_rq_mul.S', ], 'crypto_mac_x86': [ 'third_party/boringssl-with-bazel/mac-x86/crypto/chacha/chacha-x86.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/aesni-x86.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/bn-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/co-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/ghash-ssse3-x86.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/ghash-x86.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/md5-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/sha1-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/sha256-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/sha512-586.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/vpaes-x86.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/fipsmodule/x86-mont.S', 'third_party/boringssl-with-bazel/mac-x86/crypto/test/trampoline-x86.S', ], 'crypto_mac_x86_64': [ 'third_party/boringssl-with-bazel/mac-x86_64/crypto/chacha/chacha-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/aesni-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/ghash-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/md5-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/p256-x86_64-asm.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/rdrand-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/rsaz-avx2.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/sha1-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/sha256-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/sha512-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/vpaes-x86_64.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/x86_64-mont.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/fipsmodule/x86_64-mont5.S', 'third_party/boringssl-with-bazel/mac-x86_64/crypto/test/trampoline-x86_64.S', ], 'crypto_win_aarch64': [ 'third_party/boringssl-with-bazel/win-aarch64/crypto/chacha/chacha-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/aesv8-armx64.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/armv8-mont.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/ghash-neon-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/ghashv8-armx64.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/sha1-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/sha256-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/sha512-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/fipsmodule/vpaes-armv8.S', 'third_party/boringssl-with-bazel/win-aarch64/crypto/test/trampoline-armv8.S', ], 'crypto_win_x86': [ 'third_party/boringssl-with-bazel/win-x86/crypto/chacha/chacha-x86.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/aesni-x86.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/bn-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/co-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/ghash-ssse3-x86.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/ghash-x86.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/md5-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/sha1-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/sha256-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/sha512-586.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/vpaes-x86.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/fipsmodule/x86-mont.asm', 'third_party/boringssl-with-bazel/win-x86/crypto/test/trampoline-x86.asm', ], 'crypto_win_x86_64': [ 'third_party/boringssl-with-bazel/win-x86_64/crypto/chacha/chacha-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/cipher_extra/aes128gcmsiv-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/cipher_extra/chacha20_poly1305_x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/aesni-gcm-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/aesni-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/ghash-ssse3-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/ghash-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/md5-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/p256-x86_64-asm.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/p256_beeu-x86_64-asm.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/rdrand-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/rsaz-avx2.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/sha1-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/sha256-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/sha512-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/vpaes-x86_64.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/x86_64-mont.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/fipsmodule/x86_64-mont5.asm', 'third_party/boringssl-with-bazel/win-x86_64/crypto/test/trampoline-x86_64.asm', ], }
import pytest from rubrix.server.security.auth_provider.local.users.dao import create_users_dao from rubrix.server.security.auth_provider.local.users.service import UsersService usersService = UsersService.get_instance(users=create_users_dao()) def test_authenticate_user(): user = usersService.authenticate_user(username="rubrix", password="1234") assert user.username == "rubrix" def test_get_user(): user = usersService.get_user(username="rubrix") assert user.username == "rubrix" @pytest.mark.asyncio async def test_find_user_by_api_key(): user = await usersService.find_user_by_api_key(api_key="rubrix.apikey") assert user.username == "rubrix"
import React from 'react'; import PropTypes from 'prop-types'; import { withStyles } from 'material-ui/styles'; import ExpansionPanel, { ExpansionPanelDetails, ExpansionPanelSummary, } from 'material-ui/ExpansionPanel'; import Typography from 'material-ui/Typography'; import ExpandMoreIcon from 'material-ui-icons/ExpandMore'; const styles = theme => ({ root: { flexGrow: 1, }, heading: { fontSize: theme.typography.pxToRem(15), flexBasis: '33.33%', flexShrink: 0, }, secondaryHeading: { fontSize: theme.typography.pxToRem(15), color: theme.palette.text.secondary, }, }); class ControlledExpansionPanels extends React.Component { state = { expanded: null, }; handleChange = panel => (event, expanded) => { this.setState({ expanded: expanded ? panel : false, }); }; render() { const { classes } = this.props; const { expanded } = this.state; return ( <div className={classes.root}> <ExpansionPanel expanded={expanded === 'panel1'} onChange={this.handleChange('panel1')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>General settings</Typography> <Typography className={classes.secondaryHeading}>I am an expansion panel</Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nulla facilisi. Phasellus sollicitudin nulla et quam mattis feugiat. Aliquam eget maximus est, id dignissim quam. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel2'} onChange={this.handleChange('panel2')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Users</Typography> <Typography className={classes.secondaryHeading}> You are currently not an owner </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Donec placerat, lectus sed mattis semper, neque lectus feugiat lectus, varius pulvinar diam eros in elit. Pellentesque convallis laoreet laoreet. </Typography> </ExpansionPanelDetails> </ExpansionPanel> <ExpansionPanel expanded={expanded === 'panel3'} onChange={this.handleChange('panel3')}> <ExpansionPanelSummary expandIcon={<ExpandMoreIcon />}> <Typography className={classes.heading}>Advanced settings</Typography> <Typography className={classes.secondaryHeading}> Filtering has been entirely disabled for whole web server </Typography> </ExpansionPanelSummary> <ExpansionPanelDetails> <Typography> Nunc vitae orci ultricies, auctor nunc in, volutpat nisl. Integer sit amet egestas eros, vitae egestas augue. Duis vel est augue. </Typography> </ExpansionPanelDetails> </ExpansionPanel> </div> ); } } ControlledExpansionPanels.propTypes = { classes: PropTypes.object.isRequired, }; export default withStyles(styles)(ControlledExpansionPanels);
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow */ import EventEmitter from '../events'; import throttle from 'lodash.throttle'; import { SESSION_STORAGE_LAST_SELECTION_KEY, SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, __DEBUG__, } from '../constants'; import { sessionStorageGetItem, sessionStorageRemoveItem, sessionStorageSetItem, } from 'react-devtools-shared/src/storage'; import setupHighlighter from './views/Highlighter'; import { initialize as setupTraceUpdates, toggleEnabled as setTraceUpdatesEnabled, } from './views/TraceUpdates'; import {patch as patchConsole, unpatch as unpatchConsole} from './console'; import type {BackendBridge} from 'react-devtools-shared/src/bridge'; import type { InstanceAndStyle, NativeType, OwnersList, PathFrame, PathMatch, RendererID, RendererInterface, } from './types'; import type {ComponentFilter} from '../types'; const debug = (methodName, ...args) => { if (__DEBUG__) { console.log( `%cAgent %c${methodName}`, 'color: purple; font-weight: bold;', 'font-weight: bold;', ...args, ); } }; type ElementAndRendererID = {| id: number, rendererID: number, |}; type StoreAsGlobalParams = {| count: number, id: number, path: Array<string | number>, rendererID: number, |}; type CopyElementParams = {| id: number, path: Array<string | number>, rendererID: number, |}; type InspectElementParams = {| id: number, path?: Array<string | number>, rendererID: number, |}; type OverrideHookParams = {| id: number, hookID: number, path: Array<string | number>, rendererID: number, value: any, |}; type SetInParams = {| id: number, path: Array<string | number>, rendererID: number, value: any, |}; type OverrideSuspenseParams = {| id: number, rendererID: number, forceFallback: boolean, |}; type PersistedSelection = {| rendererID: number, path: Array<PathFrame>, |}; export default class Agent extends EventEmitter<{| hideNativeHighlight: [], showNativeHighlight: [NativeType], shutdown: [], traceUpdates: [Set<NativeType>], |}> { _bridge: BackendBridge; _isProfiling: boolean = false; _recordChangeDescriptions: boolean = false; _rendererInterfaces: {[key: RendererID]: RendererInterface, ...} = {}; _persistedSelection: PersistedSelection | null = null; _persistedSelectionMatch: PathMatch | null = null; _traceUpdatesEnabled: boolean = false; constructor(bridge: BackendBridge) { super(); if ( sessionStorageGetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY) === 'true' ) { this._recordChangeDescriptions = sessionStorageGetItem( SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, ) === 'true'; this._isProfiling = true; sessionStorageRemoveItem(SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY); sessionStorageRemoveItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY); } const persistedSelectionString = sessionStorageGetItem( SESSION_STORAGE_LAST_SELECTION_KEY, ); if (persistedSelectionString != null) { this._persistedSelection = JSON.parse(persistedSelectionString); } this._bridge = bridge; bridge.addListener('copyElementPath', this.copyElementPath); bridge.addListener('getProfilingData', this.getProfilingData); bridge.addListener('getProfilingStatus', this.getProfilingStatus); bridge.addListener('getOwnersList', this.getOwnersList); bridge.addListener('inspectElement', this.inspectElement); bridge.addListener('logElementToConsole', this.logElementToConsole); bridge.addListener('overrideContext', this.overrideContext); bridge.addListener('overrideHookState', this.overrideHookState); bridge.addListener('overrideProps', this.overrideProps); bridge.addListener('overrideState', this.overrideState); bridge.addListener('overrideSuspense', this.overrideSuspense); bridge.addListener('reloadAndProfile', this.reloadAndProfile); bridge.addListener('setTraceUpdatesEnabled', this.setTraceUpdatesEnabled); bridge.addListener('startProfiling', this.startProfiling); bridge.addListener('stopProfiling', this.stopProfiling); bridge.addListener('storeAsGlobal', this.storeAsGlobal); bridge.addListener( 'syncSelectionFromNativeElementsPanel', this.syncSelectionFromNativeElementsPanel, ); bridge.addListener('shutdown', this.shutdown); bridge.addListener( 'updateAppendComponentStack', this.updateAppendComponentStack, ); bridge.addListener('updateComponentFilters', this.updateComponentFilters); bridge.addListener('viewAttributeSource', this.viewAttributeSource); bridge.addListener('viewElementSource', this.viewElementSource); if (this._isProfiling) { bridge.send('profilingStatus', true); } // Notify the frontend if the backend supports the Storage API (e.g. localStorage). // If not, features like reload-and-profile will not work correctly and must be disabled. let isBackendStorageAPISupported = false; try { localStorage.getItem('test'); isBackendStorageAPISupported = true; } catch (error) {} bridge.send('isBackendStorageAPISupported', isBackendStorageAPISupported); setupHighlighter(bridge, this); setupTraceUpdates(this); } get rendererInterfaces(): {[key: RendererID]: RendererInterface, ...} { return this._rendererInterfaces; } copyElementPath = ({id, path, rendererID}: CopyElementParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.copyElementPath(id, path); } }; getInstanceAndStyle({ id, rendererID, }: ElementAndRendererID): InstanceAndStyle | null { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); return null; } return renderer.getInstanceAndStyle(id); } getIDForNode(node: Object): number | null { for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); try { const id = renderer.getFiberIDForNative(node, true); if (id !== null) { return id; } } catch (error) { // Some old React versions might throw if they can't find a match. // If so we should ignore it... } } return null; } getProfilingData = ({rendererID}: {|rendererID: RendererID|}) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } this._bridge.send('profilingData', renderer.getProfilingData()); }; getProfilingStatus = () => { this._bridge.send('profilingStatus', this._isProfiling); }; getOwnersList = ({id, rendererID}: ElementAndRendererID) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { const owners = renderer.getOwnersList(id); this._bridge.send('ownersList', ({id, owners}: OwnersList)); } }; inspectElement = ({id, path, rendererID}: InspectElementParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { this._bridge.send('inspectedElement', renderer.inspectElement(id, path)); // When user selects an element, stop trying to restore the selection, // and instead remember the current selection for the next reload. if ( this._persistedSelectionMatch === null || this._persistedSelectionMatch.id !== id ) { this._persistedSelection = null; this._persistedSelectionMatch = null; renderer.setTrackedPath(null); this._throttledPersistSelection(rendererID, id); } // TODO: If there was a way to change the selected DOM element // in native Elements tab without forcing a switch to it, we'd do it here. // For now, it doesn't seem like there is a way to do that: // https://github.com/bvaughn/react-devtools-experimental/issues/102 // (Setting $0 doesn't work, and calling inspect() switches the tab.) } }; logElementToConsole = ({id, rendererID}: ElementAndRendererID) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.logElementToConsole(id); } }; reloadAndProfile = (recordChangeDescriptions: boolean) => { sessionStorageSetItem(SESSION_STORAGE_RELOAD_AND_PROFILE_KEY, 'true'); sessionStorageSetItem( SESSION_STORAGE_RECORD_CHANGE_DESCRIPTIONS_KEY, recordChangeDescriptions ? 'true' : 'false', ); // This code path should only be hit if the shell has explicitly told the Store that it supports profiling. // In that case, the shell must also listen for this specific message to know when it needs to reload the app. // The agent can't do this in a way that is renderer agnostic. this._bridge.send('reloadAppForProfiling'); }; overrideContext = ({id, path, rendererID, value}: SetInParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.setInContext(id, path, value); } }; overrideHookState = ({ id, hookID, path, rendererID, value, }: OverrideHookParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.setInHook(id, hookID, path, value); } }; overrideProps = ({id, path, rendererID, value}: SetInParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.setInProps(id, path, value); } }; overrideState = ({id, path, rendererID, value}: SetInParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.setInState(id, path, value); } }; overrideSuspense = ({ id, rendererID, forceFallback, }: OverrideSuspenseParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.overrideSuspense(id, forceFallback); } }; selectNode(target: Object): void { const id = this.getIDForNode(target); if (id !== null) { this._bridge.send('selectFiber', id); } } setRendererInterface( rendererID: RendererID, rendererInterface: RendererInterface, ) { this._rendererInterfaces[rendererID] = rendererInterface; if (this._isProfiling) { rendererInterface.startProfiling(this._recordChangeDescriptions); } rendererInterface.setTraceUpdatesEnabled(this._traceUpdatesEnabled); // When the renderer is attached, we need to tell it whether // we remember the previous selection that we'd like to restore. // It'll start tracking mounts for matches to the last selection path. const selection = this._persistedSelection; if (selection !== null && selection.rendererID === rendererID) { rendererInterface.setTrackedPath(selection.path); } } setTraceUpdatesEnabled = (traceUpdatesEnabled: boolean) => { this._traceUpdatesEnabled = traceUpdatesEnabled; setTraceUpdatesEnabled(traceUpdatesEnabled); for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.setTraceUpdatesEnabled(traceUpdatesEnabled); } }; syncSelectionFromNativeElementsPanel = () => { const target = window.__REACT_DEVTOOLS_GLOBAL_HOOK__.$0; if (target == null) { return; } this.selectNode(target); }; shutdown = () => { // Clean up the overlay if visible, and associated events. this.emit('shutdown'); }; startProfiling = (recordChangeDescriptions: boolean) => { this._recordChangeDescriptions = recordChangeDescriptions; this._isProfiling = true; for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.startProfiling(recordChangeDescriptions); } this._bridge.send('profilingStatus', this._isProfiling); }; stopProfiling = () => { this._isProfiling = false; this._recordChangeDescriptions = false; for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.stopProfiling(); } this._bridge.send('profilingStatus', this._isProfiling); }; storeAsGlobal = ({count, id, path, rendererID}: StoreAsGlobalParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.storeAsGlobal(id, path, count); } }; updateAppendComponentStack = (appendComponentStack: boolean) => { // If the frontend preference has change, // or in the case of React Native- if the backend is just finding out the preference- // then install or uninstall the console overrides. // It's safe to call these methods multiple times, so we don't need to worry about that. if (appendComponentStack) { patchConsole(); } else { unpatchConsole(); } }; updateComponentFilters = (componentFilters: Array<ComponentFilter>) => { for (const rendererID in this._rendererInterfaces) { const renderer = ((this._rendererInterfaces[ (rendererID: any) ]: any): RendererInterface); renderer.updateComponentFilters(componentFilters); } }; viewAttributeSource = ({id, path, rendererID}: CopyElementParams) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.prepareViewAttributeSource(id, path); } }; viewElementSource = ({id, rendererID}: ElementAndRendererID) => { const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}" for element "${id}"`); } else { renderer.prepareViewElementSource(id); } }; onTraceUpdates = (nodes: Set<NativeType>) => { this.emit('traceUpdates', nodes); }; onHookOperations = (operations: Array<number>) => { if (__DEBUG__) { debug('onHookOperations', operations); } // TODO: // The chrome.runtime does not currently support transferables; it forces JSON serialization. // See bug https://bugs.chromium.org/p/chromium/issues/detail?id=927134 // // Regarding transferables, the postMessage doc states: // If the ownership of an object is transferred, it becomes unusable (neutered) // in the context it was sent from and becomes available only to the worker it was sent to. // // Even though Chrome is eventually JSON serializing the array buffer, // using the transferable approach also sometimes causes it to throw: // DOMException: Failed to execute 'postMessage' on 'Window': ArrayBuffer at index 0 is already neutered. // // See bug https://github.com/bvaughn/react-devtools-experimental/issues/25 // // The Store has a fallback in place that parses the message as JSON if the type isn't an array. // For now the simplest fix seems to be to not transfer the array. // This will negatively impact performance on Firefox so it's unfortunate, // but until we're able to fix the Chrome error mentioned above, it seems necessary. // // this._bridge.send('operations', operations, [operations.buffer]); this._bridge.send('operations', operations); if (this._persistedSelection !== null) { const rendererID = operations[0]; if (this._persistedSelection.rendererID === rendererID) { // Check if we can select a deeper match for the persisted selection. const renderer = this._rendererInterfaces[rendererID]; if (renderer == null) { console.warn(`Invalid renderer id "${rendererID}"`); } else { const prevMatch = this._persistedSelectionMatch; const nextMatch = renderer.getBestMatchForTrackedPath(); this._persistedSelectionMatch = nextMatch; const prevMatchID = prevMatch !== null ? prevMatch.id : null; const nextMatchID = nextMatch !== null ? nextMatch.id : null; if (prevMatchID !== nextMatchID) { if (nextMatchID !== null) { // We moved forward, unlocking a deeper node. this._bridge.send('selectFiber', nextMatchID); } } if (nextMatch !== null && nextMatch.isFullMatch) { // We've just unlocked the innermost selected node. // There's no point tracking it further. this._persistedSelection = null; this._persistedSelectionMatch = null; renderer.setTrackedPath(null); } } } } }; onUnsupportedRenderer(rendererID: number) { this._bridge.send('unsupportedRendererVersion', rendererID); } _throttledPersistSelection = throttle((rendererID: number, id: number) => { // This is throttled, so both renderer and selected ID // might not be available by the time we read them. // This is why we need the defensive checks here. const renderer = this._rendererInterfaces[rendererID]; const path = renderer != null ? renderer.getPathForElement(id) : null; if (path !== null) { sessionStorageSetItem( SESSION_STORAGE_LAST_SELECTION_KEY, JSON.stringify(({rendererID, path}: PersistedSelection)), ); } else { sessionStorageRemoveItem(SESSION_STORAGE_LAST_SELECTION_KEY); } }, 1000); }
//$(function(){ // $(document).on('click','.m-numinput',function(){ // var $this = $(this); // var value = $(this).find('input').val() >>> 0; // var min = $(this).find('input').attr('min') >>> 0; // var max = $(this).find('input').attr('max') >>> 0; // // if($(event.target).hasClass('dec')){ // value = value - 1; // if(min && value<min){ // value = min; // } // } // if($(event.target).hasClass('add')){ // value = value + 1; // if(max && value>max){ // value = max; // } // } // $(this).find('input').val(value).trigger('input'); // }); //});
export const fetchTours = () => { // debugger return (dispatch) => { fetch("http://localhost:3000/tours") .then(response => response.json()) .then(tours => { dispatch({ type: 'FETCH_TOURS_SUCCESS', tours }) }) } } export function fetchToursSuccess(tours) { debugger return {type: 'FETCH_TOURS_SUCCESS', tours}; } export const createTour = (tour, history) => { debugger return (dispatch) => { dispatch({type: "ADD_TOUR"}) fetch ("http://localhost:3000/tours", { method: "POST", body: JSON.stringify(tour), headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } }) .then(res => res.json()) .then(tour => { dispatch(createTourSuccess(tour)) history.push(`/tours/${tour.id}`) }) return tour } } export function createTourSuccess(tour) { debugger return {type: 'CREATE_TOUR_SUCCESS', tour} } export const deleteTour = (tour, history) => { debugger return (dispatch) => { return fetch(`http://localhost:3000/tours/${tour.id}`, { method: 'DELETE' }) .then(res => res.json()) .then(tour => { history.push(`/tours`) dispatch(deleteTourSuccess(tour)) }) } } export function deleteTourSuccess(tour) { debugger return {type: 'DELETE_TOUR_SUCCESS', tour} } export const editTour = (tour, history) => { debugger return (dispatch) => { dispatch({type: "EDIT_TOUR"}) debugger fetch(`http://localhost:3000/tours/${tour.id}`, { headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, method: 'PATCH', body: JSON.stringify({tour: tour}) }) .then(response => response.json()) .then(tour => { dispatch({ type: 'UPDATE_TOUR', tour }) }) } } export const fetchTour = (id) => { debugger return (dispatch) => { dispatch({ type: 'LOADING_TOURS'}) fetch(`http://localhost:3000/tours/${id}`) .then(response => response.json()) .then(responseJSON => { debugger dispatch({ type: 'SHOW_TOUR', tour: responseJSON }) }) } } export const updateTour = (id) => { return (dispatch) => { debugger } }
import re import sys from pathlib import Path from typing import Set def read_reqs(reqs_path: Path) -> Set[str]: return { r for r in re.findall( r"(^[^#\n-][\w\[,\]]+[-~>=<.\w]*)", reqs_path.read_text(), re.MULTILINE, ) if isinstance(r, str) } CURRENT_DIR = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent NAME = "simcore-service-library" VERSION = "1.1.0" AUTHORS = "Pedro Crespo-Valero (pcrespov)" DESCRIPTION = "Core service library for simcore (or servicelib)" # WEAK requirements (see requirements/python-dependencies.md) PROD_REQUIREMENTS = read_reqs(CURRENT_DIR / "requirements" / "_base.in") AIOHTTP_REQUIREMENTS = read_reqs(CURRENT_DIR / "requirements" / "_aiohttp.in") FASTAPI_REQUIREMENTS = read_reqs(CURRENT_DIR / "requirements" / "_fastapi.in") # STRONG requirements (see requirements/python-dependencies.md) TEST_REQUIREMENTS = read_reqs(CURRENT_DIR / "requirements" / "_test.txt") if __name__ == "__main__": from setuptools import find_packages, setup setup( name=NAME, version=VERSION, author=AUTHORS, description=DESCRIPTION, license="MIT license", python_requires="~=3.8", install_requires=tuple(PROD_REQUIREMENTS), packages=find_packages(where="src"), package_dir={"": "src"}, test_suite="tests", tests_require=tuple(TEST_REQUIREMENTS), extras_require={ "test": tuple(TEST_REQUIREMENTS), "aiohttp": tuple(AIOHTTP_REQUIREMENTS), "fastapi": tuple(FASTAPI_REQUIREMENTS), "all": tuple(AIOHTTP_REQUIREMENTS | FASTAPI_REQUIREMENTS), }, )
""" This file offers the methods to automatically retrieve the graph Hydrocarboniphaga daqingensis. The graph is automatically retrieved from the STRING repository. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ from typing import Dict from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph from ...ensmallen import Graph # pylint: disable=import-error def HydrocarboniphagaDaqingensis( directed: bool = False, preprocess: bool = True, load_nodes: bool = True, verbose: int = 2, cache: bool = True, cache_path: str = "graphs/string", version: str = "links.v11.5", **additional_graph_kwargs: Dict ) -> Graph: """Return new instance of the Hydrocarboniphaga daqingensis graph. The graph is automatically retrieved from the STRING repository. Parameters ------------------- directed: bool = False Wether to load the graph as directed or undirected. By default false. preprocess: bool = True Whether to preprocess the graph to be loaded in optimal time and memory. load_nodes: bool = True, Whether to load the nodes vocabulary or treat the nodes simply as a numeric range. verbose: int = 2, Wether to show loading bars during the retrieval and building of the graph. cache: bool = True Whether to use cache, i.e. download files only once and preprocess them only once. cache_path: str = "graphs" Where to store the downloaded graphs. version: str = "links.v11.5" The version of the graph to retrieve. The available versions are: - homology.v11.5 - physical.links.v11.5 - links.v11.5 additional_graph_kwargs: Dict Additional graph kwargs. Returns ----------------------- Instace of Hydrocarboniphaga daqingensis graph. References --------------------- Please cite the following if you use the data: ```bib @article{szklarczyk2019string, title={STRING v11: protein--protein association networks with increased coverage, supporting functional discovery in genome-wide experimental datasets}, author={Szklarczyk, Damian and Gable, Annika L and Lyon, David and Junge, Alexander and Wyder, Stefan and Huerta-Cepas, Jaime and Simonovic, Milan and Doncheva, Nadezhda T and Morris, John H and Bork, Peer and others}, journal={Nucleic acids research}, volume={47}, number={D1}, pages={D607--D613}, year={2019}, publisher={Oxford University Press} } ``` """ return AutomaticallyRetrievedGraph( graph_name="HydrocarboniphagaDaqingensis", repository="string", version=version, directed=directed, preprocess=preprocess, load_nodes=load_nodes, verbose=verbose, cache=cache, cache_path=cache_path, additional_graph_kwargs=additional_graph_kwargs )()
import { DesktopTooltipStrategy } from 'ui/scheduler/tooltip_strategies/desktopTooltipStrategy'; import { FunctionTemplate } from 'core/templates/function_template'; import { extend } from 'core/utils/extend'; import Tooltip from 'ui/tooltip'; import List from 'ui/list/ui.list.edit'; import Button from 'ui/button'; import support from 'core/utils/support'; const stubComponent = { option: sinon.stub().returns('stubOption'), focus: sinon.stub(), }; const stubCreateComponent = sinon.stub().returns(stubComponent); const stubShowAppointmentPopup = sinon.stub(); const stubAddDefaultTemplates = sinon.stub(); const stubGetAppointmentTemplate = sinon.stub().returns('template'); const stubCheckAndDeleteAppointment = sinon.stub(); const stubGetTextAndFormatDate = sinon.stub().returns('text'); const stubIsAppointmentInAllDayPanel = sinon.stub().returns(true); const stubGetSingleAppointmentData = sinon.stub().returns('currentData'); const environment = { createSimpleTooltip: function(tooltipOptions) { return new DesktopTooltipStrategy(tooltipOptions); }, tooltipOptions: { createComponent: stubCreateComponent, container: '<div>', addDefaultTemplates: stubAddDefaultTemplates, getAppointmentTemplate: stubGetAppointmentTemplate, showAppointmentPopup: stubShowAppointmentPopup, getTextAndFormatDate: stubGetTextAndFormatDate, checkAndDeleteAppointment: stubCheckAndDeleteAppointment, isAppointmentInAllDayPanel: stubIsAppointmentInAllDayPanel, getSingleAppointmentData: stubGetSingleAppointmentData }, extraOptions: { rtlEnabled: true, focusStateEnabled: true, editing: true, offset: 'offset', isButtonClick: false, }, afterEach: function() { stubCreateComponent.reset(); stubComponent.option.reset(); stubShowAppointmentPopup.reset(); stubAddDefaultTemplates.reset(); stubGetAppointmentTemplate.reset(); stubGetTextAndFormatDate.reset(); stubCheckAndDeleteAppointment.reset(); stubGetSingleAppointmentData.reset(); } }; QUnit.module('Tooltip', environment); QUnit.test('Show tooltip', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); assert.ok(tooltip, 'tooltip is created'); assert.equal(stubComponent.option.callCount, 2); assert.deepEqual(stubComponent.option.getCall(0).args, ['visible', true], 'tooltip is visible'); assert.deepEqual(stubComponent.option.getCall(1).args, ['position', { 'at': 'top', 'collision': 'fit flipfit', 'my': 'bottom', boundary: '<div>', offset: 'offset', }], 'tooltip has correct position'); assert.ok(stubCreateComponent.calledOnce); }); QUnit.test('Shouldn\'t show tooltip if data is not array', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = 12; tooltip.show('target', dataList, this.extraOptions); assert.ok(!stubCreateComponent.called); }); QUnit.test('createComponent should be called with correct options', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); assert.equal(stubCreateComponent.getCall(0).args[0][0].className, 'dx-scheduler-appointment-tooltip-wrapper'); assert.deepEqual(stubCreateComponent.getCall(0).args[1], Tooltip); assert.equal(Object.keys(stubCreateComponent.getCall(0).args[2]).length, 7); assert.equal(stubCreateComponent.getCall(0).args[2].target, 'target'); assert.equal(stubCreateComponent.getCall(0).args[2].maxHeight, 200); assert.equal(stubCreateComponent.getCall(0).args[2].rtlEnabled, true); assert.ok(stubCreateComponent.getCall(0).args[2].onShowing); assert.ok(stubCreateComponent.getCall(0).args[2].onShown); assert.ok(stubCreateComponent.getCall(0).args[2].contentTemplate); assert.ok(stubCreateComponent.getCall(0).args[2].closeOnTargetScroll); }); QUnit.test('onShowing and closeOnTargetScroll options passed to createComponent should work correct', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); const done = assert.async(); stubCreateComponent.getCall(0).args[2].onShowing(); assert.equal(stubCreateComponent.getCall(0).args[2].closeOnTargetScroll(), true); assert.timeout(1000); setTimeout(function() { assert.equal(stubCreateComponent.getCall(0).args[2].closeOnTargetScroll(), false); done(); }); }); QUnit.test('contentTemplate passed to createComponent should work correct', function(assert) { const _touch = support.touch; try { support.touch = false; const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); assert.equal(stubCreateComponent.getCall(1).args[0][0].nodeName, 'DIV'); assert.equal(stubCreateComponent.getCall(1).args[1], List); assert.equal(Object.keys(stubCreateComponent.getCall(1).args[2]).length, 5); assert.equal(stubCreateComponent.getCall(1).args[2].dataSource, dataList); assert.equal(stubCreateComponent.getCall(1).args[2].showScrollbar, 'onHover'); assert.ok(stubCreateComponent.getCall(1).args[2].onContentReady); assert.ok(stubCreateComponent.getCall(1).args[2].onItemClick); assert.ok(stubCreateComponent.getCall(1).args[2].itemTemplate); } finally { support.touch = _touch; } }); QUnit.test('Tooltip should update the content after call method "show" several times', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubComponent.option.reset(); tooltip.show('target', ['updatedData1', 'updatedData2'], this.extraOptions); assert.equal(stubComponent.option.callCount, 5); assert.deepEqual(stubComponent.option.getCall(0).args, ['visible', false]); assert.deepEqual(stubComponent.option.getCall(1).args, ['target', 'target']); assert.deepEqual(stubComponent.option.getCall(2).args, ['dataSource', ['updatedData1', 'updatedData2']]); assert.deepEqual(stubComponent.option.getCall(3).args, ['visible', true]); assert.deepEqual(stubComponent.option.getCall(4).args, ['position', { 'at': 'top', 'collision': 'fit flipfit', 'my': 'bottom', boundary: '<div>', offset: 'offset' }]); }); QUnit.test('onShown passed to createComponent should work correct, one element in tooltip', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); stubComponent.option.reset(); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(0).args[2].onShown(); assert.equal(stubComponent.option.callCount, 1); assert.deepEqual(stubComponent.option.getCall(0).args, ['focusStateEnabled', true]); }); QUnit.test('onShown passed to createComponent should work correct, several elements in tooltip', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, extend(this.extraOptions, { isButtonClick: true })); stubComponent.option.reset(); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(0).args[2].onShown(); assert.equal(stubComponent.option.callCount, 2); assert.deepEqual(stubComponent.option.getCall(1).args, ['focusedElement', null]); assert.ok(stubComponent.focus.called); }); QUnit.test('contentTemplate passed to createComponent should pass correct showScrollbar option for touch device', function(assert) { const _touch = support.touch; try { support.touch = true; const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); assert.equal(stubCreateComponent.getCall(1).args[2].showScrollbar, 'always'); } finally { support.touch = _touch; } }); QUnit.test('onContentReady passed to createComponent should work correct', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); assert.equal(stubCreateComponent.getCall(1).args[2].onContentReady(), undefined, 'called without errors'); }); QUnit.test('onContentReady passed to createComponent should work correct, with dragBehavior', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const dragBehavior = sinon.spy(); tooltip.show('target', dataList, extend(this.extraOptions, { dragBehavior: dragBehavior })); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); assert.equal(stubCreateComponent.getCall(1).args[2].onContentReady(), undefined, 'called without errors'); assert.ok(dragBehavior.called); }); QUnit.test('onItemClick passed to createComponent should work correct', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const event = { itemData: { data: 'data', currentData: 'currentData' } }; tooltip.show('target', dataList, this.extraOptions); stubComponent.option.reset(); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].onItemClick(event); assert.deepEqual(stubComponent.option.getCall(0).args, ['visible', false], 'tooltip is hide'); assert.deepEqual(stubShowAppointmentPopup.getCall(0).args, [event.itemData.data, false, event.itemData.currentData]); }); QUnit.test('onItemClick passed to createComponent should work correct, with clickEvent', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const event = { itemData: { data: 'data', currentData: 'currentData' } }; const clickEvent = sinon.spy(); tooltip.show('target', dataList, extend(this.extraOptions, { clickEvent: clickEvent })); stubComponent.option.reset(); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].onItemClick(event); assert.deepEqual(stubComponent.option.getCall(0).args, ['visible', false], 'tooltip is hide'); assert.deepEqual(stubShowAppointmentPopup.getCall(0).args, [event.itemData.data, false, event.itemData.currentData]); assert.ok(clickEvent.called); }); QUnit.test('itemTemplate passed to createComponent should work correct', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const item = { data: 'data', currentData: 'currentData', color: { done: sinon.spy() } }; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); const itemTemplate = stubCreateComponent.getCall(1).args[2].itemTemplate(item, 'index'); assert.ok(itemTemplate instanceof FunctionTemplate); assert.ok(stubAddDefaultTemplates.getCall(0).args[0]['appointmentTooltip'] instanceof FunctionTemplate); assert.equal(stubGetAppointmentTemplate.getCall(0).args[0], 'appointmentTooltipTemplate'); assert.deepEqual(stubGetTextAndFormatDate.getCall(0).args, [item.data, item.currentData]); // create delete button assert.equal(stubCreateComponent.getCall(2).args[0][0].className, 'dx-tooltip-appointment-item-delete-button'); assert.deepEqual(stubCreateComponent.getCall(2).args[1], Button); assert.equal(stubCreateComponent.getCall(2).args[2].icon, 'trash'); assert.equal(stubCreateComponent.getCall(2).args[2].stylingMode, 'text'); assert.ok(stubCreateComponent.getCall(2).args[2].onClick); // check onClick function stubComponent.option.reset(); const e = { event: { stopPropagation: sinon.spy() } }; stubCreateComponent.getCall(2).args[2].onClick(e); assert.deepEqual(stubComponent.option.getCall(0).args, ['visible', false], 'tooltip is hide'); assert.ok(e.event.stopPropagation.called); assert.deepEqual(stubCheckAndDeleteAppointment.getCall(0).args, [item.data, item.currentData]); }); QUnit.test('Delete button shouldn\'t createed, editing = false', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const item = { data: 'data', currentData: 'currentData', color: { done: sinon.spy() } }; tooltip.show('target', dataList, extend(this.extraOptions, { editing: false })); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].itemTemplate(item, 'index'); assert.equal(stubCreateComponent.getCall(2), undefined); }); QUnit.test('Delete button shouldn\'t created, appointment is disabled', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = [{ data: 'data1', disabled: true }, { data: 'data2', disabled: true }]; const item = { data: dataList[0], currentData: 'currentData', color: { done: sinon.spy() } }; tooltip.show('target', dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].itemTemplate(item, 'index'); assert.equal(stubCreateComponent.getCall(2), undefined); }); QUnit.test('isAlreadyShown method, tooltip is not created', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const target = ['target']; assert.ok(!tooltip.isAlreadyShown(target), 'tooltip is not created and haven\'t data'); }); QUnit.test('isAlreadyShown method, tooltip is created and shown', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = [{ data: 'data1' }, { data: 'data2' }]; const target = ['target']; const callback = sinon.stub(); callback.withArgs('target').returns(target); callback.withArgs('visible').returns(true); stubComponent.option = callback; tooltip.show(target, dataList, this.extraOptions); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); assert.ok(tooltip.isAlreadyShown(target), 'tooltip is shown and have the same target'); assert.ok(!tooltip.isAlreadyShown(['target_1']), 'tooltip is shown and have another target'); }); QUnit.test('isAlreadyShown method, tooltip is hide', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = [{ data: 'data1' }, { data: 'data2' }]; const target = ['target']; const callback = sinon.stub(); callback.withArgs('target').returns(target); callback.withArgs('visible').returns(false); stubComponent.option = callback; tooltip.show(target, dataList, this.extraOptions); assert.ok(!tooltip.isAlreadyShown(target), 'tooltip is hidden'); }); // deprecated option QUnit.test('dropDownAppointmentTemplate equal to "dropDownAppointment"', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const item = { data: 'data', currentData: 'currentData', color: { done: sinon.spy() } }; tooltip.show('target', dataList, extend(this.extraOptions, { dropDownAppointmentTemplate: 'dropDownAppointment' })); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].itemTemplate(item, 'index'); assert.ok(stubAddDefaultTemplates.getCall(0).args[0]['appointmentTooltip'] instanceof FunctionTemplate); assert.equal(stubGetAppointmentTemplate.getCall(0).args[0], 'appointmentTooltipTemplate'); }); QUnit.test('dropDownAppointmentTemplate equal to custom template', function(assert) { const tooltip = this.createSimpleTooltip(this.tooltipOptions); const dataList = ['data1', 'data2']; const item = { data: 'data', currentData: 'currentData', color: { done: sinon.spy() } }; tooltip.show('target', dataList, extend(this.extraOptions, { dropDownAppointmentTemplate: 'custom_template' })); stubCreateComponent.getCall(0).args[2].contentTemplate('<div>'); stubCreateComponent.getCall(1).args[2].itemTemplate(item, 'index'); assert.ok(stubAddDefaultTemplates.getCall(0).args[0]['dropDownAppointment'] instanceof FunctionTemplate); assert.equal(stubGetAppointmentTemplate.getCall(0).args[0], 'dropDownAppointmentTemplate'); });
# stdlib from typing import Any # syft relative from ...core.common import UID from ...core.common.serde.serializable import Serializable class PyPrimitive(Serializable): def __init__(self) -> None: self._id: UID def upcast(self) -> Any: pass
/* @flow */ import type { ChannelControl, ControlMessage } from '@mixxx-launchpad/mixxx' import type { LaunchpadDevice, MidiMessage } from '../../' import { modes } from '../ModifierSidebar' import type { Modifier } from '../ModifierSidebar' export default (gridPosition: [number, number]) => (deck: ChannelControl) => (modifier: Modifier) => (device: LaunchpadDevice) => { return { bindings: { sync: { type: 'button', target: gridPosition, attack: (message: MidiMessage, { bindings }: Object) => { modes(modifier.getState(), () => { if (bindings.syncMode.getValue()) { deck.sync_enabled.setValue(0) } else { deck.sync_enabled.setValue(1) } }, () => { if (bindings.syncMode.getValue() === 2) { deck.sync_master.setValue(0) } else { deck.sync_master.setValue(1) } } ) } }, syncMode: { type: 'control', target: deck.sync_mode, update: ({ value }: ControlMessage, { bindings }: Object) => { if (value === 0) { bindings.sync.button.sendColor(device.colors.black) } else if (value === 1) { bindings.sync.button.sendColor(device.colors.hi_orange) } else if (value === 2) { bindings.sync.button.sendColor(device.colors.hi_red) } } } } } }
import GameSprite from "./GameSprite"; import Display from "../Display" /** * Runner reprezentuje hlavní postavu hry. */ export default class Runner extends GameSprite { constructor(scene, x, y, state) { super(scene, x, y, 'dude', 'run', true) this.default = { x: x, y: y } this.states = new States(this, scene) this.currentState = this.states[state] this.lives = 3 this.id = 0 this.pivotY = 240 * Display.gamingArea.scaleY this.body.setBounce(0.2) } run() { this.currentState.run() } hit() { this.currentState.hit() } jump() { this.currentState.jump() } slide() { this.currentState.slide() } } function States(runner, scene) { function jump() { runner.emit('jump') runner.currentState = runner.states['jumpingState'] runner.anim = 'jump' runner.setVelocityY(-500 * Display.gamingArea.scaleY) let anim = runner.character + runner.anim + scene.foregroundColor runner.play(anim) return true } function hit() { runner.currentState = runner.states['hitState'] runner.anim = 'hit' runner.lives-- if (runner.lives === 0) { runner.emit('killed') } else { runner.emit('hit') runner.play('dudehit' + scene.foregroundColor) runner.setSize() runner.setY(runner.pivotY) scene.time.delayedCall(100, () => { runner.anim = 'run' runner.play('dude' + runner.anim + scene.foregroundColor) runner.setSize() runner.setY(runner.pivotY) runner.currentState = runner.states['runningState'] }) } return true } function run() { runner.emit('run') runner.currentState = runner.states['runningState'] runner.anim = 'run' let anim = runner.character + runner.anim + scene.foregroundColor runner.play(anim) runner.setSize() runner.setY(runner.pivotY) return true } function jumpDown() { runner.emit('jumpdown') runner.anim = 'slide' runner.setVelocityY(900 * Display.gamingArea.scaleY) runner.play(runner.character + runner.anim + scene.foregroundColor) return true } function emptyf() { return false } function gap() { scene.fallableObjects.remove(runner) runner.currentState = runner.states['gapState'] runner.anim = 'jump' runner.play(runner.character + runner.anim + scene.foregroundColor) } function slide() { runner.emit('slide') runner.currentState = runner.states['slidingState'] runner.anim = 'slide' runner.play(runner.character + runner.anim + scene.foregroundColor) runner.setSize() } this.runningState = { name: 'runningState', slide: slide, run: emptyf, jump: jump, hit: hit, gap: gap } /** * Jumping State */ this.hitState = { name: 'hitState', slide: emptyf, run: emptyf, jump: emptyf, hit: emptyf, gap: emptyf } /** * Sliding State */ this.slidingState = { name: 'slidingState', slide: emptyf, run: emptyf, jump: run, hit: hit, gap: gap } //JUMPING STATE this.jumpingState = { name: 'jumpingState', jump: emptyf, slide: jumpDown, run: run, hit: hit, gap: gap } this.gapState = { name: 'gapState', jump: emptyf, slide: emptyf, run: emptyf, hit: emptyf, gap: emptyf } this.jumpingAndslideing = { name: 'jumpingAndslideingState', jump: emptyf, slide: emptyf, run: run, gap: gap } }
import test from './test'; import store from 'store'; import { sleep } from 'utils'; export default async function() { await test(window, 0); const hasSW = !!navigator.serviceWorker; // test if we suggest navigator.serviceWorker await store.put('feature', Number(hasSW), 'navigator.serviceWorker'); if (!hasSW) return; const sw = await navigator.serviceWorker.register('/auto/global-sw.js', { scope: '/auto/' }); console.log('Registered!', sw); await store.put('feature', 1, 'Registered'); await sleep(3000); await sw.unregister(); console.log('Unregistered'); await store.put('feature', 1, 'Unregistered'); }
var searchData= [ ['sdl2_5ftypes_2ehpp',['sdl2_Types.hpp',['../d0/d29/sdl2___types_8hpp.html',1,'']]], ['sdl_5fttf_5fmajor_5fversion',['SDL_TTF_MAJOR_VERSION',['../d6/d5a/ttf___s_d_l__ttf_8h.html#a895f91173346a028d25202ced75b549e',1,'ttf_SDL_ttf.h']]], ['sdl_5fttf_5fminor_5fversion',['SDL_TTF_MINOR_VERSION',['../d6/d5a/ttf___s_d_l__ttf_8h.html#ae192fcc5f145ad3ffb3652fe4ab768bb',1,'ttf_SDL_ttf.h']]], ['sdl_5fttf_5fpatchlevel',['SDL_TTF_PATCHLEVEL',['../d6/d5a/ttf___s_d_l__ttf_8h.html#a6c438d5ec0bddd2361845ac5d4f7f30b',1,'ttf_SDL_ttf.h']]], ['sdl_5fttf_5fversion',['SDL_TTF_VERSION',['../d6/d5a/ttf___s_d_l__ttf_8h.html#ae9baeafdf603e01fdd7f52ef71d7a1e8',1,'ttf_SDL_ttf.h']]], ['sdlflags',['SDLFlags',['../df/d6f/structpu_1_1ui_1_1render_1_1_renderer_init_options.html#afcb4550f72bb4c7ac7034d32a51c405c',1,'pu::ui::render::RendererInitOptions']]], ['setalphavalue',['SetAlphaValue',['../da/d54/namespacepu_1_1ui_1_1render.html#a3a2422c61c974b0ad2adbb45ad61c7e5',1,'pu::ui::render']]], ['setbackgroundcolor',['SetBackgroundColor',['../d6/d11/classpu_1_1ui_1_1_layout.html#a41292d1243a117bff050a872f64791d3',1,'pu::ui::Layout']]], ['setbackgroundimage',['SetBackgroundImage',['../d6/d11/classpu_1_1ui_1_1_layout.html#a272091e3b143aabe600922e8ea99d18b',1,'pu::ui::Layout']]], ['setbaserenderalpha',['SetBaseRenderAlpha',['../d0/d27/classpu_1_1ui_1_1render_1_1_renderer.html#ae5925f725a77473f6a18fb328990c314',1,'pu::ui::render::Renderer']]], ['setbaserenderposition',['SetBaseRenderPosition',['../d0/d27/classpu_1_1ui_1_1render_1_1_renderer.html#a99cf122124b49ec37641d3d0caa7bedc',1,'pu::ui::render::Renderer']]], ['setborderradius',['SetBorderRadius',['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#aeb4919c5ca965f62fe221e55d6697ab6',1,'pu::ui::elm::Rectangle']]], ['setcanceloption',['SetCancelOption',['../d6/de9/classpu_1_1ui_1_1_dialog.html#a375d4dea4932e413266d752c265cb460',1,'pu::ui::Dialog']]], ['setcolor',['SetColor',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a03f952e5c922407c3ea63c6ac927c756',1,'pu::ui::elm::Button::SetColor()'],['../de/dbb/classpu_1_1ui_1_1elm_1_1_menu_item.html#af10bd093467b14234c339a4ba16bc41d',1,'pu::ui::elm::MenuItem::SetColor()'],['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#aa529d2b3a7d5e91fe3b0a9cc668eb312',1,'pu::ui::elm::Menu::SetColor()'],['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#a1ff5184213c1379dca9d45b025912152',1,'pu::ui::elm::ProgressBar::SetColor()'],['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#ae6a61ec139b6026e9db394b6723712d9',1,'pu::ui::elm::Rectangle::SetColor()'],['../df/d21/classpu_1_1ui_1_1elm_1_1_text_block.html#ae4bcdf1cd435a364de473c117ea8d215',1,'pu::ui::elm::TextBlock::SetColor()'],['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#a377233227eb7f5dabf8007c3b4ba0e86',1,'pu::ui::elm::Toggle::SetColor()']]], ['setcontent',['SetContent',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a4f79d2a84843f179d7305f2444e3c64a',1,'pu::ui::elm::Button::SetContent()'],['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#a9ebbcd42a556dbafb475d0d31d5cabfe',1,'pu::ui::elm::Toggle::SetContent()']]], ['setcontentfont',['SetContentFont',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a4acbcc492facb04335b119142d30c9b3',1,'pu::ui::elm::Button']]], ['setcooldownenabled',['SetCooldownEnabled',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a122f27cfbf10d3a01142aeef20b549a3',1,'pu::ui::elm::Menu']]], ['setfadealphaamountperframe',['SetFadeAlphaAmountPerFrame',['../da/dc0/classpu_1_1ui_1_1_application.html#a0b42b7b087bac46fba4a9e492a2bcb55',1,'pu::ui::Application']]], ['setfont',['SetFont',['../df/d21/classpu_1_1ui_1_1elm_1_1_text_block.html#a341d6656d9b684266642337d3ae5b151',1,'pu::ui::elm::TextBlock::SetFont()'],['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#ac2f670f1b549ffbfaaffb6253c23de47',1,'pu::ui::elm::Toggle::SetFont()']]], ['setheight',['SetHeight',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a9c1c705c1888f5d6e024c887558ebe93',1,'pu::ui::elm::Button::SetHeight()'],['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#a7a4dd430044e9df21d7d743198e3b6d7',1,'pu::ui::elm::Image::SetHeight()'],['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#abbaf41f598b12462f599909edc076207',1,'pu::ui::elm::ProgressBar::SetHeight()'],['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#a5f36972786b4d3e58f5657bb5b0e89f5',1,'pu::ui::elm::Rectangle::SetHeight()'],['../dc/dcd/classpu_1_1ui_1_1_container.html#a86d4802e7a35c3b89929b652744c5c9c',1,'pu::ui::Container::SetHeight()']]], ['sethorizontalalign',['SetHorizontalAlign',['../d9/d0e/classpu_1_1ui_1_1elm_1_1_element.html#ac1247e8603f94cd7f042f67a0d9d1dd9',1,'pu::ui::elm::Element']]], ['seticon',['SetIcon',['../de/dbb/classpu_1_1ui_1_1elm_1_1_menu_item.html#ae76e8cb632ace0bb680b78050c4495ec',1,'pu::ui::elm::MenuItem::SetIcon()'],['../d6/de9/classpu_1_1ui_1_1_dialog.html#ac705ecbdf17c20d95c4392f372944582',1,'pu::ui::Dialog::SetIcon()']]], ['setimage',['SetImage',['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#ad456ea7042bd03e6b7dd7671699f7add',1,'pu::ui::elm::Image']]], ['setitemsize',['SetItemSize',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#ac65be771f69b986ef3d1f51c8baa7c81',1,'pu::ui::elm::Menu']]], ['setkey',['SetKey',['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#affb6993bb98a439aa0355776cf988942',1,'pu::ui::elm::Toggle']]], ['setmaxvalue',['SetMaxValue',['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#aa835d1a1743b1b31a922d52e3d39bedc',1,'pu::ui::elm::ProgressBar']]], ['setname',['SetName',['../de/dbb/classpu_1_1ui_1_1elm_1_1_menu_item.html#ae7b91a19e3fcacf5c4ebc61422280d26',1,'pu::ui::elm::MenuItem']]], ['setnumberofitemstoshow',['SetNumberOfItemsToShow',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a5276c21c98e83a5ce278f70a9396bb35',1,'pu::ui::elm::Menu']]], ['setonclick',['SetOnClick',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a5462ca68673ae2bd60f87133802346b1',1,'pu::ui::elm::Button']]], ['setonfocuscolor',['SetOnFocusColor',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#af581cd1a4036843706b4e1c1578d3c06',1,'pu::ui::elm::Menu']]], ['setoninput',['SetOnInput',['../da/dc0/classpu_1_1ui_1_1_application.html#a8caaa727dff48ca7e4955284294bf86e',1,'pu::ui::Application::SetOnInput()'],['../d6/d11/classpu_1_1ui_1_1_layout.html#a7ae11b4155d3f9075a31aebae4f5c082',1,'pu::ui::Layout::SetOnInput()']]], ['setonselectionchanged',['SetOnSelectionChanged',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a868a219682ca14babd88cb798252a20c',1,'pu::ui::elm::Menu']]], ['setparent',['SetParent',['../d9/d0e/classpu_1_1ui_1_1elm_1_1_element.html#a4240103c231e278ede5ae8eaf397868d',1,'pu::ui::elm::Element']]], ['setposition',['SetPosition',['../d8/d8f/namespacepu_1_1audio.html#a04714ba749bfc72df1ae72ec3e229e42',1,'pu::audio']]], ['setprogress',['SetProgress',['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#a679125453ccdf2048f3968c03a971252',1,'pu::ui::elm::ProgressBar']]], ['setprogresscolor',['SetProgressColor',['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#a0f1db259dc7fc0f7c87bb7d573717070',1,'pu::ui::elm::ProgressBar']]], ['setradius',['SetRadius',['../d6/d8f/classpu_1_1ui_1_1_overlay.html#ab95778fa7306e8213c9269213b4d2052',1,'pu::ui::Overlay']]], ['setrotation',['SetRotation',['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#a5d17349fc28f8abd56804a315411f5d1',1,'pu::ui::elm::Image']]], ['setscrollbarcolor',['SetScrollbarColor',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a9b0aa24831dd2e67e8e2ce2e33aca75a',1,'pu::ui::elm::Menu']]], ['setselectedindex',['SetSelectedIndex',['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a025e8e8f8479be5335d12c6d90b110b8',1,'pu::ui::elm::Menu']]], ['settext',['SetText',['../df/d21/classpu_1_1ui_1_1elm_1_1_text_block.html#a6eef4a4ce8fc47d50d56cba7bdb52486',1,'pu::ui::elm::TextBlock::SetText()'],['../dc/d49/classpu_1_1ui_1_1extras_1_1_toast.html#a670a953ceb56718228aebface8d14f63',1,'pu::ui::extras::Toast::SetText()']]], ['setverticalalign',['SetVerticalAlign',['../d9/d0e/classpu_1_1ui_1_1elm_1_1_element.html#ac4051f1cf5bbbcc6585cdd6649cb73ff',1,'pu::ui::elm::Element']]], ['setvisible',['SetVisible',['../d9/d0e/classpu_1_1ui_1_1elm_1_1_element.html#a90267646ac32185250f0d7151b7ea6b2',1,'pu::ui::elm::Element']]], ['setvolume',['SetVolume',['../d8/d8f/namespacepu_1_1audio.html#ab1e9f5d82a750544cf34e0a6c99d8560',1,'pu::audio']]], ['setwidth',['SetWidth',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#a5a640c6ebc00cd42b132f63227fe67c4',1,'pu::ui::elm::Button::SetWidth()'],['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#a0ad166e3e6dc7c14b7f8a5d546ffa354',1,'pu::ui::elm::Image::SetWidth()'],['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a685cc892f2e7fad9f74e19c7c5cd8adb',1,'pu::ui::elm::Menu::SetWidth()'],['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#abb46ed264657fce12eb82b15ac40daf2',1,'pu::ui::elm::ProgressBar::SetWidth()'],['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#a3ed63c9a60db18731843605ed6cd6a73',1,'pu::ui::elm::Rectangle::SetWidth()'],['../dc/dcd/classpu_1_1ui_1_1_container.html#a5547b8175840969c403b85aa966b8e9c',1,'pu::ui::Container::SetWidth()']]], ['setx',['SetX',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#ad68929294f37287c6c6cc5e7f60e1fce',1,'pu::ui::elm::Button::SetX()'],['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#a0fd85939738d5937808704fbd3b1f54e',1,'pu::ui::elm::Image::SetX()'],['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#aa0caa6aab30748818cbc858f8acb2ac5',1,'pu::ui::elm::Menu::SetX()'],['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#a8ccfd0bf45e387737f546f9db95eb7fe',1,'pu::ui::elm::ProgressBar::SetX()'],['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#a44d84070429d85bb16a4bd7f442a5cbd',1,'pu::ui::elm::Rectangle::SetX()'],['../df/d21/classpu_1_1ui_1_1elm_1_1_text_block.html#a74b38c9bbb7de615d41268a6e502c691',1,'pu::ui::elm::TextBlock::SetX()'],['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#a478395569f2591baadcbb5a07660bcbb',1,'pu::ui::elm::Toggle::SetX()'],['../dc/dcd/classpu_1_1ui_1_1_container.html#ac002ebdb4cd030f2b68f1ffe26899851',1,'pu::ui::Container::SetX()']]], ['sety',['SetY',['../d4/de7/classpu_1_1ui_1_1elm_1_1_button.html#ae2043e7eb028bfd7a4d5fde95373c336',1,'pu::ui::elm::Button::SetY()'],['../d6/d63/classpu_1_1ui_1_1elm_1_1_image.html#ab314354828a825e992911d3a7fdea92c',1,'pu::ui::elm::Image::SetY()'],['../dc/d6c/classpu_1_1ui_1_1elm_1_1_menu.html#a1149593bb0c132641faebbd20a61e892',1,'pu::ui::elm::Menu::SetY()'],['../d2/dcc/classpu_1_1ui_1_1elm_1_1_progress_bar.html#ad8499f4f76bcd5d32a4c9d4f8658a462',1,'pu::ui::elm::ProgressBar::SetY()'],['../d5/dea/classpu_1_1ui_1_1elm_1_1_rectangle.html#a3780adb6abaced943ca3acc90ed75e7c',1,'pu::ui::elm::Rectangle::SetY()'],['../df/d21/classpu_1_1ui_1_1elm_1_1_text_block.html#a69a6ec4255dcd8d7ae445293aaf1429d',1,'pu::ui::elm::TextBlock::SetY()'],['../d5/d51/classpu_1_1ui_1_1elm_1_1_toggle.html#a49ac1879cc0a478afea3e5f4ec4cd68c',1,'pu::ui::elm::Toggle::SetY()'],['../dc/dcd/classpu_1_1ui_1_1_container.html#aa8aef1a9c44336f8869b6c34ef6a4150',1,'pu::ui::Container::SetY()']]], ['sfx',['Sfx',['../d8/d8f/namespacepu_1_1audio.html#a8c7c61eb27f10a7ab3ae5abe610887a6',1,'pu::audio']]], ['sharedfont',['SharedFont',['../da/d54/namespacepu_1_1ui_1_1render.html#a3c7c58449d392444ecb914962de801c7',1,'pu::ui::render']]], ['show',['show',['../da/dc0/classpu_1_1ui_1_1_application.html#a0a5805816688c95a130b64eeebd457d1',1,'pu::ui::Application::show()'],['../da/dc0/classpu_1_1ui_1_1_application.html#aea869e54e6672af5507df7d7559b2885',1,'pu::ui::Application::Show()'],['../d6/de9/classpu_1_1ui_1_1_dialog.html#ad0a1bf737aacad368058dfa578abee38',1,'pu::ui::Dialog::Show()']]], ['showdialog',['ShowDialog',['../da/dc0/classpu_1_1ui_1_1_application.html#aa55454aeeb6d1c27b68e92786b21e59d',1,'pu::ui::Application']]], ['showwithfadein',['ShowWithFadeIn',['../da/dc0/classpu_1_1ui_1_1_application.html#a7290833d778556c8303bcca9e06fa707',1,'pu::ui::Application']]], ['simulatetouch',['SimulateTouch',['../d6/d11/classpu_1_1ui_1_1_layout.html#aa2e57187e7414c1f594c1f0059b1735f',1,'pu::ui::Layout']]], ['standard',['Standard',['../da/d54/namespacepu_1_1ui_1_1render.html#a3c7c58449d392444ecb914962de801c7aeb6d8ae6f20283755b339c0dc273988b',1,'pu::ui::render']]], ['startoverlay',['StartOverlay',['../da/dc0/classpu_1_1ui_1_1_application.html#aa0e7eaf1eb9c9f55256db3c9de4f6124',1,'pu::ui::Application']]], ['startoverlaywithtimeout',['StartOverlayWithTimeout',['../da/dc0/classpu_1_1ui_1_1_application.html#acddde0e194b8f148142d699cf4427f63',1,'pu::ui::Application']]], ['startswith',['StartsWith',['../d2/de5/classpu_1_1_string.html#af0ede32ab151fb8fad1253d0e4644a3c',1,'pu::String']]], ['stoi',['stoi',['../d6/d23/pu___string_8hpp.html#aa641cfa3482ffdf08be99dd4e0f182ce',1,'std']]], ['stop',['Stop',['../d8/d8f/namespacepu_1_1audio.html#abfeb75790aa1646d075c1ce31006d2ff',1,'pu::audio']]], ['string',['String',['../d2/de5/classpu_1_1_string.html#a859dc16d50365b158178a07fd966f8d2',1,'pu::String::String()'],['../d2/de5/classpu_1_1_string.html#af2691d375f31f19595dad4df98f4a0cf',1,'pu::String::String(const char *C_UTF8)'],['../d2/de5/classpu_1_1_string.html#a4da3be735cf322fb823011c2e2c69c2f',1,'pu::String::String(const char16_t *C_UTF16)'],['../d2/de5/classpu_1_1_string.html#a00ee3a8466cfdfbcb59293c3a0cc29fd',1,'pu::String::String(std::string UTF8)'],['../d2/de5/classpu_1_1_string.html#aa0e2ac0825616a6969890161eb32193a',1,'pu::String::String(std::u16string UTF16)']]], ['string',['String',['../d2/de5/classpu_1_1_string.html',1,'pu']]], ['substr',['substr',['../d2/de5/classpu_1_1_string.html#ae31428777674f9f55a05b471a9c89d06',1,'pu::String']]], ['substring',['Substring',['../d2/de5/classpu_1_1_string.html#a2cf84acf3bc183f435778e186dc4c9c0',1,'pu::String']]], ['surface',['Surface',['../d1/d78/namespacepu_1_1sdl2.html#a00c40ae94ad2fc0b78571071c62faa19',1,'pu::sdl2']]] ];
/*! jQuery UI - v1.10.3 - 2013-10-05 * http://jqueryui.com * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(t){t.datepicker.regional.fr={closeText:"Fermer",prevText:"Précédent",nextText:"Suivant",currentText:"Aujourd'hui",monthNames:["Janvier","Février","Mars","Avril","Mai","Juin","Juillet","Août","Septembre","Octobre","Novembre","Décembre"],monthNamesShort:["Janv.","Févr.","Mars","Avril","Mai","Juin","Juil.","Août","Sept.","Oct.","Nov.","Déc."],dayNames:["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"],dayNamesShort:["Dim.","Lun.","Mar.","Mer.","Jeu.","Ven.","Sam."],dayNamesMin:["D","L","M","M","J","V","S"],weekHeader:"Sem.",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},t.datepicker.setDefaults(t.datepicker.regional.fr)});
const compressSync = require('iltorb').compressSync; try { var output = compressSync(input); } catch(err) { // ... }
load("bf4b12814bc95f34eeb130127d8438ab.js"); load("93fae755edd261212639eed30afa2ca4.js"); // Copyright (c) 2012 Ecma International. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- es5id: 15.3.5.4_2-83gs description: > Strict mode - checking access to strict function caller from non-strict function (non-strict function declaration called by strict Function.prototype.apply(globalObject)) flags: [noStrict] features: [caller] ---*/ var global = this; function f() { return gNonStrict();}; (function () {"use strict"; f.apply(global); })(); function gNonStrict() { return gNonStrict.caller; }
import logging import time from flask import make_response, request from flask_login import current_user from flask_restful import abort from redash import models, settings from redash.handlers.base import BaseResource, get_object_or_404 from redash.permissions import (has_access, not_view_only, require_access, require_permission, view_only) from redash.tasks import QueryTask from redash.tasks.queries import enqueue_query from redash.utils import (collect_parameters_from_request, gen_query_hash, json_dumps, utcnow) from redash.utils.parameterized_query import ParameterizedQuery def error_response(message): return {'job': {'status': 4, 'error': message}}, 400 # # Run a parameterized query synchronously and return the result # DISCLAIMER: Temporary solution to support parameters in queries. Should be # removed once we refactor the query results API endpoints and handling # on the client side. Please don't reuse in other API handlers. # def run_query_sync(data_source, parameter_values, query_text, max_age=0): query = ParameterizedQuery(query_text).apply(parameter_values) if query.missing_params: raise Exception('Missing parameter value for: {}'.format(", ".join(query.missing_params))) if max_age <= 0: query_result = None else: query_result = models.QueryResult.get_latest(data_source, query.text, max_age) query_hash = gen_query_hash(query.text) if query_result: logging.info("Returning cached result for query %s" % query_hash) return query_result try: started_at = time.time() data, error = data_source.query_runner.run_query(query.text, current_user) if error: logging.info('got bak error') logging.info(error) return None run_time = time.time() - started_at query_result, updated_query_ids = models.QueryResult.store_result(data_source.org_id, data_source, query_hash, query.text, data, run_time, utcnow()) models.db.session.commit() return query_result except Exception as e: if max_age > 0: abort(404, message="Unable to get result from the database, and no cached query result found.") else: abort(503, message="Unable to get result from the database.") return None def run_query(data_source, parameter_values, query_text, query_id, max_age=0): if data_source.paused: if data_source.pause_reason: message = '{} is paused ({}). Please try later.'.format(data_source.name, data_source.pause_reason) else: message = '{} is paused. Please try later.'.format(data_source.name) return error_response(message) query = ParameterizedQuery(query_text).apply(parameter_values) if query.missing_params: return error_response(u'Missing parameter value for: {}'.format(u", ".join(query.missing_params))) if max_age == 0: query_result = None else: query_result = models.QueryResult.get_latest(data_source, query.text, max_age) if query_result: return {'query_result': query_result.to_dict()} else: job = enqueue_query(query.text, data_source, current_user.id, metadata={"Username": current_user.email, "Query ID": query_id}) return {'job': job.to_dict()} class QueryResultListResource(BaseResource): @require_permission('execute_query') def post(self): """ Execute a query (or retrieve recent results). :qparam string query: The query text to execute :qparam number query_id: The query object to update with the result (optional) :qparam number max_age: If query results less than `max_age` seconds old are available, return them, otherwise execute the query; if omitted or -1, returns any cached result, or executes if not available. Set to zero to always execute. :qparam number data_source_id: ID of data source to query :qparam object parameters: A set of parameter values to apply to the query. """ params = request.get_json(force=True) query = params['query'] max_age = int(params.get('max_age', -1)) query_id = params.get('query_id', 'adhoc') parameters = params.get('parameters', collect_parameters_from_request(request.args)) data_source = models.DataSource.get_by_id_and_org(params.get('data_source_id'), self.current_org) if not has_access(data_source.groups, self.current_user, not_view_only): return {'job': {'status': 4, 'error': 'You do not have permission to run queries with this data source.'}}, 403 self.record_event({ 'action': 'execute_query', 'object_id': data_source.id, 'object_type': 'data_source', 'query': query, 'query_id': query_id, 'parameters': parameters }) return run_query(data_source, parameters, query, query_id, max_age) ONE_YEAR = 60 * 60 * 24 * 365.25 class QueryResultResource(BaseResource): @staticmethod def add_cors_headers(headers): if 'Origin' in request.headers: origin = request.headers['Origin'] if set(['*', origin]) & settings.ACCESS_CONTROL_ALLOW_ORIGIN: headers['Access-Control-Allow-Origin'] = origin headers['Access-Control-Allow-Credentials'] = str(settings.ACCESS_CONTROL_ALLOW_CREDENTIALS).lower() @require_permission('view_query') def options(self, query_id=None, query_result_id=None, filetype='json'): headers = {} self.add_cors_headers(headers) if settings.ACCESS_CONTROL_REQUEST_METHOD: headers['Access-Control-Request-Method'] = settings.ACCESS_CONTROL_REQUEST_METHOD if settings.ACCESS_CONTROL_ALLOW_HEADERS: headers['Access-Control-Allow-Headers'] = settings.ACCESS_CONTROL_ALLOW_HEADERS return make_response("", 200, headers) @require_permission('execute_query') def post(self, query_id): """ Execute a saved query. :param number query_id: The ID of the query whose results should be fetched. :param object parameters: The parameter values to apply to the query. :qparam number max_age: If query results less than `max_age` seconds old are available, return them, otherwise execute the query; if omitted or -1, returns any cached result, or executes if not available. Set to zero to always execute. """ params = request.get_json(force=True) parameters = params.get('parameters', {}) max_age = int(params.get('max_age', 0)) query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org) if not has_access(query.data_source.groups, self.current_user, not_view_only): return {'job': {'status': 4, 'error': 'You do not have permission to run queries with this data source.'}}, 403 else: return run_query(query.data_source, parameters, query.query_text, query_id, max_age) @require_permission('view_query') def get(self, query_id=None, query_result_id=None, filetype='json'): """ Retrieve query results. :param number query_id: The ID of the query whose results should be fetched :param number query_result_id: the ID of the query result to fetch :param string filetype: Format to return. One of 'json', 'xlsx', or 'csv'. Defaults to 'json'. :<json number id: Query result ID :<json string query: Query that produced this result :<json string query_hash: Hash code for query text :<json object data: Query output :<json number data_source_id: ID of data source that produced this result :<json number runtime: Length of execution time in seconds :<json string retrieved_at: Query retrieval date/time, in ISO format """ # TODO: # This method handles two cases: retrieving result by id & retrieving result by query id. # They need to be split, as they have different logic (for example, retrieving by query id # should check for query parameters and shouldn't cache the result). should_cache = query_result_id is not None parameter_values = collect_parameters_from_request(request.args) max_age = int(request.args.get('maxAge', 0)) query_result = None if query_result_id: query_result = get_object_or_404(models.QueryResult.get_by_id_and_org, query_result_id, self.current_org) if query_id is not None: query = get_object_or_404(models.Query.get_by_id_and_org, query_id, self.current_org) if query_result is None and query is not None: if settings.ALLOW_PARAMETERS_IN_EMBEDS and parameter_values: query_result = run_query_sync(query.data_source, parameter_values, query.query_text, max_age=max_age) elif query.latest_query_data_id is not None: query_result = get_object_or_404(models.QueryResult.get_by_id_and_org, query.latest_query_data_id, self.current_org) if query is not None and query_result is not None and self.current_user.is_api_user(): if query.query_hash != query_result.query_hash: abort(404, message='No cached result found for this query.') if query_result: require_access(query_result.data_source.groups, self.current_user, view_only) if isinstance(self.current_user, models.ApiUser): event = { 'user_id': None, 'org_id': self.current_org.id, 'action': 'api_get', 'api_key': self.current_user.name, 'file_type': filetype, 'user_agent': request.user_agent.string, 'ip': request.remote_addr } if query_id: event['object_type'] = 'query' event['object_id'] = query_id else: event['object_type'] = 'query_result' event['object_id'] = query_result_id self.record_event(event) if filetype == 'json': response = self.make_json_response(query_result) elif filetype == 'xlsx': response = self.make_excel_response(query_result) else: response = self.make_csv_response(query_result) if len(settings.ACCESS_CONTROL_ALLOW_ORIGIN) > 0: self.add_cors_headers(response.headers) if should_cache: response.headers.add_header('Cache-Control', 'private,max-age=%d' % ONE_YEAR) return response else: abort(404, message='No cached result found for this query.') def make_json_response(self, query_result): data = json_dumps({'query_result': query_result.to_dict()}) headers = {'Content-Type': "application/json"} return make_response(data, 200, headers) @staticmethod def make_csv_response(query_result): headers = {'Content-Type': "text/csv; charset=UTF-8"} return make_response(query_result.make_csv_content(), 200, headers) @staticmethod def make_excel_response(query_result): headers = {'Content-Type': "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"} return make_response(query_result.make_excel_content(), 200, headers) class JobResource(BaseResource): def get(self, job_id): """ Retrieve info about a running query job. """ job = QueryTask(job_id=job_id) return {'job': job.to_dict()} def delete(self, job_id): """ Cancel a query job in progress. """ job = QueryTask(job_id=job_id) job.cancel()
// Load modules var Net = require('net'); var Stream = require('stream'); var Http = require('http'); var Lab = require('lab'); var Nipple = require('nipple'); var Hoek = require('hoek'); var Shot = require('shot'); var Hoek = require('hoek'); var Hapi = require('..'); // Declare internals var internals = {}; // Test shortcuts var expect = Lab.expect; var before = Lab.before; var after = Lab.after; var describe = Lab.experiment; var it = Lab.test; describe('Request', function () { it('returns valid OPTIONS response', function (done) { var handler = function (request, reply) { reply(Hapi.error.badRequest()); }; var server = new Hapi.Server({ cors: true }); server.route({ method: 'GET', path: '/', handler: handler }); server.inject({ method: 'OPTIONS', url: '/' }, function (res) { expect(res.headers['access-control-allow-origin']).to.equal('*'); done(); }); }); it('generates tail event', function (done) { var handler = function (request, reply) { var t1 = request.addTail('t1'); var t2 = request.addTail('t2'); reply('Done'); t1(); t1(); // Ignored setTimeout(t2, 10); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); var result = null; server.once('tail', function () { expect(result).to.equal('Done'); done(); }); server.inject('/', function (res) { result = res.result; }); }); it('generates tail event without name', function (done) { var handler = function (request, reply) { var tail = request.tail(); reply('Done'); tail(); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); var result = null; server.once('tail', function () { done(); }); server.inject('/', function (res) { }); }); it('returns error response on ext error', function (done) { var handler = function (request, reply) { reply('OK'); }; var server = new Hapi.Server(); var ext = function (request, next) { next(Hapi.error.badRequest()); }; server.ext('onPostHandler', ext); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result.statusCode).to.equal(400); done(); }); }); it('returns unknown response using reply()', function (done) { var unknownRouteHandler = function (request, reply) { reply('unknown-reply'); }; var server = new Hapi.Server(); server.route({ method: '*', path: '/{p*}', handler: unknownRouteHandler }); server.inject('/', function (res) { expect(res.statusCode).to.equal(200); expect(res.result).to.equal('unknown-reply'); done(); }); }); it('handles errors on the response after the response has been started', function (done) { var handler = function (request, reply) { reply('success'); var orig = request.raw.res.write; request.raw.res.write = function (chunk, encoding) { orig.call(request.raw.res, chunk, encoding); request.raw.res.emit('error', new Error('fail')); }; }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.equal('success'); done(); }); }); it('handles stream errors on the response after the response has been piped', function (done) { var handler = function (request, reply) { var TestStream = function () { Stream.Readable.call(this); }; Hoek.inherits(TestStream, Stream.Readable); TestStream.prototype._read = function (size) { var self = this; if (this.isDone) { return; } this.isDone = true; self.push('success'); setImmediate(function () { self.emit('error', new Error()); }); }; var stream = new TestStream(); reply(stream); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.equal('success'); done(); }); }); it('returns 500 on handler exception (same tick)', function (done) { var server = new Hapi.Server({ debug: false }); var handler = function (request) { var x = a.b.c; }; server.route({ method: 'GET', path: '/domain', handler: handler }); server.inject('/domain', function (res) { expect(res.statusCode).to.equal(500); done(); }); }); it('returns 500 on handler exception (next tick)', { parallel: false }, function (done) { var handler = function (request) { setImmediate(function () { var x = not.here; }); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.on('internalError', function (request, err) { expect(err.message).to.equal('Uncaught error: not is not defined'); done(); }); var orig = console.error; console.error = function () { console.error = orig; expect(arguments[0]).to.equal('Debug:'); expect(arguments[1]).to.equal('hapi, internal, implementation, error'); }; server.inject('/', function (res) { expect(res.statusCode).to.equal(500); }); }); it('ignores second call to onReply()', function (done) { var server = new Hapi.Server(); var handler = function (request, reply) { reply('123').hold().send(); }; server.route({ method: 'GET', path: '/domain', handler: handler }); server.inject('/domain', function (res) { expect(res.result).to.equal('123'); done(); }); }); it('sends reply after handler timeout', function (done) { var server = new Hapi.Server(); var handler = function (request, reply) { var response = reply('123').hold(); setTimeout(function () { response.send(); }, 10); }; server.route({ method: 'GET', path: '/domain', handler: handler }); server.inject('/domain', function (res) { expect(res.result).to.equal('123'); done(); }); }); it('returns 500 on ext method exception (same tick)', function (done) { var server = new Hapi.Server({ debug: false }); server.ext('onRequest', function (request, next) { var x = a.b.c; }); var handler = function (request, reply) { reply('neven gonna happen'); }; server.route({ method: 'GET', path: '/domain', handler: handler }); server.inject('/domain', function (res) { expect(res.statusCode).to.equal(500); done(); }); }); it('invokes handler with right arguments', function (done) { var server = new Hapi.Server(); var handler = function (request, reply) { expect(arguments.length).to.equal(2); expect(reply.send).to.not.exist; reply('ok'); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.equal('ok'); done(); }); }); it('request has client address', function (done) { var handler = function (request, reply) { expect(request.info.remoteAddress).to.equal('127.0.0.1'); expect(request.info.remoteAddress).to.equal(request.info.remoteAddress); reply('ok'); }; var server = new Hapi.Server(0); server.route({ method: 'GET', path: '/', handler: handler }); server.start(function () { Nipple.get('http://localhost:' + server.info.port, function (err, res, body) { expect(body).to.equal('ok'); done(); }); }); }); it('request has referrer', function (done) { var server = new Hapi.Server(); var handler = function (request, reply) { expect(request.info.referrer).to.equal('http://site.com'); reply('ok'); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject({ url: '/', headers: { referrer: 'http://site.com' } }, function (res) { expect(res.result).to.equal('ok'); done(); }); }); it('request has referer', function (done) { var server = new Hapi.Server(); var handler = function (request, reply) { expect(request.info.referrer).to.equal('http://site.com'); reply('ok'); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject({ url: '/', headers: { referer: 'http://site.com' } }, function (res) { expect(res.result).to.equal('ok'); done(); }); }); it('returns 400 on invalid path', function (done) { var server = new Hapi.Server(); server.inject('invalid', function (res) { expect(res.statusCode).to.equal(400); done(); }); }); it('returns 403 on forbidden response', function (done) { var handler = function (request, reply) { reply(Hapi.error.forbidden('Unauthorized content')); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.statusCode).to.equal(403); done(); }); }); it('handles aborted requests', { parallel: false }, function (done) { var handler = function (request, reply) { var TestStream = function () { Stream.Readable.call(this); }; Hoek.inherits(TestStream, Stream.Readable); TestStream.prototype._read = function (size) { if (this.isDone) { return; } this.isDone = true; this.push('success'); this.emit('data', 'success'); }; var stream = new TestStream(); reply(stream); }; var server = new Hapi.Server(0); server.route({ method: 'GET', path: '/', handler: handler }); server.start(function () { var total = 2; var createConnection = function () { var client = Net.connect(server.info.port, function () { client.write('GET / HTTP/1.1\r\n\r\n'); client.write('GET / HTTP/1.1\r\n\r\n'); }); client.on('data', function () { total--; client.destroy(); }); }; var check = function () { if (total) { createConnection(); setImmediate(check); } else { done(); } }; check(); }); }); it('returns request header', function (done) { var handler = function (request, reply) { reply(request.headers['user-agent']); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.payload).to.equal('shot'); done(); }); }); it('parses nested query string', function (done) { var handler = function (request, reply) { reply(request.query); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/?a[b]=5&d[ff]=ok', function (res) { expect(res.result).to.deep.equal({ a: { b: '5' }, d: { ff: 'ok' } }); done(); }); }); it('returns empty params array when none present', function (done) { var handler = function (request, reply) { reply(request.params); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.deep.equal({}); done(); }); }); it('gunzips when parse=gunzip', function (done) { var zlib = require('zlib'); var msg = "hapi=joi"; var buf = new Buffer(msg, 'utf-8'); var handler = function (request, reply) { reply({ isBuffer: Buffer.isBuffer(request.payload), msg: request.payload.toString() }); }; var server = new Hapi.Server(); server.route({ method: 'POST', path: '/', config: { payload: { parse: 'gunzip' }, handler: handler } }); zlib.gzip(buf, function (err, gz_data) { server.inject({ method: 'POST', url: '/', payload: gz_data, headers: { 'Content-Encoding': 'gzip', 'Content-Type': 'application/x-www-form-urlencoded' } }, function (res) { expect(res.result.isBuffer).to.equal(true); expect(res.result.msg).to.equal(msg); done(); }); }); }); it('does not fail on abort', function (done) { var clientRequest; var handler = function (request, reply) { clientRequest.abort(); setTimeout(function () { reply(new Error('fail')); setTimeout(done, 10); }, 10); }; var server = new Hapi.Server(0); server.route({ method: 'GET', path: '/', handler: handler }); server.start(function () { clientRequest = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET' }); clientRequest.on('error', function () { /* NOP */ }); clientRequest.end(); }); }); it('does not fail on abort with ext', function (done) { var clientRequest; var handler = function (request, reply) { clientRequest.abort(); setTimeout(function () { reply(new Error('boom')); }, 10); }; var server = new Hapi.Server(0); server.route({ method: 'GET', path: '/', handler: handler }); server.ext('onPreResponse', function (request, reply) { return reply(); }); server.on('tail', function () { done(); }); server.start(function () { clientRequest = Http.request({ hostname: 'localhost', port: server.info.port, method: 'GET' }); clientRequest.on('error', function () { /* NOP */ }); clientRequest.end(); }); }); it('closes response after server timeout', function (done) { var handler = function (request, reply) { setTimeout(function () { var stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; stream.close = function () { done(); } reply(stream); }, 10) }; var server = new Hapi.Server({ timeout: { server: 5 } }); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.statusCode).to.equal(503); }); }); it('does not close error response after server timeout', function (done) { var handler = function (request, reply) { setTimeout(function () { reply(new Error('after')); }, 10) }; var server = new Hapi.Server({ timeout: { server: 5 } }); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.statusCode).to.equal(503); done(); }); }); describe('#setMethod', function () { it('changes method with a lowercase version of the value passed in', function (done) { var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: function (request, reply) { } }); server.ext('onRequest', function (request, reply) { request.setMethod('POST'); reply(request.method); }); server.inject('/', function (res) { expect(res.payload).to.equal('post'); done(); }); }); it('errors on missing method', function (done) { var server = new Hapi.Server({ debug: false }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { } }); server.ext('onRequest', function (request, reply) { request.setMethod(); }); server.inject('/', function (res) { expect(res.statusCode).to.equal(500); done(); }); }); it('errors on invalid method type', function (done) { var server = new Hapi.Server({ debug: false }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { } }); server.ext('onRequest', function (request, reply) { request.setMethod(42); }); server.inject('/', function (res) { expect(res.statusCode).to.equal(500); done(); }); }); }); describe('#setUrl', function () { it('sets url, path, and query', function (done) { var url = 'http://localhost/page?param1=something'; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: function (request, reply) { } }); server.ext('onRequest', function (request, reply) { request.setUrl(url); reply([request.url.href, request.path, request.query.param1].join('|')); }); server.inject('/', function (res) { expect(res.payload).to.equal(url + '|/page|something'); done(); }); }); it('normalizes a path', function (done) { var rawPath = '/%0%1%2%3%4%5%6%7%8%9%a%b%c%d%e%f%10%11%12%13%14%15%16%17%18%19%1a%1b%1c%1d%1e%1f%20%21%22%23%24%25%26%27%28%29%2a%2b%2c%2d%2e%2f%30%31%32%33%34%35%36%37%38%39%3a%3b%3c%3d%3e%3f%40%41%42%43%44%45%46%47%48%49%4a%4b%4c%4d%4e%4f%50%51%52%53%54%55%56%57%58%59%5a%5b%5c%5d%5e%5f%60%61%62%63%64%65%66%67%68%69%6a%6b%6c%6d%6e%6f%70%71%72%73%74%75%76%77%78%79%7a%7b%7c%7d%7e%7f%80%81%82%83%84%85%86%87%88%89%8a%8b%8c%8d%8e%8f%90%91%92%93%94%95%96%97%98%99%9a%9b%9c%9d%9e%9f%a0%a1%a2%a3%a4%a5%a6%a7%a8%a9%aa%ab%ac%ad%ae%af%b0%b1%b2%b3%b4%b5%b6%b7%b8%b9%ba%bb%bc%bd%be%bf%c0%c1%c2%c3%c4%c5%c6%c7%c8%c9%ca%cb%cc%cd%ce%cf%d0%d1%d2%d3%d4%d5%d6%d7%d8%d9%da%db%dc%dd%de%df%e0%e1%e2%e3%e4%e5%e6%e7%e8%e9%ea%eb%ec%ed%ee%ef%f0%f1%f2%f3%f4%f5%f6%f7%f8%f9%fa%fb%fc%fd%fe%ff%0%1%2%3%4%5%6%7%8%9%A%B%C%D%E%F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29%2A%2B%2C%2D%2E%2F%30%31%32%33%34%35%36%37%38%39%3A%3B%3C%3D%3E%3F%40%41%42%43%44%45%46%47%48%49%4A%4B%4C%4D%4E%4F%50%51%52%53%54%55%56%57%58%59%5A%5B%5C%5D%5E%5F%60%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F%70%71%72%73%74%75%76%77%78%79%7A%7B%7C%7D%7E%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF'; var normPath = '/%0%1%2%3%4%5%6%7%8%9%a%b%c%d%e%f%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&\'()*+,-.%2F0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF%0%1%2%3%4%5%6%7%8%9%A%B%C%D%E%F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20!%22%23$%25&\'()*+,-.%2F0123456789:;%3C=%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D~%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF'; var url = 'http://localhost' + rawPath + '?param1=something'; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: function (request, reply) { } }); server.ext('onRequest', function (request, reply) { request.setUrl(url); reply([request.url.href, request.path, request.query.param1].join('|')); }); server.inject('/', function (res) { expect(res.payload).to.equal(url + '|' + normPath + '|something'); done(); }); }); it('allows missing path', function (done) { var server = new Hapi.Server(); server.ext('onRequest', function (request, reply) { request.setUrl(''); reply(); }); server.inject('/', function (res) { expect(res.statusCode).to.equal(400); done(); }); }); it('strips trailing slash', function (done) { var server = new Hapi.Server({ router: { stripTrailingSlash: true } }); server.route({ method: 'GET', path: '/test', handler: function (request, reply) { reply(); } }); server.inject('/test/', function (res) { expect(res.statusCode).to.equal(200); done(); }); }) it('does not strip trailing slash on /', function (done) { var server = new Hapi.Server({ router: { stripTrailingSlash: true } }); server.route({ method: 'GET', path: '/', handler: function (request, reply) { reply(); } }); server.inject('/', function (res) { expect(res.statusCode).to.equal(200); done(); }); }) }); describe('#log', { parallel: false }, function () { it('outputs log data to debug console', function (done) { var handler = function (request, reply) { request.log(['implementation'], 'data'); reply(); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); var orig = console.error; console.error = function () { expect(arguments[0]).to.equal('Debug:'); expect(arguments[1]).to.equal('implementation'); expect(arguments[2]).to.equal('\n data'); console.error = orig; done(); }; server.inject('/', function (res) { expect(res.statusCode).to.equal(200); }); }); it('outputs log to debug console without data', function (done) { var handler = function (request, reply) { request.log(['implementation']); reply(); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); var orig = console.error; console.error = function () { expect(arguments[0]).to.equal('Debug:'); expect(arguments[1]).to.equal('implementation'); expect(arguments[2]).to.equal(''); console.error = orig; done(); }; server.inject('/', function (res) { expect(res.statusCode).to.equal(200); }); }); it('handles invalid log data object stringify', function (done) { var handler = function (request, reply) { var obj = {}; obj.a = obj; request.log(['implementation'], obj); reply(); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); var orig = console.error; console.error = function () { console.error = orig; expect(arguments[0]).to.equal('Debug:'); expect(arguments[1]).to.equal('implementation'); expect(arguments[2]).to.equal('\n [Cannot display object: Converting circular structure to JSON]'); done(); }; server.inject('/', function (res) { expect(res.statusCode).to.equal(200); }); }); it('adds a log event to the request', function (done) { var handler = function (request, reply) { request.log('1', 'log event 1', Date.now()); request.log(['2'], 'log event 2', new Date(Date.now())); request.log(['3', '4']); request.log(['1', '4']); request.log(['2', '3']); request.log(['4']); request.log('4'); reply([request.getLog('1').length, request.getLog('4').length, request.getLog(['4']).length, request.getLog('0').length, request.getLog(['1', '2', '3', '4']).length, request.getLog().length >= 7].join('|')); }; var server = new Hapi.Server(); server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.payload).to.equal('2|4|4|0|7|true'); done(); }); }); it('does not output events when debug disabled', function (done) { var server = new Hapi.Server({ debug: false }); var i = 0; var orig = console.error; console.error = function () { ++i; }; var handler = function (request, reply) { request.log(['implementation']); reply(); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { console.error('nothing'); expect(i).to.equal(1); console.error = orig; done(); }); }); it('does not output events when debug.request disabled', function (done) { var server = new Hapi.Server({ debug: { request: false } }); var i = 0; var orig = console.error; console.error = function () { ++i; }; var handler = function (request, reply) { request.log(['implementation']); reply(); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { console.error('nothing'); expect(i).to.equal(1); console.error = orig; done(); }); }); it('does not output non-implementation events by default', function (done) { var server = new Hapi.Server(); var i = 0; var orig = console.error; console.error = function () { ++i; }; var handler = function (request, reply) { request.log(['xyz']); reply(); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { console.error('nothing'); expect(i).to.equal(1); console.error = orig; done(); }); }); }); describe('#_setResponse', function () { it('leaves the response open when the same response is set again', function (done) { var server = new Hapi.Server(); server.ext('onPostHandler', function (request, reply) { reply(request.response); }); var handler = function (request, reply) { var stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; reply(stream); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.equal('value'); done(); }); }); it('leaves the response open when the same response source is set again', function (done) { var server = new Hapi.Server(); server.ext('onPostHandler', function (request, reply) { reply(request.response.source); }); var handler = function (request, reply) { var stream = new Stream.Readable(); stream._read = function (size) { this.push('value'); this.push(null); }; reply(stream); }; server.route({ method: 'GET', path: '/', handler: handler }); server.inject('/', function (res) { expect(res.result).to.equal('value'); done(); }); }); }); });
import React from 'react'; import * as R from 'ramda'; import { Link } from 'redux-little-router'; import PLAN_STATUS from '../../constants/plan-status'; import { formPlanIdentifierText, getPlanFileUrls, formPlanUrl, parseFileNameFromURL, versionToCharacter } from '../../utils'; /** * Form link elements for each file url * @private * @param {object} * @return {React.Element[]|string} */ const formPlanFileUrls = R.pipe( getPlanFileUrls, // eslint-disable-next-line react/no-array-index-key R.map((url, idx) => (<a key={`${url}_${idx}`} href={url} className="PlanListItem__fileUrl" target="_blank">{parseFileNameFromURL(url)}</a>)), R.defaultTo('-'), ); /** * Choose a correct component for indicating plan status * @param {object} props * @param {object} plan */ const PlanStatusIcon = ({ plan }) => { if (plan.maintenanceDuty) { return <i className="text-success fa fa-check-circle-o" />; } if (plan.status === PLAN_STATUS.APPROVED) { return <i className="text-success fa fa-check" />; } return <span>&nbsp;</span>; }; /** * Component for displaying project's plans as a list * @param {object} props * @param {object} props.plan * @param {number} props.projectId */ const PlanListItem = ({ plan = {}, project = {} }) => ( <li className="PlansListItem"> <div className="one column"><PlanStatusIcon plan={plan} /></div> <div className="three columns PlansListItem__identifier"> <Link href={formPlanUrl(project.projectId, plan.planId)}> {formPlanIdentifierText(plan)} </Link> </div> <div className="six columns">{formPlanFileUrls(plan)}</div> <div className="two columns">{versionToCharacter(plan.version)}</div> </li> ); export default PlanListItem;
// @flow import * as React from 'react'; import PropTypes from 'prop-types'; import styles from './IconButton.css'; import icons from './icons/index.js'; import Pog from './Pog.js'; type Props = {| accessibilityExpanded?: boolean, accessibilityHaspopup?: boolean, accessibilityLabel: string, bgColor?: 'transparent' | 'gray' | 'lightGray' | 'white', iconColor?: 'gray' | 'darkGray' | 'red' | 'blue' | 'white', icon: $Keys<typeof icons>, onClick?: ({ event: SyntheticMouseEvent<> }) => void, size?: 'xs' | 'sm' | 'md' | 'lg' | 'xl', |}; type State = {| active: boolean, focused: boolean, hovered: boolean, |}; export default class IconButton extends React.Component<Props, State> { static propTypes = { accessibilityExpanded: PropTypes.bool, accessibilityHaspopup: PropTypes.bool, accessibilityLabel: PropTypes.string.isRequired, bgColor: PropTypes.oneOf(['transparent', 'gray', 'lightGray', 'white']), icon: PropTypes.oneOf(Object.keys(icons)).isRequired, iconColor: PropTypes.oneOf(['gray', 'darkGray', 'red', 'blue', 'white']), onClick: PropTypes.func, size: PropTypes.oneOf(['xs', 'sm', 'md', 'lg', 'xl']), }; state: State = { active: false, focused: false, hovered: false, }; handleBlur = () => this.setState({ focused: false }); handleFocus = () => { this.setState({ focused: true }); }; handleMouseDown = () => { this.setState({ active: true }); }; handleMouseEnter = () => { this.setState({ hovered: true }); }; handleMouseLeave = () => { this.setState({ active: false, hovered: false, }); }; handleMouseUp = () => { this.setState({ active: false }); }; render() { const { accessibilityExpanded, accessibilityHaspopup, accessibilityLabel, bgColor, iconColor, icon, size, onClick, } = this.props; const { active, focused, hovered } = this.state; return ( <button aria-expanded={accessibilityExpanded} aria-haspopup={accessibilityHaspopup} aria-label={accessibilityLabel} className={styles.button} onBlur={this.handleBlur} onClick={event => onClick && onClick({ event })} onFocus={this.handleFocus} onMouseDown={this.handleMouseDown} onMouseEnter={this.handleMouseEnter} onMouseLeave={this.handleMouseLeave} onMouseUp={this.handleMouseUp} type="button" > <Pog active={active} bgColor={bgColor} focused={focused} hovered={hovered} iconColor={iconColor} icon={icon} size={size} /> </button> ); } }
import { useRef, useLayoutEffect } from 'react'; const isInBrowser = typeof window !== 'undefined'; function getMediaSizes () { if (!isInBrowser) { return { width: null, height: null, lg: null, md: null, sm: null, xs: null } } const width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; const height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight; const xl = width > 1200; const lg = width > 996 && width <= 1200; const md = width > 768 && width <= 996; const sm = width > 556 && width <= 768; const xs = width <= 556; return { width, height, xl, lg, md, sm, xs, }; } export default function useMediaQuery (effect) { const media = useRef(getMediaSizes()); function updateMediaQueryRef() { const currentMedia = getMediaSizes(); effect(currentMedia); media.current = currentMedia; } useLayoutEffect(() => { window.addEventListener('resize', () => updateMediaQueryRef()); return () => { window.removeEventListener('resize', () => updateMediaQueryRef()); }; }); }
'use strict'; /** * @ngdoc type * @name angular.Module * @module ng * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @module ng * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, filters, and configuration information. * `angular.module` is used to configure the {@link auto.$injector $injector}. * * ```js * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * ``` * * Then you can create an injector and load your modules like this: * * ```js * var injector = angular.injector(['ng', 'myModule']) * ``` * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If * unspecified then the module is being retrieved for further configuration. * @param {Function} configFn Optional configuration function for the module. Same as * {@link angular.Module#config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @module ng * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @module ng * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @module ng * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link auto.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @module ng * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link auto.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @module ng * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link auto.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @module ng * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link auto.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @module ng * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link auto.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @module ng * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * ```js * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * ``` * * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @module ng * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @module ng * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @module ng * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @module ng * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @module ng * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); }
dataset_maps = dict() """ each item in the dataset maps are a list of the following info ( dataset_folder, annotation file name (video dataset) / path of annotation file (image dataset), split file name (video dataset) / path of image folder (image dataset) , modality ) """ dataset_maps['TAO'] = ['TAO', 'anno_person.json', 'splits_person.json', 'video'] dataset_maps['CRP'] = ['caltech_roadside_pedestrians', 'anno.json', 'splits.json', 'video'] dataset_maps['MOT17_DPM'] = ['MOT17', 'anno.json', 'splits_DPM.json', 'video'] dataset_maps['MOT17'] = ['MOT17', 'anno.json', 'splits.json', 'video'] dataset_maps['AOT'] = ['airbone_object_tracking', 'anno.json', 'splits.json', 'video'] dataset_maps['COCO17_train'] = ['mscoco', 'annotations/MSCOCO2017_train_person.json', 'images/train2017', # all raw images would be in dataset_root/mscoco/images/train2017 'image'] dataset_maps['crowdhuman_train_fbox'] = ['CrowdHuman', 'annotations/annotation_train_fbox.json', 'Images', # all raw images would be in dataset_root/CrowdHuman/Images 'image'] dataset_maps['crowdhuman_train_vbox'] = ['CrowdHuman', 'annotations/annotation_train_vbox.json', 'Images', 'image'] dataset_maps['crowdhuman_val_fbox'] = ['CrowdHuman', 'annotations/annotation_val_fbox.json', 'Images', 'image'] dataset_maps['crowdhuman_val_vbox'] = ['CrowdHuman', 'annotations/annotation_val_vbox.json', 'Images', 'image']
function Drb(){} function Grb(){} function YQb(){} function cRb(){} function vRb(){vRb=yAc;XQb=new cRb} function Irb(){Irb=yAc;Crb=new Grb} function srb(a,b){this.b=a;this.c=b} function uRb(){uRb=yAc;WQb=new bgb((Tgb(),new Lgb((FF(),PGc))),82,26)} function Arb(a){this.f=a;this.g=(new Drb,Irb(),Crb);Frb(this.g);this.b=us($doc);this.d=us($doc);this.c=new rIb(this.b);this.e=new rIb(this.d)} function orb(a){var b,c,d;c=new Snc((elb(),clb));Hnc(c,new srb(a,c));b=new YQb;a.b=new lPb(new Wlb(c),b);jPb(a.b,true);d=zrb(new Arb(a));return d} function Frb(a){if(!a.b){a.b=true;Qw((FF(),'.GNHGC04COJ{width:500px;border:1px solid #ccc;}.GNHGC04CNJ{padding-left:15px;}'));return true}return false} function Jrb(a,b,c){var d;d=new Hrc;d.b.b+="<table> <tr> <td valign='top'> <span id='";Brc(d,Hgb(a));d.b.b+="'><\/span> <\/td> <td valign='top'> <b> ";Brc(d,b.b);d.b.b+=gNc;Brc(d,Hgb(c));d.b.b+=OMc;return new mgb(d.b.b)} function zrb(a){var b,c,d,e;c=new f6b(Jrb(a.b,(Ggb(),new wgb(fNc)),a.d).b);b=tIb(c.db);qIb(a.c);qIb(a.e);b.c?Hr(b.c,b.b,b.d):wIb(b.b);d6b(c,(d=a.f.b,pj(d.db,'GNHGC04COJ',true),d),qIb(a.c));d6b(c,(e=new M2b,pj(e.db,'GNHGC04CNJ',true),a.f.c=e,e),qIb(a.e));return c} function rRb(){rRb=yAc;TQb=new bgb((Tgb(),new Lgb((FF(),'data:image/gif;base64,R0lGODlhDwAPAIQaAFhorldnrquz1mFxsvz9/vr6/M3Q2ZGbw5mixvb3+Gp5t2Nys77F4GRzs9ze4mt6uGV1s8/R2VZnrl5usFdortPV2/P09+3u8eXm6lZnrf///wAAzP///////////////yH5BAEAAB8ALAAAAAAPAA8AAAVD4CeOZGmeaEoqWds+58IUWk0IgwlY/MYnEhPlQtwQL8ESBbNpNjEZIWa6mUJNAQfVGi1NEJGK2HCYnCCuVkPFbrtHIQA7'))),15,15)} function tRb(){tRb=yAc;VQb=new bgb((Tgb(),new Lgb((FF(),'data:image/gif;base64,R0lGODlhDwAPAIQaAFhorldnrquz1mFxsvz9/vr6/M3Q2ZGbw5mixvb3+Gp5t2Nys77F4GRzs9ze4mt6uGV1s8/R2VZnrl5usFdortPV2/P09+3u8eXm6lZnrf///wAAzP///////////////yH5BAEAAB8ALAAAAAAPAA8AAAVC4CeOZGmeaEoqWds+58IUWk0IgwlY/MUnEhPlQixegiUKZsNkYjJCjPQifZoCjmkVWpogIpWw4TA5QVythmrNbo9CADs='))),15,15)} function sRb(){sRb=yAc;UQb=new bgb((Tgb(),new Lgb((FF(),'data:image/gif;base64,R0lGODlhEAAQAPYAAP///wAAzNTU9ZSU6WBg3kBA2ERE2W5u4aKi69zc96Sk7CQk0ygo0zAw1TY21j4+2Gpq4Lq68Bwc0XJy4uzs+u7u+sLC8oqK51BQ215e3r6+8dDQ9Do61xYW0IyM56qq7Vxc3nx85OLi+IaG5g4Ozmho4Jyc6mZm4La270ZG2QoKzbCw7paW6RgY0AYGzejo+fT0/Hh444SE5fb2/IKC5aio7fr6/fz8/cDA8crK8/j4/NbW9q6u7vDw+9LS9eTk+N7e987O9MbG8ry88eDg+NjY9vLy+9ra9np65LS077Ky70xM2lJS3Fpa3WJi30JC2Dw818TE8nZ24zIy1erq+ioq1I6O51hY3Sws1B4e0aCg605O2xISz4iI5mRk3zQ01sjI88zM9Obm+bi48H5+5JKS6J6e61ZW3JCQ6EpK2khI2iIi0qam7BAQzwwMzqys7QQEzJqa6iYm0xQUzzg413R04i4u1QgIzXBw4iAg0lRU3Gxs4YCA5QAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAAHjYAAgoOEhYUbIykthoUIHCQqLoI2OjeFCgsdJSsvgjcwPTaDAgYSHoY2FBSWAAMLE4wAPT89ggQMEbEzQD+CBQ0UsQA7RYIGDhWxN0E+ggcPFrEUQjuCCAYXsT5DRIIJEBgfhjsrFkaDERkgJhswMwk4CDzdhBohJwcxNB4sPAmMIlCwkOGhRo5gwhIGAgAh+QQJCgAAACwAAAAAEAAQAAAHjIAAgoOEhYU7A1dYDFtdG4YAPBhVC1ktXCRfJoVKT1NIERRUSl4qXIRHBFCbhTKFCgYjkII3g0hLUbMAOjaCBEw9ukZGgidNxLMUFYIXTkGzOmLLAEkQCLNUQMEAPxdSGoYvAkS9gjkyNEkJOjovRWAb04NBJlYsWh9KQ2FUkFQ5SWqsEJIAhq6DAAIBACH5BAkKAAAALAAAAAAQABAAAAeJgACCg4SFhQkKE2kGXiwChgBDB0sGDw4NDGpshTheZ2hRFRVDUmsMCIMiZE48hmgtUBuCYxBmkAAQbV2CLBM+t0puaoIySDC3VC4tgh40M7eFNRdH0IRgZUO3NjqDFB9mv4U6Pc+DRzUfQVQ3NzAULxU2hUBDKENCQTtAL9yGRgkbcvggEq9atUAAIfkECQoAAAAsAAAAABAAEAAAB4+AAIKDhIWFPygeEE4hbEeGADkXBycZZ1tqTkqFQSNIbBtGPUJdD088g1QmMjiGZl9MO4I5ViiQAEgMA4JKLAm3EWtXgmxmOrcUElWCb2zHkFQdcoIWPGK3Sm1LgkcoPrdOKiOCRmA4IpBwDUGDL2A5IjCCN/QAcYUURQIJIlQ9MzZu6aAgRgwFGAFvKRwUCAAh+QQJCgAAACwAAAAAEAAQAAAHjIAAgoOEhYUUYW9lHiYRP4YACStxZRc0SBMyFoVEPAoWQDMzAgolEBqDRjg8O4ZKIBNAgkBjG5AAZVtsgj44VLdCanWCYUI3txUPS7xBx5AVDgazAjC3Q3ZeghUJv5B1cgOCNmI/1YUeWSkCgzNUFDODKydzCwqFNkYwOoIubnQIt244MzDC1q2DggIBACH5BAkKAAAALAAAAAAQABAAAAeJgACCg4SFhTBAOSgrEUEUhgBUQThjSh8IcQo+hRUbYEdUNjoiGlZWQYM2QD4vhkI0ZWKCPQmtkG9SEYJURDOQAD4HaLuyv0ZeB4IVj8ZNJ4IwRje/QkxkgjYz05BdamyDN9uFJg9OR4YEK1RUYzFTT0qGdnduXC1Zchg8kEEjaQsMzpTZ8avgoEAAIfkECQoAAAAsAAAAABAAEAAAB4iAAIKDhIWFNz0/Oz47IjCGADpURAkCQUI4USKFNhUvFTMANxU7KElAhDA9OoZHH0oVgjczrJBRZkGyNpCCRCw8vIUzHmXBhDM0HoIGLsCQAjEmgjIqXrxaBxGCGw5cF4Y8TnybglprLXhjFBUWVnpeOIUIT3lydg4PantDz2UZDwYOIEhgzFggACH5BAkKAAAALAAAAAAQABAAAAeLgACCg4SFhjc6RhUVRjaGgzYzRhRiREQ9hSaGOhRFOxSDQQ0uj1RBPjOCIypOjwAJFkSCSyQrrhRDOYILXFSuNkpjggwtvo86H7YAZ1korkRaEYJlC3WuESxBggJLWHGGFhcIxgBvUHQyUT1GQWwhFxuFKyBPakxNXgceYY9HCDEZTlxA8cOVwUGBAAA7AAAAAAAAAAAA'))),16,16)} cfb(580,1,pBc,srb);_.Ve=function trb(a){var b,c,d,e,f;c=new Hrc;b=true;d=new Pvc(Pnc(this.c));uwc(d);for(f=new Ruc(d);f.c<f.e.ue();){e=MU(Puc(f),74);b?(b=false):(c.b.b+=QEc,c);Brc(c,e.f+mCc+e.i)}K2b(this.b.c,c.b.b)};_.b=null;_.c=null;cfb(581,1,tBc);_.qc=function xrb(){Hhb(this.c,orb(this.b))};cfb(582,1,{},Arb);_.b=null;_.c=null;_.d=null;_.e=null;_.f=null;_.g=null;cfb(583,1,{},Drb);var Crb=null;cfb(584,1,{},Grb);_.Me=function Hrb(){return Frb(this)};_.b=false;cfb(904,1,{},YQb);_.vg=function ZQb(){return rRb(),TQb};_.wg=function $Qb(){return sRb(),UQb};_.xg=function _Qb(){return tRb(),VQb};_.yg=function aRb(){return vRb(),XQb};var TQb=null,UQb=null,VQb=null,WQb=null,XQb=null;cfb(905,1,{},cRb);_.zg=function dRb(){return 'GNHGC04CJE'};_.Ag=function eRb(){return 'GNHGC04CKE'};_.Bg=function fRb(){return 'GNHGC04CLE'};_.Cg=function gRb(){return 'GNHGC04CME'};_.Dg=function hRb(){return 'GNHGC04CNE'};_.Eg=function iRb(){return 'GNHGC04COE'};_.Fg=function jRb(){return 'GNHGC04CPE'};_.Gg=function kRb(){return 'GNHGC04CAF'};_.Hg=function lRb(){return 'GNHGC04CBF'};_.Ig=function mRb(){return 'GNHGC04CCF'};_.Jg=function nRb(){return 'GNHGC04CDF'};_.Kg=function oRb(){return 'GNHGC04CEF'};_.Lg=function pRb(){return 'GNHGC04CFF'};_.Me=function qRb(){if(!this.b){this.b=true;Qw((FF(),'.GNHGC04CJE{padding-left:16px;font-style:italic;}.GNHGC04CKE{padding-top:4px;padding-bottom:4px;cursor:hand;cursor:pointer;zoom:1;}.GNHGC04CME{zoom:1;}.GNHGC04CNE{padding-left:3px;padding-right:3px;outline:none;}.GNHGC04COE{background-color:#ffc;outline:none;}.GNHGC04CAF{height:'+(uRb(),WQb.b)+MGc+WQb.e.b+NGc+WQb.c+OGc+WQb.d+'px repeat-x;background-color:#628cd5;color:white;height:auto;overflow:visible;}.GNHGC04CBF{padding-left:16px;outline:none;}'));return true}return false};_.b=false;var r1=Hpc(wIc,'CwCellTree$1',580),m6=Hpc(yIc,'CellTree_BasicResources_fr_InlineClientBundleGenerator',904),l6=Hpc(yIc,'CellTree_BasicResources_fr_InlineClientBundleGenerator$1',905),t1=Hpc(wIc,'CwCellTree_BinderImpl$Widgets',582),v1=Hpc(wIc,'CwCellTree_BinderImpl_GenBundle_fr_InlineClientBundleGenerator',583),u1=Hpc(wIc,'CwCellTree_BinderImpl_GenBundle_fr_InlineClientBundleGenerator$1',584);gCc(Jn)(40);
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Setup file for jinja_helper. This file was generated with PyScaffold 3.0.3. PyScaffold helps you to put up the scaffold of your new Python project. Learn more under: http://pyscaffold.org/ """ import sys from setuptools import setup # Add here console scripts and other entry points in ini-style format entry_points = """ [console_scripts] # script_name = jinja_helper.module:function # For example: # fibonacci = jinja_helper.skeleton:run jinja-helper = jinja_helper.cli:main """ def setup_package(): needs_sphinx = {'build_sphinx', 'upload_docs'}.intersection(sys.argv) sphinx = ['sphinx'] if needs_sphinx else [] setup(setup_requires=['pyscaffold>=3.0a0,<3.1a0'] + sphinx, entry_points=entry_points, use_pyscaffold=True) if __name__ == "__main__": setup_package()
#!/usr/bin/env node var path = require('path'), fs = require('fs'), extend = require('util')._extend, exec = require('child_process').exec, processes = []; var baseDir = path.resolve(__dirname, '..'), srcDir = baseDir, chimpBin = path.resolve(baseDir, 'node_modules/.bin/chimp'); var appOptions = { port: 3000, env: { ROOT_URL: 'http://localhost:3000/', VELOCITY: 1 } }; var mirrorOptions = { port: 3100, env: { IS_MIRROR: 1, MONGO_URL: 'mongodb://localhost:' + 3001 + '/chimp_db', ROOT_URL: 'http://localhost:3100/' }, logFile: './chimp-mirror.log' }; var chimpSwitches = ' --path=' + path.resolve('tests/features') + ' -r=' + path.resolve('tests/features/step_definitions'); if (process.env.CI || process.env.TRAVIS || process.env.CIRCLECI) { // when not in Watch mode, Chimp existing will exit Meteor too // we also don't need Velocity for the app chimp will run against appOptions.env.VELOCITY = 0; } else { chimpSwitches += ' --watch'; } if (process.env.SIMIAN_API && process.env.SIMIAN_REPOSITORY) { chimpSwitches += ' --simianRepositoryId=' + process.env.SIMIAN_REPOSITORY; chimpSwitches += ' --simianAccessToken=' + process.env.SIMIAN_API; } // set this flag to start with a mirror locally (ala Velocity xolvio:cucumber style) if (process.env.WITH_MIRROR) { chimpWithMirror(); } else if (process.env.NO_METEOR) { startChimp('--ddp=' + appOptions.env.ROOT_URL + chimpSwitches); } else { chimpNoMirror(); } // ************************************************* function chimpWithMirror() { appOptions.waitForMessage = 'Started MongoDB'; startApp(function () { startMirror(function () { console.log('=> Test App running at:', mirrorOptions.env.ROOT_URL); console.log('=> Log file: tail -f', path.resolve(mirrorOptions.logFile), '\n'); startChimp('--ddp=' + mirrorOptions.env.ROOT_URL + chimpSwitches ) }); }); } function chimpNoMirror() { appOptions.waitForMessage = 'App running at'; startApp(function () { startChimp('--ddp=' + appOptions.env.ROOT_URL + chimpSwitches); }); } function startApp(callback) { startProcess({ name: 'Meteor App', command: 'meteor --port ' + appOptions.port, waitForMessage: appOptions.waitForMessage, options: { cwd: srcDir, env: extend(appOptions.env, process.env) } }, callback); } function startMirror(callback) { startProcess({ name: 'Meteor Mirror', command: 'meteor --port ' + mirrorOptions.port, silent: true, logFile: mirrorOptions.logFile, waitForMessage: 'App running at', options: { cwd: srcDir, env: extend(mirrorOptions.env, process.env) } }, callback); } function startChimp(command) { startProcess({ name: 'Chimp', command: chimpBin + ' ' + command }); } function startProcess(opts, callback) { var proc = exec( opts.command, opts.options ); if (opts.waitForMessage) { proc.stdout.on('data', function waitForMessage(data) { if (data.toString().match(opts.waitForMessage)) { if (callback) { callback(); } } }); } if (!opts.silent) { proc.stdout.pipe(process.stdout); proc.stderr.pipe(process.stderr); } if (opts.logFile) { var logStream = fs.createWriteStream(opts.logFile, {flags: 'a'}); proc.stdout.pipe(logStream); proc.stderr.pipe(logStream); } proc.on('close', function (code) { console.log(opts.name, 'exited with code ' + code); for (var i = 0; i < processes.length; i += 1) { processes[i].kill(); } process.exit(code); }); processes.push(proc); }
#!/bin/bash # use strict mode: http://redsymbol.net/articles/unofficial-bash-strict-mode/ set -xeuo pipefail
# -*- coding: utf-8 -*- # vim: set ts=4 sw=4 et ai: """ | This file is part of the web2py Web Framework | Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> | License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) Command line interface ---------------------- The processing of all command line arguments is done using the argparse library in the console function. The basic principle is to process and check for all options in a single place, this place is the parse_args function. Notice that when I say all options I mean really all, options sourced from a configuration file are included. A brief summary of options style follows, for the benefit of code maintainers/developers: - use the underscore to split words in long names (as in '--run_system_tests') - remember to allow the '-' too as word separator (e.g. '--run-system-tests') but do not use this form on help - prefer short names on help messages, instead use all options names in warning/error messages (e.g. '-R/--run requires -S/--shell') """ from __future__ import print_function __author__ = 'Paolo Pastori' import os.path import argparse import logging import socket import sys import re import ast from collections import OrderedDict import copy from gluon._compat import PY2 from gluon.shell import die from gluon.utils import is_valid_ip_address from gluon.settings import global_settings def warn(msg): print("%s: warning: %s" % (sys.argv[0], msg), file=sys.stderr) def is_appdir(applications_parent, app): return os.path.isdir(os.path.join(applications_parent, 'applications', app)) def console(version): """ Load command line options. Trivial -h/--help and --version options are also processed. Returns a namespace object (in the sense of argparse) with all options loaded. """ # replacement hints for deprecated options deprecated_opts = { '--debug': '--log_level', '--nogui': '--no_gui', '--ssl_private_key': '--server_key', '--ssl_certificate': '--server_cert', '--interfaces': None, # dest is 'interfaces', hint is '--interface' '-n': '--min_threads', '--numthreads': '--min_threads', '--minthreads': '--min_threads', '--maxthreads': '--max_threads', '-z': None, '--shutdown_timeout': None, '--profiler': '--profiler_dir', '--run-cron': '--with_cron', '--softcron': '--soft_cron', '--cron': '--cron_run', '--test': '--run_doctests' } class HelpFormatter2(argparse.HelpFormatter): """Hides the options listed in _hidden_options in usage help.""" # NOTE: preferred style for long options name is to use '_' # between words (as in 'no_gui'), also accept the '-' in # most of the options but do not show both versions on help _omitted_opts = ('--add-options', '--errors-to-console', '--no-banner', '--log-level', '--no-gui', '--import-models', '--server-name', '--server-key', '--server-cert', '--ca-cert', '--pid-filename', '--log-filename', '--min-threads', '--max-threads', '--request-queue-size', '--socket-timeout', '--profiler-dir', '--with-scheduler', '--with-cron', '--soft-cron', '--cron-run', '--run-doctests', '--run-system-tests', '--with-coverage') _hidden_options = _omitted_opts + tuple(deprecated_opts.keys()) def _format_action_invocation(self, action): if not action.option_strings: return super(HelpFormatter2, self)._format_action_invocation(action) parts = [] if action.nargs == 0: parts.extend(filter(lambda o : o not in self._hidden_options, action.option_strings)) else: default = action.dest.upper() args_string = self._format_args(action, default) for option_string in action.option_strings: if option_string in self._hidden_options: continue parts.append('%s %s' % (option_string, args_string)) return ', '.join(parts) class ExtendAction(argparse._AppendAction): """Action to accumulate values in a flat list.""" def __call__(self, parser, namespace, values, option_string=None): if isinstance(values, list): # must copy to avoid altering the option default value value = getattr(namespace, self.dest, None) if value is None: value = [] setattr(namespace, self.dest, value) items = value[:] # for options that allows multiple args (i.e. those declared # with add_argument(..., nargs='+', ...)) the values are # always placed into a list while len(values) == 1 and isinstance(values[0], list): values = values[0] items.extend(values) setattr(namespace, self.dest, items) else: super(ExtendAction, self).__call__(parser, namespace, values, option_string) parser = argparse.ArgumentParser( usage='python %(prog)s [options]', description='web2py Web Framework startup script.', epilog='''NOTE: unless a password is specified (-a 'passwd') web2py will attempt to run a GUI to ask for it when starting the web server (if not disabled with --no_gui).''', formatter_class=HelpFormatter2, add_help=False) # do not add -h/--help option # global options g = parser.add_argument_group('global options') g.add_argument('-h', '--help', action='help', help='show this help message and exit') g.add_argument('--version', action='version', version=version, help="show program's version and exit") folder = os.getcwd() g.add_argument('-f', '--folder', default=folder, metavar='WEB2PY_DIR', help='web2py installation directory (%(default)s)') def existing_file(v): if not v: raise argparse.ArgumentTypeError('empty argument') if not os.path.exists(v): raise argparse.ArgumentTypeError("file %r not found" % v) return v g.add_argument('-L', '--config', type=existing_file, metavar='PYTHON_FILE', help='read all options from PYTHON_FILE') g.add_argument('--add_options', '--add-options', default=False, action='store_true', help= 'add options to existing ones, useful with -L only') g.add_argument('-a', '--password', default='<ask>', help= 'password to be used for administration (use "<recycle>" ' 'to reuse the last password), when no password is available ' 'the administrative web interface will be disabled') g.add_argument('-e', '--errors_to_console', '--errors-to-console', default=False, action='store_true', help='log application errors to console') g.add_argument('--no_banner', '--no-banner', default=False, action='store_true', help='do not print header banner') g.add_argument('-Q', '--quiet', default=False, action='store_true', help='disable all output') integer_log_level = [] def log_level(v): # try to convert a lgging level name to its numeric value, # could use logging.getLevelName but not with # 3.4 <= Python < 3.4.2, see # https://docs.python.org/3/library/logging.html#logging.getLevelName) try: name2level = logging._levelNames except AttributeError: # logging._levelNames has gone with Python 3.4, see # https://github.com/python/cpython/commit/3b84eae03ebd8122fdbdced3d85999dd9aedfc7e name2level = logging._nameToLevel try: return name2level[v.upper()] except KeyError: pass try: ill = int(v) # value deprecated: integer in range(101) if 0 <= ill <= 100: integer_log_level.append(ill) return ill except ValueError: pass raise argparse.ArgumentTypeError("bad level %r" % v) g.add_argument('-D', '--log_level', '--log-level', '--debug', # deprecated default='WARNING', type=log_level, metavar='LOG_LEVEL', help= 'set log level, allowed values are: NOTSET, DEBUG, INFO, WARN, ' 'WARNING, ERROR, and CRITICAL, also lowercase (default is ' '%(default)s)') # GUI options g = parser.add_argument_group('GUI options') g.add_argument('--no_gui', '--no-gui', '--nogui', # deprecated default=False, action='store_true', help='do not run GUI') g.add_argument('-t', '--taskbar', default=False, action='store_true', help='run in taskbar (system tray)') # console options g = parser.add_argument_group('console options') g.add_argument('-S', '--shell', metavar='APP_ENV', help= 'run web2py in Python interactive shell or IPython (if installed) ' 'with specified application environment (if application does not ' 'exist it will be created). APP_ENV like a/c/f?x=y (c, f and vars ' 'optional), if APP_ENV include the action f then after the ' 'action execution the interpreter is exited') g.add_argument('-B', '--bpython', default=False, action='store_true', help= 'use bpython (if installed) when running in interactive shell, ' 'see -S above') g.add_argument('-P', '--plain', default=False, action='store_true', help= 'use plain Python shell when running in interactive shell, ' 'see -S above') g.add_argument('-M', '--import_models', '--import-models', default=False, action='store_true', help= 'auto import model files when running in interactive shell ' '(default is %(default)s), see -S above. NOTE: when the APP_ENV ' 'argument of -S include a controller c automatic import of ' 'models is always enabled') g.add_argument('-R', '--run', type=existing_file, metavar='PYTHON_FILE', help= 'run PYTHON_FILE in web2py environment; require -S') g.add_argument('-A', '--args', default=[], nargs=argparse.REMAINDER, help= 'use this to pass arguments to the PYTHON_FILE above; require ' '-R. NOTE: must be the last option because eat all remaining ' 'arguments') # web server options g = parser.add_argument_group('web server options') g.add_argument('-s', '--server_name', '--server-name', default=socket.gethostname(), help='web server name (%(default)s)') def ip_addr(v): if not is_valid_ip_address(v): raise argparse.ArgumentTypeError("bad IP address %s" % v) return v g.add_argument('-i', '--ip', default='127.0.0.1', type=ip_addr, metavar='IP_ADDR', help= 'IP address of the server (%(default)s), accept either IPv4 or ' 'IPv6 (e.g. ::1) addresses. NOTE: this option is ignored if ' '--interface is specified') def not_negative_int(v, err_label='value'): try: iv = int(v) if iv < 0: raise ValueError() return iv except ValueError: pass raise argparse.ArgumentTypeError("bad %s %s" % (err_label, v)) def port(v): return not_negative_int(v, err_label='port') g.add_argument('-p', '--port', default=8000, type=port, metavar='NUM', help= 'port of server (%(default)d). ' 'NOTE: this option is ignored if --interface is specified') g.add_argument('-k', '--server_key', '--server-key', '--ssl_private_key', # deprecated type=existing_file, metavar='FILE', help='server private key') g.add_argument('-c', '--server_cert', '--server-cert', '--ssl_certificate', # deprecated type=existing_file, metavar='FILE', help='server certificate') g.add_argument('--ca_cert', '--ca-cert', type=existing_file, metavar='FILE', help='CA certificate') def iface(v, sep=','): if not v: raise argparse.ArgumentTypeError('empty argument') if sep == ':': # deprecated --interfaces ip:port:key:cert:ca_cert # IPv6 addresses in square brackets if v.startswith('['): # IPv6 ip, v_remainder = v.split(']', 1) ip = ip[1:] ifp = v_remainder[1:].split(':') ifp.insert(0, ip) else: # IPv4 ifp = v.split(':') else: # --interface ifp = v.split(sep, 5) if not len(ifp) in (2, 4, 5): raise argparse.ArgumentTypeError("bad interface %r" % v) try: ip_addr(ifp[0]) ifp[1] = port(ifp[1]) for fv in ifp[2:]: existing_file(fv) except argparse.ArgumentTypeError as ex: raise argparse.ArgumentTypeError("bad interface %r (%s)" % (v, ex)) return tuple(ifp) g.add_argument('--interface', dest='interfaces', default=[], action=ExtendAction, type=iface, nargs='+', metavar='IF_INFO', help= 'listen on specified interface, IF_INFO = ' 'IP_ADDR,PORT[,KEY_FILE,CERT_FILE[,CA_CERT_FILE]].' ' NOTE: this option can be used multiple times to provide additional ' 'interfaces to choose from but you can choose which one to listen to ' 'only using the GUI otherwise the first interface specified is used') def ifaces(v): # deprecated --interfaces 'if1;if2;...' if not v: raise argparse.ArgumentTypeError('empty argument') return [iface(i, ':') for i in v.split(';')] g.add_argument('--interfaces', # deprecated default=argparse.SUPPRESS, # do not set if absent action=ExtendAction, type=ifaces, help=argparse.SUPPRESS) # do not show on help g.add_argument('-d', '--pid_filename', '--pid-filename', default='httpserver.pid', metavar='FILE', help='server pid file (%(default)s)') g.add_argument('-l', '--log_filename', '--log-filename', default='httpserver.log', metavar='FILE', help='server log file (%(default)s)') g.add_argument('--min_threads', '--min-threads', '--minthreads', '-n', '--numthreads', # deprecated type=not_negative_int, metavar='NUM', help='minimum number of server threads') g.add_argument('--max_threads', '--max-threads', '--maxthreads', # deprecated type=not_negative_int, metavar='NUM', help='maximum number of server threads') g.add_argument('-q', '--request_queue_size', '--request-queue-size', default=5, type=not_negative_int, metavar='NUM', help= 'max number of queued requests when server busy (%(default)d)') g.add_argument('-o', '--timeout', default=10, type=not_negative_int, metavar='SECONDS', help='timeout for individual request (%(default)d seconds)') g.add_argument('--socket_timeout', '--socket-timeout', default=5, type=not_negative_int, metavar='SECONDS', help='timeout for socket (%(default)d seconds)') g.add_argument('-z', '--shutdown_timeout', # deprecated type=not_negative_int, help=argparse.SUPPRESS) # do not show on help g.add_argument('-F', '--profiler_dir', '--profiler-dir', '--profiler', # deprecated help='profiler directory') # scheduler options g = parser.add_argument_group('scheduler options') g.add_argument('-X', '--with_scheduler', '--with-scheduler', default=False, action='store_true', help= 'run schedulers alongside web server; require --K') def is_app(app): return is_appdir(folder, app) def scheduler(v): if not v: raise argparse.ArgumentTypeError('empty argument') if ',' in v: # legacy "app1,..." vl = [n.strip() for n in v.split(',')] return [scheduler(iv) for iv in vl] vp = [n.strip() for n in v.split(':')] app = vp[0] if not app: raise argparse.ArgumentTypeError('empty application') if not is_app(app): warn("argument -K/--scheduler: bad application %r, skipped" % app) return None return ':'.join(filter(None, vp)) g.add_argument('-K', '--scheduler', dest='schedulers', default=[], action=ExtendAction, type=scheduler, nargs='+', metavar='APP_INFO', help= 'run scheduler for the specified application(s), APP_INFO = ' 'APP_NAME[:GROUPS], that is an optional list of groups can follow ' 'the application name (e.g. app:group1:group2); require a scheduler ' "to be defined in the application's models. NOTE: this option can " 'be used multiple times to add schedulers') # cron options g = parser.add_argument_group('cron options') g.add_argument('-Y', '--with_cron', '--with-cron', '--run-cron', # deprecated default=False, action='store_true', help= 'run cron service alongside web server') def crontab(v): if not v: raise argparse.ArgumentTypeError('empty argument') if not is_app(v): warn("argument --crontab: bad application %r, skipped" % v) return None return v g.add_argument('--crontab', dest='crontabs', default=[], action=ExtendAction, type=crontab, nargs='+', metavar='APP_NAME', help= 'tell cron to read the crontab for the specified application(s) ' 'only, the default behaviour is to read the crontab for all of the ' 'installed applications. NOTE: this option can be used multiple ' 'times to build the list of crontabs to be processed by cron') g.add_argument('--soft_cron', '--soft-cron', '--softcron', # deprecated default=False, action='store_true', help= 'use cron software emulation instead of separate cron process; ' 'require -Y. NOTE: use of cron software emulation is strongly ' 'discouraged') g.add_argument('-C', '--cron_run', '--cron-run', '--cron', # deprecated default=False, action='store_true', help= 'trigger a cron run and exit; usually used when invoked ' 'from a system (external) crontab') g.add_argument('--cron_job', # NOTE: this is intended for internal use only default=False, action='store_true', help=argparse.SUPPRESS) # do not show on help # test options g = parser.add_argument_group('test options') g.add_argument('-v', '--verbose', default=False, action='store_true', help='increase verbosity') g.add_argument('-T', '--run_doctests', '--run-doctests', '--test', # deprecated metavar='APP_ENV', help= 'run doctests in application environment. APP_ENV like a/c/f (c, f ' 'optional)') g.add_argument('--run_system_tests', '--run-system-tests', default=False, action='store_true', help='run web2py test suite') g.add_argument('--with_coverage', '--with-coverage', default=False, action='store_true', help= 'collect coverage data when used with --run_system_tests; ' 'require Python 2.7+ and the coverage module installed') # other options g = parser.add_argument_group('other options') g.add_argument('-G', '--GAE', dest='gae', metavar='APP_NAME', help= 'will create app.yaml and gaehandler.py and exit') options = parse_args(parser, sys.argv[1:], deprecated_opts, integer_log_level) # make a copy of all options for global_settings copy_options = copy.deepcopy(options) copy_options.password = '******' global_settings.cmd_options = copy_options return options REGEX_PEP263 = r'^[ \t\f]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)' def get_pep263_encoding(source): """ Read python source file encoding, according to PEP 263, see https://www.python.org/dev/peps/pep-0263/ """ with open(source, 'r') as sf: l12 = (sf.readline(), sf.readline()) m12 = re.match(REGEX_PEP263, l12[0]) or re.match(REGEX_PEP263, l12[1]) return m12 and m12.group(1) IGNORE = lambda: None def load_config(config_file, opt_map): """ Load options from config file (a Python script). config_file(str): file name opt_map(dict): mapping fom option name (key) to callable (val), used to post-process parsed value for the option Notice that the configuring Python script is never executed/imported, instead the ast library is used to evaluate each option assignment, provided that it is written on a single line. Returns an OrderedDict with sourced options. """ REGEX_ASSIGN_EXP = re.compile(r'\s*=\s*(.+)') map_items = opt_map.items() # preserve the order of loaded options even though this is not needed pl = OrderedDict() config_encoding = get_pep263_encoding(config_file) # NOTE: assume 'ascii' encoding when not explicitly stated (Python 2), # this is not correct for Python 3 where the default is 'utf-8' open_kwargs = dict() if PY2 else dict(encoding=config_encoding or 'ascii') with open(config_file, 'r', **open_kwargs) as cfil: for linenum, clin in enumerate(cfil, start=1): if PY2 and config_encoding: clin = unicode(clin, config_encoding) clin = clin.strip() for opt, mapr in map_items: if clin.startswith(opt): m = REGEX_ASSIGN_EXP.match(clin[len(opt):]) if m is None: continue try: val = opt_map[opt](ast.literal_eval(m.group(1))) except: die("cannot parse config file %r at line %d" % (config_file, linenum)) if val is not IGNORE: pl[opt] = val return pl def parse_args(parser, cli_args, deprecated_opts, integer_log_level, namespace=None): #print('PARSING ARGS:', cli_args) del integer_log_level[:] options = parser.parse_args(cli_args, namespace) #print('PARSED OPTIONS:', options) # warn for deprecated options deprecated_args = [a for a in cli_args if a in deprecated_opts] for da in deprecated_args: # verify if it was a real option by looking into # parsed values for the actual destination hint = deprecated_opts[da] dest = (hint or da).lstrip('-') default = parser.get_default(dest) if da == '--interfaces': hint = '--interface' if getattr(options, dest) is not default: # the option has been specified msg = "%s is deprecated" % da if hint: msg += ", use %s instead" % hint warn(msg) # warn for deprecated values if integer_log_level and '--debug' not in deprecated_args: warn('integer argument for -D/--log_level is deprecated, ' 'use label instead') # fix schedulers and die if all were skipped if None in options.schedulers: options.schedulers = [i for i in options.schedulers if i is not None] if not options.schedulers: die('no scheduler left') # fix crontabs and die if all were skipped if None in options.crontabs: options.crontabs = [i for i in options.crontabs if i is not None] if not options.crontabs: die('no crontab left') # taskbar if options.taskbar and os.name != 'nt': warn('--taskbar not supported on this platform, skipped') options.taskbar = False # options consistency checkings if options.run and not options.shell: die('-R/--run requires -S/--shell', exit_status=2) if options.args and not options.run: die('-A/--args requires -R/--run', exit_status=2) if options.with_scheduler and not options.schedulers: die('-X/--with_scheduler requires -K/--scheduler', exit_status=2) if options.soft_cron and not options.with_cron: die('--soft_cron requires -Y/--with_cron', exit_status=2) if options.shell: for o, os in dict(with_scheduler='-X/--with_scheduler', schedulers='-K/--scheduler', with_cron='-Y/--with_cron', cron_run='-C/--cron_run', run_doctests='-T/--run_doctests', run_system_tests='--run_system_tests').items(): if getattr(options, o): die("-S/--shell and %s are conflicting options" % os, exit_status=2) if options.bpython and options.plain: die('-B/--bpython and -P/--plain are conflicting options', exit_status=2) if options.cron_run: for o, os in dict(with_cron='-Y/--with_cron', run_doctests='-T/--run_doctests', run_system_tests='--run_system_tests').items(): if getattr(options, o): die("-C/--cron_run and %s are conflicting options" % os, exit_status=2) if options.run_doctests and options.run_system_tests: die('-T/--run_doctests and --run_system_tests are conflicting options', exit_status=2) if options.config: # load options from file, # all options sourced from file that evaluates to False # are skipped, the special IGNORE value is used for this store_true = lambda v: True if v else IGNORE str_or_default = lambda v : str(v) if v else IGNORE list_or_default = lambda v : ( [str(i) for i in v] if isinstance(v, list) else [str(v)]) if v \ else IGNORE # NOTE: 'help', 'version', 'folder', 'cron_job' and 'GAE' are not # sourced from file, the same applies to deprecated options opt_map = { # global options 'config': str_or_default, 'add_options': store_true, 'password': str_or_default, 'errors_to_console': store_true, 'no_banner': store_true, 'quiet': store_true, 'log_level': str_or_default, # GUI options 'no_gui': store_true, 'taskbar': store_true, # console options 'shell': str_or_default, 'bpython': store_true, 'plain': store_true, 'import_models': store_true, 'run': str_or_default, 'args': list_or_default, # web server options 'server_name': str_or_default, 'ip': str_or_default, 'port': str_or_default, 'server_key': str_or_default, 'server_cert': str_or_default, 'ca_cert': str_or_default, 'interface': list_or_default, 'pid_filename': str_or_default, 'log_filename': str_or_default, 'min_threads': str_or_default, 'max_threads': str_or_default, 'request_queue_size': str_or_default, 'timeout': str_or_default, 'socket_timeout': str_or_default, 'profiler_dir': str_or_default, # scheduler options 'with_scheduler': store_true, 'scheduler': list_or_default, # cron options 'with_cron': store_true, 'crontab': list_or_default, 'soft_cron': store_true, 'cron_run': store_true, # test options 'verbose': store_true, 'run_doctests': str_or_default, 'run_system_tests': store_true, 'with_coverage': store_true, } od = load_config(options.config, opt_map) #print("LOADED FROM %s:" % options.config, od) # convert loaded options dict as retuned by load_config # into a list of arguments for further parsing by parse_args file_args = []; args_args = [] # '--args' must be the last for key, val in od.items(): if key != 'args': file_args.append('--' + key) if isinstance(val, list): file_args.extend(val) elif not isinstance(val, bool): file_args.append(val) else: args_args = ['--args'] + val file_args += args_args if options.add_options: # add options to existing ones, # must clear config to avoid infinite recursion options.config = options.add_options = None return parse_args(parser, file_args, deprecated_opts, integer_log_level, options) return parse_args(parser, file_args, deprecated_opts, integer_log_level) return options
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HSVtoCMYK = exports.HSVtoHEX = exports.HSVtoRGB = exports.HSVtoHSL = exports.CMYKtoHSV = exports.CMYKtoHEX = exports.CMYKtoRGB = exports.CMYKtoHSL = exports.extractNumberFromHex = exports.Hex3To6Char = exports.HEXtoHSV = exports.HEXtoCMYK = exports.HEXtoRGB = exports.HEXtoHSL = exports.RGBtoHSV = exports.RGBtoCMYK = exports.numberToHex = exports.RGBtoHEX = exports.RGBtoHSL = exports.HSLtoHSV = exports.HSLtoCMYK = exports.HSLtoHEX = exports.HSLtoRGB = void 0; /* Supports formats: HSL, RGB, HEX, CMYK, HSV Functions: 1. HSLtoRGB HSLtoHEX HSLtoCMYK HSLtoHSV 2. RGBtoHSL RGBtoHEX RGBtoCMYK RGBtoHSV 3. HEXtoHSL HEXtoRGB HEXtoCMYK HEXtoHSV 4. CMYKtoHSL CMYKtoRGB CMYKtoHEX CMYKtoHSV 5. HSVtoHSL HSVtoRGB HSVtoHEX HSVtoCMYK */ const HSLtoRGB = function (hsl) { let h = hsl.hue; let s = hsl.sat; let l = hsl.light; let r, g, b; h /= 360; s /= 100; l /= 100; if (s == 0) { r = g = b = l; } else { const hue2rgb = function (p, q, t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1 / 6) return p + (q - p) * 6 * t; if (t < 1 / 2) return q; if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; return p; }; let q = l < 0.5 ? l * (1 + s) : l + s - l * s; let p = 2 * l - q; r = hue2rgb(p, q, h + 1 / 3); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1 / 3); } return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; }; exports.HSLtoRGB = HSLtoRGB; const HSLtoHEX = function (hsl) { return RGBtoHEX(HSLtoRGB(hsl)); }; exports.HSLtoHEX = HSLtoHEX; const HSLtoCMYK = function (hsl) { return RGBtoCMYK(HSLtoRGB(hsl)); }; exports.HSLtoCMYK = HSLtoCMYK; const HSLtoHSV = function (hsl) { return RGBtoHSV(HSLtoRGB(hsl)); }; exports.HSLtoHSV = HSLtoHSV; const RGBtoHSL = function (rgb) { let r = rgb.r; let g = rgb.g; let b = rgb.b; r /= 255; g /= 255; b /= 255; let max = Math.max(r, g, b); let min = Math.min(r, g, b); let h, s, l = (max + min) / 2; if (max == min) { h = s = 0; } else { let d = max - min; s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } let hsl = { hue: Math.round(h * 360), sat: Math.round(s * 100), light: Math.round(l * 100) }; hsl.h = hsl.h == 360 ? 0 : hsl.h; return hsl; }; exports.RGBtoHSL = RGBtoHSL; const RGBtoHEX = function (rgb) { return "#" + numberToHex(parseInt(rgb.r)) + numberToHex(parseInt(rgb.g)) + numberToHex(parseInt(rgb.b)); }; exports.RGBtoHEX = RGBtoHEX; const numberToHex = function (n) { let hex = n.toString(16); return hex.length == 1 ? "0" + hex : hex; }; exports.numberToHex = numberToHex; const RGBtoCMYK = function (rgb) { let r = rgb.r; let g = rgb.g; let b = rgb.b; r /= 255; g /= 255; b /= 255; let k = 1 - Math.max(r, g, b); let c = (1 - r - k) / (1 - k) || 0; let m = (1 - g - k) / (1 - k) || 0; let y = (1 - b - k) / (1 - k) || 0; let format = function (c) { return c > 0.0 && c < 1.0 ? parseFloat(c.toFixed(2)) : c; }; c = format(c); m = format(m); y = format(y); k = format(k); return { c, m, y, k }; }; exports.RGBtoCMYK = RGBtoCMYK; const RGBtoHSV = function (rgb) { let r = rgb.r; let g = rgb.g; let b = rgb.b; r /= 255; g /= 255; b /= 255; let max = Math.max(r, g, b), min = Math.min(r, g, b); let h, s, v = max; let d = max - min; s = max == 0 ? 0 : d / max; if (max == min) { h = 0; } else { switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { hue: Math.round(h * 360), sat: Math.round(s * 100), val: Math.round(v * 100) }; }; exports.RGBtoHSV = RGBtoHSV; const HEXtoHSL = function (hexString) { return RGBtoHSL(HEXtoRGB(hexString)); }; exports.HEXtoHSL = HEXtoHSL; const HEXtoRGB = function (hexString) { let rgb = { r: extractNumberFromHex(hexString, 1, 3), g: extractNumberFromHex(hexString, 3, 5), b: extractNumberFromHex(hexString, 5, 7) }; return isNaN(rgb.r) || isNaN(rgb.g) || isNaN(rgb.b) ? { r: NaN, g: NaN, b: NaN } : rgb; }; exports.HEXtoRGB = HEXtoRGB; const HEXtoCMYK = function (hexString) { return RGBtoCMYK(HEXtoRGB(hexString)); }; exports.HEXtoCMYK = HEXtoCMYK; const HEXtoHSV = function (hexString) { return RGBtoHSV(HEXtoRGB(hexString)); }; exports.HEXtoHSV = HEXtoHSV; const Hex3To6Char = function (hex) { return hex.length == 4 ? "#" + hex.substring(1, 2).repeat(2) + "" + hex.substring(2, 3).repeat(2) + "" + hex.substring(3, 4).repeat(2) : hex; }; exports.Hex3To6Char = Hex3To6Char; const extractNumberFromHex = function (HEXString, start, end) { HEXString = Hex3To6Char(HEXString); return parseInt(HEXString.substring(start, end), 16); }; exports.extractNumberFromHex = extractNumberFromHex; const CMYKtoHSL = function (cmyk) { return RGBtoHSL(CMYKtoRGB(cmyk)); }; exports.CMYKtoHSL = CMYKtoHSL; const CMYKtoRGB = function (cmyk) { return { r: Math.round(255 * (1 - cmyk.c) * (1 - cmyk.k)), g: Math.round(255 * (1 - cmyk.m) * (1 - cmyk.k)), b: Math.round(255 * (1 - cmyk.y) * (1 - cmyk.k)) }; }; exports.CMYKtoRGB = CMYKtoRGB; const CMYKtoHEX = function (cmyk) { return RGBtoHEX(CMYKtoRGB(cmyk)); }; exports.CMYKtoHEX = CMYKtoHEX; const CMYKtoHSV = function (cmyk) { return RGBtoHSV(CMYKtoRGB(cmyk)); }; exports.CMYKtoHSV = CMYKtoHSV; const HSVtoHSL = function (hsv) { return RGBtoHSL(HSVtoRGB(hsv)); }; exports.HSVtoHSL = HSVtoHSL; const HSVtoRGB = function (hsv) { let h = hsv.hue / 360, s = hsv.sat / 100, v = hsv.val / 100; let r, g, b; let i = Math.floor(h * 6); let f = h * 6 - i; let p = v * (1 - s); let q = v * (1 - f * s); let t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: { r = v; g = t; b = p; } break; case 1: { r = q; g = v; b = p; } break; case 2: { r = p; g = v; b = t; } break; case 3: { r = p; g = q; b = v; } break; case 4: { r = t; g = p; b = v; } break; case 5: { r = v; g = p; b = q; } break; } return { r: Math.round(r * 255), g: Math.round(g * 255), b: Math.round(b * 255) }; }; exports.HSVtoRGB = HSVtoRGB; const HSVtoHEX = function (hsv) { return RGBtoHEX(HSVtoRGB(hsv)); }; exports.HSVtoHEX = HSVtoHEX; const HSVtoCMYK = function (hsv) { return RGBtoCMYK(HSVtoRGB(hsv)); }; exports.HSVtoCMYK = HSVtoCMYK;
var fs = require('fs'); module.exports = function(grunt) { var browsers = grunt.option('browser') ? grunt.option('browser').split(',') : ['PhantomJS']; var copyright = '/*! <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today(\'yyyy-mm-dd\') %>\n' + '* Copyright (c) <%= grunt.template.today(\'yyyy\') %> Environmental Systems Research Institute, Inc.\n' + '* Apache License' + '*/\n'; var umdHeader = '(function (factory) {\n' + ' //define an AMD module that relies on \'leaflet\'\n' + ' if (typeof define === \'function\' && define.amd) {\n' + ' define([\'leaflet\'], function (L) {\n' + ' return factory(L);\n' + ' });\n' + ' //define a common js module that relies on \'leaflet\'\n' + ' } else if (typeof module === \'object\' && typeof module.exports === \'object\') {\n' + ' module.exports = factory(require(\'leaflet\'));\n' + ' }\n\n' + ' if(typeof window !== \'undefined\' && window.L){\n' + ' factory(window.L);\n' + ' }\n' + '}(function (L) {\n'; var umdFooter = '\n\n return EsriLeaflet;\n' + '}));'; var complete = [ 'src/EsriLeaflet.js', 'src/Util.js', 'src/Request.js', 'src/Services/Service.js', 'src/Services/FeatureLayerService.js', 'src/Services/MapService.js', 'src/Services/ImageService.js', 'src/Tasks/Task.js', 'src/Tasks/Query.js', 'src/Tasks/Find.js', 'src/Tasks/Identify.js', 'src/Tasks/IdentifyImage.js', 'src/Tasks/IdentifyFeatures.js', 'src/Layers/BasemapLayer.js', 'src/Layers/RasterLayer.js', 'src/Layers/DynamicMapLayer.js', 'src/Layers/ImageMapLayer.js', 'src/Layers/TiledMapLayer.js', 'src/Layers/FeatureLayer/FeatureGrid.js', 'src/Layers/FeatureLayer/FeatureManager.js', 'src/Layers/FeatureLayer/FeatureLayer.js', 'src/Controls/Logo.js' ]; var core = [ 'src/EsriLeaflet.js', 'src/Util.js', 'src/Request.js', 'src/Tasks/Task.js', 'src/Services/Service.js' ]; var basemaps = [ 'src/EsriLeaflet.js', 'src/Request.js', 'src/Layers/BasemapLayer.js', 'src/Controls/Logo.js' ]; var mapservice = [ 'src/EsriLeaflet.js', 'src/Util.js', 'src/Request.js', 'src/Services/Service.js', 'src/Services/MapService.js', 'src/Tasks/Task.js', 'src/Tasks/Identify.js', 'src/Tasks/IdentifyFeatures.js', 'src/Tasks/Query.js', 'src/Tasks/Find.js', 'src/Layers/RasterLayer.js', 'src/Layers/DynamicMapLayer.js', 'src/Layers/TiledMapLayer.js' ]; var imageservice = [ 'src/EsriLeaflet.js', 'src/Util.js', 'src/Request.js', 'src/Services/Service.js', 'src/Services/ImageService.js', 'src/Tasks/Task.js', 'src/Tasks/Query.js', 'src/Tasks/Identify.js', 'src/Tasks/Identify/IdentifyImage.js', 'src/Layers/RasterLayer.js', 'src/Layers/ImageMapLayer.js' ]; var featureservice = [ 'src/EsriLeaflet.js', 'src/Util.js', 'src/Request.js', 'src/Services/Service.js', 'src/Services/FeatureLayerService.js', 'src/Tasks/Task.js', 'src/Tasks/Query.js', 'src/Layers/FeatureLayer/FeatureGrid.js', 'src/Layers/FeatureLayer/FeatureManager.js', 'src/Layers/FeatureLayer/FeatureLayer.js' ]; var customLaunchers = { sl_chrome: { base: 'SauceLabs', browserName: 'chrome', platform: 'Windows 7', version: '35' }, sl_firefox: { base: 'SauceLabs', browserName: 'firefox', version: '30' }, sl_ios_safari: { base: 'SauceLabs', browserName: 'iphone', platform: 'OS X 10.9', version: '7.1' }, sl_ie_11: { base: 'SauceLabs', browserName: 'internet explorer', platform: 'Windows 8.1', version: '11' } }; // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jshint: { options: { jshintrc: '.jshintrc' }, all: { src: [ 'src/**/*.js' ] } }, watch: { scripts: { files: [ 'src/**/*.js', 'spec/**/*.js' ], tasks: ['jshint'], options: { spawn: false } }, 'docs-sass': { files: ['site/source/scss/**/*.scss'], tasks: ['sass'], options: { nospawn: true } }, 'docs-js': { files: ['site/source/**/*.js'], tasks: ['concat', 'uglify', 'copy:assemble'], options: { nospawn: true } }, 'docs-img': { files: ['site/source/img/**/*'], tasks: ['newer:imagemin'], options: { nospawn: true } }, 'docs-assemble': { files: ['site/source/**/*.md', 'site/source/**/*.hbs'], tasks: ['assemble:dev'], options: { nospawn: true, livereload: true } } }, concurrent: { options: { logConcurrentOutput: true }, dev: ['watch:scripts', 'karma:watch', 'docs'] }, concat: { options: { sourceMap: true, separator: '\n\n', banner: copyright + umdHeader, footer: umdFooter, }, complete: { src: complete, dest: 'dist/esri-leaflet-src.js' }, core: { src: core, dest: 'dist/builds/core/esri-leaflet-core-src.js' }, basemaps: { src: basemaps, dest: 'dist/builds/basemaps/esri-leaflet-basemaps-src.js' }, mapservice: { src: mapservice, dest: 'dist/builds/map-service/esri-leaflet-map-service-src.js' }, imageservice: { src: imageservice, dest: 'dist/builds/image-service/esri-leaflet-image-service-src.js' }, featureservice: { src: featureservice, dest: 'dist/builds/feature-layer/esri-leaflet-feature-layer-src.js' } }, uglify: { options: { sourceMap: true, sourceMapIncludeSources: true, wrap: false, mangle: { except: ['L'] }, preserveComments: 'some', report: 'gzip', banner: copyright + umdHeader, footer: umdFooter, }, dist: { files: { 'dist/esri-leaflet.js': complete, 'dist/builds/core/esri-leaflet-core.js': core, 'dist/builds/basemaps/esri-leaflet-basemaps.js': basemaps, 'dist/builds/map-service/esri-leaflet-map-service.js': mapservice, 'dist/builds/image-service/esri-leaflet-image-service.js': imageservice, 'dist/builds/feature-layer/esri-leaflet-feature-layer.js': featureservice } } }, karma: { options: { configFile: 'karma.conf.js' }, run: { reporters: ['progress'], browsers: browsers, logLevel: 'ERROR' }, coverage: { reporters: ['progress', 'coverage'], browsers: browsers, preprocessors: { 'src/**/*.js': 'coverage' } }, watch: { singleRun: false, autoWatch: true, browsers: browsers }, sauce: { sauceLabs: { testName: 'Esri Leaflet Unit Tests' }, customLaunchers: customLaunchers, browsers: Object.keys(customLaunchers), reporters: ['progress', 'saucelabs'], singleRun: true } }, connect: { server: { options: { port: 8000, base: '.', keepalive: true } }, docs: { options: { port: 8001, hostname: '0.0.0.0', base: './site/build/' } } }, assemble: { options: { layout: 'layout.hbs', layoutdir: 'site/source/layouts/', partials: 'site/source/partials/**/*.hbs', helpers: ['site/source/helpers/**/*.js' ] }, dev: { options: { data: ['site/data/*.json', 'package.json'], assets: 'site/build/' }, files: [{ cwd: 'site/source/pages', dest: 'site/build', expand: true, src: ['**/*.hbs', '**/*.md'] }] }, build: { options: { assets: 'esri-leaflet/' }, files: [{ cwd: 'site/source/pages', dest: 'site/build', expand: true, src: ['**/*.hbs', '**/*.md'] }] } }, copy: { assemble: { files: [ { src: 'site/source/js/script.js', dest: 'site/build/js/script.js'} ] } }, imagemin: { dynamic: { files: [{ expand: true, cwd: 'site/source/img', src: ['**/*.{png,jpg,gif}'], dest: 'site/build/img' }] } }, sass: { site: { files: { 'site/build/css/style.css': 'site/source/scss/style.scss' } } }, 'gh-pages': { options: { base: 'site/build', repo: 'git@github.com:Esri/esri-leaflet.git' }, src: ['**'] }, releaseable: { release: { options: { remote: 'upstream', dryRun: grunt.option('dryRun') ? grunt.option('dryRun') : false, silent: false }, src: [ 'dist/**/*.js','dist/**/*.map' ] } } }); // Development Tasks grunt.registerTask('default', ['concurrent:dev']); grunt.registerTask('build', ['jshint', 'karma:coverage', 'concat', 'uglify']); grunt.registerTask('test', ['jshint', 'karma:run']); grunt.registerTask('prepublish', ['concat', 'uglify']); grunt.registerTask('release', ['releaseable']); grunt.registerTask('test:sauce', ['karma:sauce']); // Documentation Site Tasks grunt.registerTask('docs', ['assemble:dev', 'concat', 'uglify', 'sass', 'copy', 'connect:docs', 'watch']); // Documentation Site Tasks grunt.registerTask('docs:build', ['assemble:build', 'copy', 'imagemin','sass', 'gh-pages']); // Require all grunt modules require('load-grunt-tasks')(grunt, {pattern: ['grunt-*', 'assemble']}); };
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved (function () { "use strict"; var page = WinJS.UI.Pages.define("/html/scenario7_enableNotificationQueue.html", { ready: function (element, options) { document.getElementById("enableNotificationQueue").addEventListener("click", enableNotificationQueue, false); document.getElementById("disableNotificationQueue").addEventListener("click", disableNotificationQueue, false); document.getElementById("enableSquare150x150NotificationQueue").addEventListener("click", enableSquare150x150NotificationQueue, false); document.getElementById("disableSquare150x150NotificationQueue").addEventListener("click", disableSquare150x150NotificationQueue, false); document.getElementById("enableWide310x150NotificationQueue").addEventListener("click", enableWide310x150NotificationQueue, false); document.getElementById("disableWide310x150NotificationQueue").addEventListener("click", disableWide310x150NotificationQueue, false); document.getElementById("enableSquare310x310NotificationQueue").addEventListener("click", enableSquare310x310NotificationQueue, false); document.getElementById("disableSquare310x310NotificationQueue").addEventListener("click", disableSquare310x310NotificationQueue, false); document.getElementById("useTileNotificationTag").addEventListener("click", useTileNotificationTag, false); document.getElementById("clearTileNotification").addEventListener("click", clearTileNotification, false); } }); function clearTileNotification() { Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().clear(); WinJS.log && WinJS.log("Tile cleared", "sample", "status"); } function enableNotificationQueue() { // Enable the notification queue - this only needs to be called once in the lifetime of your app Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(true); WinJS.log && WinJS.log("Tile notification cycling enabled for all tile sizes.", "sample", "status"); } function disableNotificationQueue() { Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueue(false); WinJS.log && WinJS.log("Tile notification cycling disabled for all tile sizes.", "sample", "status"); } function enableSquare150x150NotificationQueue() { // Enable the notification queue for Square150x150 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForSquare150x150(true); WinJS.log && WinJS.log("Notification cycling enabled for Square150x150 Tiles.", "sample", "status"); } function disableSquare150x150NotificationQueue() { // Disable the notification queue for Square150x150 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForSquare150x150(false); WinJS.log && WinJS.log("Notification cycling disabled for Square150x150 Tiles.", "sample", "status"); } function enableWide310x150NotificationQueue() { // Enable the notification queue for Wide310x150 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForWide310x150(true); WinJS.log && WinJS.log("Notification cycling enabled for Wide310x150 Tiles.", "sample", "status"); } function disableWide310x150NotificationQueue() { // Enable the notification queue for Wide310x150 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForWide310x150(false); WinJS.log && WinJS.log("Notification cycling disabled for Wide310x150 Tiles.", "sample", "status"); } function enableSquare310x310NotificationQueue() { // Enable the notification queue for Square310x310 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForSquare310x310(true); WinJS.log && WinJS.log("Notification cycling enabled for Square310x310 Tiles.", "sample", "status"); } function disableSquare310x310NotificationQueue() { // Disable the notification queue for Square310x310 Tiles. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().enableNotificationQueueForSquare310x310(false); WinJS.log && WinJS.log("Notification cycling disabled for Square310x310 Tiles.", "sample", "status"); } function useTileNotificationTag() { var currentTime = new Date(); var tag = document.getElementById("tag").value; if (!(tag.length > 0 && tag.length <= 16)) { tag = "TestTag01"; } var tileText = document.getElementById("text").value; // Create a notification for the Square310x310 tile using one of the available templates for the size. var square310x310TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileSquare310x310Text09(); square310x310TileContent.textHeadingWrap.text = tileText; // Create a notification for the Wide310x150 tile using one of the available templates for the size. var wide310x150TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileWide310x150Text03(); wide310x150TileContent.textHeadingWrap.text = tileText; // Create a notification for the Square150x150 tile using one of the available templates for the size. var square150x150TileContent = NotificationsExtensions.TileContent.TileContentFactory.createTileSquare150x150Text04(); square150x150TileContent.textBodyWrap.text = tileText; // Attach the Square150x150 template to the Wide310x150 template. wide310x150TileContent.square150x150Content = square150x150TileContent; // Attach the Wide310x150 template to the Square310x310 template. square310x310TileContent.wide310x150Content = wide310x150TileContent; var tileNotification = square310x310TileContent.createNotification(); // Set the tag on the notification. tileNotification.tag = tag; // Send the notification to the application’s tile. Windows.UI.Notifications.TileUpdateManager.createTileUpdaterForApplication().update(tileNotification); WinJS.log && WinJS.log("Tile notification sent. It is tagged with " + tag, "sample", "status"); } })();
module.exports = { publicPath: process.env.NODE_ENV === 'production' ? '/YAPP/' : '/' }
""" Ecuador-specific form helpers. """ from __future__ import absolute_import from django.contrib.localflavor.ec.ec_provinces import PROVINCE_CHOICES from django.forms.fields import Select class ECProvinceSelect(Select): """ A Select widget that uses a list of Ecuador provinces as its choices. """ def __init__(self, attrs=None): super(ECProvinceSelect, self).__init__(attrs, choices=PROVINCE_CHOICES)
// https://date-fns.org/ import { formatDistanceToNowStrict, subDays, parseISO, startOfTomorrow } from 'date-fns' const now = new Date(); const tomorrow = startOfTomorrow(); const myAge = formatDistanceToNowStrict(parseISO('1983-02-25'), { addSuffix: false}); document.getElementById("dateNow").innerHTML = now; document.getElementById("dateTomorrow").innerHTML = tomorrow; document.getElementById("dateMyAge").innerHTML = myAge;
/** * CRUD sample */ ej.diagrams.Diagram.Inject( ej.diagrams.DataBinding, ej.diagrams.HierarchicalTree ); var diagram; var dialog; var toolbarObj; var sourceDropdown; var targetDropdown; var sourceID; var targetID; var nodeData = []; // custom code start function dlgButtonClick(args) { var dialogHeader = dialog.header; var description = document.getElementById("Description").value; var color = document.getElementById("Color").value; var selectedItem; if (diagram.selectedItems.nodes.length > 0) { selectedItem = diagram.selectedItems.nodes[0]; } if (diagram.selectedItems.connectors.length > 0) { selectedItem = diagram.selectedItems.connectors[0]; } //Add new node and connector in diagram at runtime. if (dialogHeader === "Add") { var node = { id: "node" + ej.diagrams.randomId(), style: { fill: color }, Description: description, Color: color, Id: Math.floor(Math.random() * 1000 + 100) }; var connector = { id: "connector" + ej.diagrams.randomId(), sourceID: selectedItem.id, targetID: node.id, Id: Math.floor(Math.random() * 1000 + 100) }; diagram.add(node); diagram.add(connector); diagram.doLayout(); //Insert newly added eelements into the database. diagram.insertData(); nodeData.push({ Name: node.id, Label: description }); sourceDropdown.dataSource = getDataSource(); sourceDropdown.dataBind(); targetDropdown.dataSource = getDataSource(); targetDropdown.dataBind(); } else { if (selectedItem instanceof ej.diagrams.Connector) { //Update sourceNode and targetNode at runtime. selectedItem.sourceID = sourceID ? sourceID : selectedItem.sourceID; selectedItem.targetID = targetID ? targetID : selectedItem.targetID; diagram.dataBind(); diagram.doLayout(); } else { //Update an node text and node bgColor. selectedItem.Description = description; selectedItem.Color = color; selectedItem.annotations[0].content = description; selectedItem.style.fill = color; diagram.dataBind(); } diagram.updateData(); } dialog.hide(); } //Set an sourceId of an selected Connector. function sourceDropdownChange(args) { sourceID = args.value; } //Set an targetId of an selected Connector. function targetDropdownChange(args) { targetID = args.value; } //Displays nodes name in dropdown. function sourceDropdownCreate(args) { sourceDropdown.dataSource = getDataSource(); sourceDropdown.dataBind(); } //Displays nodes name in dropdown. function targetDropdownCreate(args) { targetDropdown.dataSource = getDataSource(); targetDropdown.dataBind(); } // custom code end //Disable or Enable the toolbar items based on element selection. function selectionChange(args) { if (args.state === "Changing") { if (args.newValue.length > 0) { if (args.newValue[0] instanceof ej.diagrams.Node) { enableToolbarItems(true); } else { toolbarObj.enableItems( document.getElementById(items[0].id).parentElement, false ); toolbarObj.enableItems( document.getElementById(items[2].id).parentElement, true ); toolbarObj.enableItems( document.getElementById(items[4].id).parentElement, false ); } } else { enableToolbarItems(false); } } } // custom code start //Enable or disable the toolbar items. function enableToolbarItems(isEnableItem) { toolbarObj.enableItems( document.getElementById(items[0].id).parentElement, isEnableItem ); toolbarObj.enableItems( document.getElementById(items[2].id).parentElement, isEnableItem ); toolbarObj.enableItems( document.getElementById(items[4].id).parentElement, isEnableItem ); } // custom code end function connectionChange(args) { if (args.state === "Completed") { if (!args.connector.targetID || !args.connector.sourceID) { args.cancel = true; } } } //Set an label for each node. function setNodeTemplate(obj) { obj.annotations = [{ style: { color: "black" } }]; obj.annotations[0].content = obj.Description; obj.style = { fill: obj.Color }; if (obj.Id === 1) { //Restrict Delete Constraints for root node. obj.constraints = ej.diagrams.NodeConstraints.Default & ~ej.diagrams.NodeConstraints.Delete; } } // custom code start //Opens a dialog with textbox and dropdown control based on toolbar clicked items. function toolbarClick(args) { var selectedItem; if (diagram.selectedItems.nodes.length > 0) { selectedItem = diagram.selectedItems.nodes[0]; } if (diagram.selectedItems.connectors.length > 0) { selectedItem = diagram.selectedItems.connectors[0]; } if (selectedItem) { switch (args.item.tooltipText) { case "Add": openDialog("Add", "", "", true); break; case "Edit": if (selectedItem instanceof ej.diagrams.Connector) { var sourceNode = diagram.getObject(selectedItem.sourceID); var targetNode = diagram.getObject(selectedItem.targetID); openDialog("Edit", sourceNode.Description, targetNode.Description, false ); } else { openDialog("Edit", selectedItem.Description, selectedItem.Color, true ); } break; case "Delete": diagram.remove(selectedItem); diagram.doLayout(); //Delete an selected items from database. diagram.removeData(); var element = { Name: selectedItem.id, Label: selectedItem.Description }; var index = nodeData.indexOf(element); nodeData.splice(index, 1); sourceDropdown.dataSource = getDataSource(); sourceDropdown.dataBind(); targetDropdown.dataSource = getDataSource(); targetDropdown.dataBind(); } } } //Show or Hide the Textbox and Dropdown in dialog control. function hideClassElement(className, display) { var i; var showDropdown = document.querySelectorAll(className); for (i = 0; i < showDropdown.length; i++) { showDropdown[i].style.display = display; } } //open a dialog control on clicking the toolbar items. function openDialog(title, description, color, isNode) { dialog.header = title; if (isNode) { hideClassElement(".showDropdown", "none"); hideClassElement(".showLabel", "block"); document.getElementById("Description").value = description; document.getElementById("Color").value = color; } else { hideClassElement(".showDropdown", "block"); hideClassElement(".showLabel", "none"); document.getElementById("SourceId").value = description; document.getElementById("TargetId").value = color; } //Open a dialog. dialog.show(); } // custom code end //Returns an node text collection in diagram. function getDataSource() { var i; nodeData = []; for (i = 0; i < diagram.nodes.length; i++) { var node = diagram.nodes[i]; var element = { Name: node.id, Label: node.Description }; nodeData.push(element); } return nodeData; } //Add icons in Toolbar. var items = [ { text: "Add", tooltipText: "Add", prefixIcon: "e-ddb-icons e-add", id: "Add" }, { type: "Separator" }, { text: "Edit", tooltipText: "Edit", prefixIcon: "e-ddb-icons e-update", id: "Edit" }, { type: "Separator" }, { text: "Delete", tooltipText: "Delete", prefixIcon: "e-ddb-icons e-delete", id: "Delete" } ]; this.default = function() { diagram = new ej.diagrams.Diagram({ width: "100%", height: 600, dataSourceSettings: { id: 'Name', //Define URL to perform CRUD operations with nodes records in database. crudAction: { read: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/GetNodes', create: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/AddNodes', update: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/UpdateNodes', destroy: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/DeleteNodes', customFields: ['Id', 'Description', 'Color'], }, connectionDataSource: { id: 'Name', sourceID: 'SourceNode', targetID: 'TargetNode', //Define URL to perform CRUD operations with connector records in database. crudAction: { read: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/GetConnectors', create: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/AddConnectors', update: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/UpdateConnectors', destroy: 'https://js.syncfusion.com/demos/ejServices/api/Diagram/DeleteConnectors', customFields: ['Id'], } } }, layout: { type: "HierarchicalTree", verticalSpacing: 40 }, snapSettings: { constraints: 0 }, //Set node default properties. getNodeDefaults: function (obj, diagram) { obj.width = 100; obj.height = 50; obj.shape = { type: 'Basic', shape: 'Rectangle' }; obj.style = { strokeWidth: 1, strokeColor: '#DDDDDD' }; return obj; }, //Set connector default properties. getConnectorDefaults: function (connector, diagram) { connector.type = 'Orthogonal'; connector.style.fill = '#707070'; connector.style.strokeColor = '#707070'; connector.targetDecorator = { style: { strokeColor: '#707070', fill: '#707070' }, }; return connector; }, selectionChange: selectionChange, sourcePointChange: connectionChange, targetPointChange: connectionChange, setNodeTemplate: setNodeTemplate }); diagram.appendTo("#diagram"); //Initialize ToolBar control. toolbarObj = new ej.navigations.Toolbar({ clicked: toolbarClick, items: items }); toolbarObj.appendTo("#toolbar"); enableToolbarItems(false); //Initialize dialog control. dialog = new ej.popups.Dialog({ width: "300px", visible: false, isModal: true, showCloseIcon: true, buttons: [ { click: dlgButtonClick, buttonModel: { content: "Update", isPrimary: true } } ] }); dialog.appendTo("#editDialog"); //Initialize textbox control. var inputobj1 = new ej.inputs.TextBox({ floatLabelType: "Always", placeholder: "Description" }); inputobj1.appendTo("#Description"); //Initialize textbox control. var inputobj2 = new ej.inputs.TextBox({ floatLabelType: "Always", placeholder: "Color" }); inputobj2.appendTo("#Color"); //Initialize button control to update the node label and node color. var button = new ej.buttons.Button(); button.appendTo("#btnUpdate"); //Initialize dropdownlist control to display an sourceNodes in diagram. sourceDropdown = new ej.dropdowns.DropDownList({ fields: { text: "Label", value: "Name" }, change: sourceDropdownChange, created: sourceDropdownCreate }); sourceDropdown.appendTo("#SourceId"); //Initialize dropdownlist control to display an targetNodes in diagram. targetDropdown = new ej.dropdowns.DropDownList({ fields: { text: "Label", value: "Name" }, change: targetDropdownChange, created: targetDropdownCreate }); targetDropdown.appendTo("#TargetId"); };
# -*- coding: utf-8 -*- # Copyright 2019 Cohesity Inc. class EnvironmentSearchProtectionSourcesEnum(object): """Implementation of the 'Environment_SearchProtectionSources' enum. TODO: type enum description here. Attributes: KVMWARE: TODO: type description here. KHYPERV: TODO: type description here. KSQL: TODO: type description here. KVIEW: TODO: type description here. KPUPPETEER: TODO: type description here. KPHYSICAL: TODO: type description here. KPURE: TODO: type description here. KAZURE: TODO: type description here. KNETAPP: TODO: type description here. KAGENT: TODO: type description here. KGENERICNAS: TODO: type description here. KACROPOLIS: TODO: type description here. KPHYSICALFILES: TODO: type description here. KISILON: TODO: type description here. KKVM: TODO: type description here. KAWS: TODO: type description here. KEXCHANGE: TODO: type description here. KHYPERVVSS: TODO: type description here. KORACLE: TODO: type description here. KGCP: TODO: type description here. KFLASHBLADE: TODO: type description here. KAWSNATIVE: TODO: type description here. KVCD: TODO: type description here. KO365: TODO: type description here. KO365OUTLOOK: TODO: type description here. KHYPERFLEX: TODO: type description here. KGCPNATIVE: TODO: type description here. KAZURENATIVE: TODO: type description here. """ K_VMWARE = 'kVMware' K_HYPERV = 'kHyperV' KSQL = 'kSQL' KVIEW = 'kView' KPUPPETEER = 'kPuppeteer' KPHYSICAL = 'kPhysical' KPURE = 'kPure' KAZURE = 'kAzure' KNETAPP = 'kNetapp' KAGENT = 'kAgent' KGENERICNAS = 'kGenericNas' KACROPOLIS = 'kAcropolis' KPHYSICALFILES = 'kPhysicalFiles' KISILON = 'kIsilon' KKVM = 'kKVM' KAWS = 'kAWS' KEXCHANGE = 'kExchange' K_HYPERV_VSS = 'kHyperVVSS' KORACLE = 'kOracle' KGCP = 'kGCP' KFLASHBLADE = 'kFlashBlade' KAWSNATIVE = 'kAWSNative' KVCD = 'kVCD' KO365 = 'kO365' KO365OUTLOOK = 'kO365Outlook' KHYPERFLEX = 'kHyperFlex' KGCPNATIVE = 'kGCPNative' KAZURENATIVE = 'kAzureNative'
import React, { Component } from 'react'; import './PostItem.css'; function PostReader({ author, date }){ return ( <div className="post-reader"> <img className="avatar" src={author.avatar} alt="avatar"/> <div className="details"> <strong>{author.name}</strong> <span>{date}</span> </div> </div> ); } function PostComments({ comments }){ return ( <div className="post-comments" > <div className="divider"> {comments.map(comment => ( <div key={comment.id} className="comment-content"> <img className="avatar-comment" src={comment.author.avatar} alt="avatar"/> <p> <strong>{comment.author.name} </strong> {comment.content} </p> </div> ))} </div> </div> ); } function PostItem({ author, date, content, comments }) { return ( <div className="post"> <PostReader author={author} date={date} /> <p className="post-content">{content}</p> <PostComments comments={comments}/> </div> ); } export default PostItem;
const axios = require("axios"); const curlizer = require("axios-curlirize"); curlizer(axios); let test = await axios.get("http://ifconfig.me");