text
stringlengths
3
1.05M
function f0(x) { switch (x) { default: throw new v2(); case 'aab': return 2; case 'aac': return 3; case 'baaa': return 4; case 'baab': return 5; case 'baac': return 6; case 'caaaa': return 7; case 'caaab': return 8; case 'caaac': return 9; default: return 10; } } function f1(pre, post) { return pre + 'a' + post; } var v0 = [ f1('a', 'a'), f1('a', 'b'), f1('a', 'c'), f1('b', 'aa'), f1('b', 'ab'), f1('b', 'ac'), f1('c', 'aaa'), f1('c', 'aab'), f1('c', 'aac'), f1('a', 'd'), f1('b', 'ad'), f1('c', 'aad'), 'd', f1('d', 'a') ]; var v1 = 0; for (var v2 = 0; v2 < 1000000; ++v2) v1 += f0(v0[v2 % v0.length]); if (v1 != 6785696) throw 'Bad result: ' + v1;
$(document).ready(function() { console.log('chart loaded'); function draw(id, series) { var labels = ['Sangat Buruk', 'Buruk', 'Sedang', 'Baik', 'Sangat Baik']; new Chartist.Pie('#' + id, { series: series, }, { height: 250, // donut: true, // donutWidth: 50, donutSolid: true, labelInterpolationFnc: function (value, idx) { return (value == 0)? "" : labels[idx] + " (" + value + ")"; }, // distributeSeries: true, }); } // GENERATE QUESTIONS var t_questions = []; var index = 0; for (var i = 0; i < q_sessions.length; i++) { if (q_sessions[i]['answer_type'] == 3) { t_questions[index] = [q_sessions[i]['question'], q_sessions[i]['colname']]; index++; } } console.log(t_questions); var s_questions = []; index = 0; for (var i = 0; i < q_speakers.length; i++) { if (q_speakers[i]['answer_type'] == 3) { s_questions[index] = [q_speakers[i]['question'], q_speakers[i]['colname']]; index++; } } console.log(s_questions); // SESSION for (var i = 0; i < tracks.length; i++) { var answers = []; for (var j = 0; j < t_questions.length; j++) { answers[j] = [0, 0, 0, 0, 0]; } var feedbacks = tracks[i]['feedbacks']; for (var j = 0; j < feedbacks.length; j++) { for (var k = 0; k < t_questions.length; k++) { console.log(answers[k][feedbacks[j][t_questions[k][1]]-1]); answers[k][feedbacks[j][t_questions[k][1]]-1]++; } } for (var j = 0; j < t_questions.length; j++) { var id = 'title-t-' + tracks[i]['track_id'] + '-s-' + t_questions[j][1]; document.getElementById(id).innerText = t_questions[j][0]; draw(id, answers[j]); } // SPEAKER for (var j = 0; j < tracks[i]['speakers'].length; j++) { var s_answers = []; for (var k = 0; k < s_questions.length; k++) { s_answers[k] = [0, 0, 0, 0, 0]; } var s_feedbacks = tracks[i]['speakers'][j]['feedbacks']; for (var k = 0; k < s_feedbacks.length; k++) { for (var l = 0; l < s_questions.length; l++) { s_answers[l][s_feedbacks[k][s_questions[l][1]]-1]++; } } for (var k = 0; k < s_questions.length; k++) { var s_id = 't-' + tracks[i]['track_id'] + '-sp-' + tracks[i]['speakers'][j]['speaker_id'] + '-q-' + s_questions[k][1]; console.log(s_id); document.getElementById('title-' + s_id).innerText = s_questions[k][0]; draw(s_id, s_answers[k]); console.log(s_answers[k]); } } } // ================================== $sessions = tracks[0]['feedbacks']; for ($i = 0; $i < $sessions.length; $i++) { // console.log($sessions[$i]); } $speakers = tracks[1]; });
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Unit tests for the transform.external classes.""" from __future__ import absolute_import import typing import unittest import apache_beam as beam from apache_beam import typehints from apache_beam.portability.api.external_transforms_pb2 import ExternalConfigurationPayload from apache_beam.transforms.external import AnnotationBasedPayloadBuilder from apache_beam.transforms.external_test import PayloadBase def get_payload(cls): payload = ExternalConfigurationPayload() payload.ParseFromString(cls._payload) return payload class ExternalAnnotationPayloadTest(PayloadBase, unittest.TestCase): def get_payload_from_typing_hints(self, values): class AnnotatedTransform(beam.ExternalTransform): URN = 'beam:external:fakeurn:v1' def __init__(self, integer_example: int, string_example: str, list_of_strings: typing.List[str], optional_kv: typing.Optional[ typing.Tuple[str, float]] = None, optional_integer: typing.Optional[int] = None, expansion_service=None): super(AnnotatedTransform, self).__init__( self.URN, AnnotationBasedPayloadBuilder( self, integer_example=integer_example, string_example=string_example, list_of_strings=list_of_strings, optional_kv=optional_kv, optional_integer=optional_integer, ), expansion_service ) return get_payload(AnnotatedTransform(**values)) def get_payload_from_beam_typehints(self, values): class AnnotatedTransform(beam.ExternalTransform): URN = 'beam:external:fakeurn:v1' def __init__(self, integer_example: int, string_example: str, list_of_strings: typehints.List[str], optional_kv: typehints.Optional[ typehints.KV[str, float]] = None, optional_integer: typehints.Optional[int] = None, expansion_service=None): super(AnnotatedTransform, self).__init__( self.URN, AnnotationBasedPayloadBuilder( self, integer_example=integer_example, string_example=string_example, list_of_strings=list_of_strings, optional_kv=optional_kv, optional_integer=optional_integer, ), expansion_service ) return get_payload(AnnotatedTransform(**values)) if __name__ == '__main__': unittest.main()
// @flow import * as React from 'react'; import loadPageIntoElement from './loadPageIntoElement'; type WithAppLoaderOptions = { elementId: string, appUrl: string, loadPage?: (string, string) => void, LoadingComponent?: React.ComponentType<any>, }; export const withAppLoader = ({ elementId, appUrl, loadPage = loadPageIntoElement, LoadingComponent, }: WithAppLoaderOptions): React.ComponentType<any> | Error => { type State = {}; type Props = {}; return class AppLoader extends React.PureComponent<Props, State> { componentDidMount() { this.loadApp(); } componentDidCatch = async (error, info) => { // eslint-disable-next-line console.log('catch error:', error); // eslint-disable-next-line console.log('catch info:', info); }; loadApp = async () => { try { await loadPage(elementId, appUrl); } catch (e) { throw new Error(e); } }; render() { return ( <React.Fragment> <div id={elementId}>{LoadingComponent ? <LoadingComponent /> : null}</div> </React.Fragment> ); } }; };
# This file is part of Pynguin. # # Pynguin is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Pynguin is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with Pynguin. If not, see <https://www.gnu.org/licenses/>. import pytest from pynguin.generation.stoppingconditions.maxiterationsstoppingcondition import ( MaxIterationsStoppingCondition, ) @pytest.fixture def stopping_condition(): return MaxIterationsStoppingCondition() def test_set_get_limit(stopping_condition): stopping_condition.set_limit(42) assert stopping_condition.limit() == 42 def test_is_not_fulfilled(stopping_condition): stopping_condition.reset() assert not stopping_condition.is_fulfilled() def test_is_fulfilled(stopping_condition): stopping_condition.set_limit(1) stopping_condition.iterate() stopping_condition.iterate() assert stopping_condition.is_fulfilled()
const prayers = [ { name: "Fajr", time: "02:37:00" }, { name: "Zuhr", time: "11:44:00" }, { name: "Asr", time: "15:33:00" }, { name: "Maghrib", time: "19:01:00" }, { name: "Isha", time: "20:34:00" } ]; const now = new Date("2018-06-25T12:24:00"); // const now = new Date(); let nextPrayer = null; for (let i = 0; i < prayers.length - 1; i++) { const firstPrayer = prayers[i]; const secondPrayer = prayers[i + 1]; const firstTime = firstPrayer.time.split(":"); const firstPrayerDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(firstTime[0]), parseInt(firstTime[1]), parseInt(firstTime[2])); const secondTime = secondPrayer.time.split(":"); const secondPrayerDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), parseInt(secondTime[0]), parseInt(secondTime[1]), parseInt(secondTime[2])); if (now >= firstPrayerDate && now <= secondPrayerDate) { nextPrayer = secondPrayer; break; } } if (nextPrayer == null) { nextPrayer = prayers[0]; } console.log( `${nextPrayer.name} prayer at ${nextPrayer.time}. The time now is ${now}` );
/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRelayCompatContainerBuilder * * @format */ 'use strict'; var _extends3 = _interopRequireDefault(require('babel-runtime/helpers/extends')); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _require = require('./RelayContainerUtils'), getComponentName = _require.getComponentName; function getContainerName(Component) { return 'Relay(' + getComponentName(Component) + ')'; } var containerContextTypes = { relay: require('./RelayPropTypes').Relay }; /** * `injectDefaultVariablesProvider()` allows classic versions of a container to * inject default variable values for a fragment via the arguments of any * references to it. This is useful for fragments that need to reference * global query constants (e.g. the device pixel ratio) but may be included * in classic queries that do not define the necessary param. */ var injectedDefaultVariablesProvider = null; function injectDefaultVariablesProvider(variablesProvider) { require('fbjs/lib/invariant')(!injectedDefaultVariablesProvider, 'injectDefaultVariablesProvider must be called no more than once.'); injectedDefaultVariablesProvider = variablesProvider; } /** * Creates a component class whose instances adapt to the * `context.relay.environment` in which they are rendered and which have the * necessary static methods (`getFragment()` etc) to be composed within classic * `Relay.Containers`. * * The returned constructor uses the given `createContainerForEnvironment` to * construct a new container type whenever a new environment is encountered; * while the constructor is being used for the same environment (the expected * majority case) this value is memoized to avoid creating unnecessary extra * container definitions or unwrapping the environment-specific fragment * defintions unnecessarily. */ function buildCompatContainer(ComponentClass, fragmentSpec, createContainerWithFragments) { // Sanity-check user-defined fragment input var containerName = getContainerName(ComponentClass); require('./assertFragmentMap')(getComponentName(ComponentClass), fragmentSpec); var injectedDefaultVariables = null; function getDefaultVariables() { if (injectedDefaultVariables == null) { injectedDefaultVariables = injectedDefaultVariablesProvider ? injectedDefaultVariablesProvider() : {}; } return injectedDefaultVariables; } // Similar to RelayContainer.getFragment(), except that this returns a // FragmentSpread in order to support referencing root variables. function getFragment(fragmentName, variableMapping) { var taggedNode = fragmentSpec[fragmentName]; require('fbjs/lib/invariant')(taggedNode, 'ReactRelayCompatContainerBuilder: Expected a fragment named `%s` to be defined ' + 'on `%s`.', fragmentName, containerName); var fragment = require('./RelayGraphQLTag').getClassicFragment(taggedNode); var args = (0, _extends3['default'])({}, getDefaultVariables(), variableMapping || {}); return { kind: 'FragmentSpread', args: args, fragment: fragment }; } function hasVariable(variableName) { return Object.keys(fragmentSpec).some(function (fragmentName) { var fragment = require('./RelayGraphQLTag').getClassicFragment(fragmentSpec[fragmentName]); return fragment.argumentDefinitions.some(function (argDef) { return argDef.name === variableName; }); }); } // Memoize a container for the last environment instance encountered var environment = void 0; var Container = void 0; function ContainerConstructor(props, context) { if (Container == null || context.relay.environment !== environment) { environment = context.relay.environment; var getFragmentFromTag = environment.unstable_internal.getFragment; var _fragments = require('fbjs/lib/mapObject')(fragmentSpec, getFragmentFromTag); Container = createContainerWithFragments(ComponentClass, _fragments); require('./RelayContainerProxy').proxyMethods(Container, ComponentClass); } return new Container(props, context); } ContainerConstructor.contextTypes = containerContextTypes; ContainerConstructor.displayName = containerName; // Classic container static methods ContainerConstructor.getFragment = getFragment; ContainerConstructor.getFragmentNames = function () { return Object.keys(fragmentSpec); }; ContainerConstructor.hasFragment = function (name) { return fragmentSpec.hasOwnProperty(name); }; ContainerConstructor.hasVariable = hasVariable; // Create a back-reference from the Component to the Container for cases // where a Classic Component might refer to itself, expecting a Container. ComponentClass.__container__ = ContainerConstructor; return ContainerConstructor; } module.exports = { injectDefaultVariablesProvider: injectDefaultVariablesProvider, buildCompatContainer: buildCompatContainer };
angular.module('proton', [ 'gettext', 'as.sortable', 'cgNotify', 'ngCookies', 'ngIcal', 'ngMessages', 'ngSanitize', 'ngScrollbars', 'pikaday', 'ui.router', 'ui.codemirror', // Constant 'proton.constants', 'proton.core', 'proton.outside', 'proton.utils', 'proton.user', // templates 'templates-app', // App 'proton.routes', 'proton.composer', 'proton.commons', 'proton.bugReport', 'proton.browserSupport', // Config 'proton.config', 'proton.analytics', 'proton.search', 'proton.ui', 'proton.dnd', 'proton.sidebar', 'proton.attachments', 'proton.authentication', 'proton.elements', 'proton.members', 'proton.labels', 'proton.autoresponder', 'proton.filter', 'proton.domains', 'proton.address', 'proton.message', 'proton.conversation', 'proton.organization', 'proton.squire', 'proton.wizard', 'proton.contact', // Controllers 'proton.settings', 'proton.dashboard', 'proton.vpn', 'proton.payment', 'proton.formUtils' ]) /** * Check if the current browser owns some requirements */ .config(() => { const isGoodPrngAvailable = () => { if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) { return true; } else if (typeof window !== 'undefined' && typeof window.msCrypto === 'object' && typeof window.msCrypto.getRandomValues === 'function') { return true; } return false; }; const isSessionStorageAvailable = () => { return (typeof (sessionStorage) !== 'undefined'); }; if (isSessionStorageAvailable() === false) { alert('Error: sessionStorage is required to use ProtonMail.'); setTimeout(() => { window.location = 'https://protonmail.com/support/knowledge-base/sessionstorage/'; }, 1000); } if (isGoodPrngAvailable() === false) { alert('Error: a PRNG is required to use ProtonMail.'); setTimeout(() => { window.location = 'https://protonmail.com/support/knowledge-base/prng/'; }, 1000); } }) .config((urlProvider, CONFIG, notificationProvider) => { urlProvider.setBaseUrl(CONFIG.apiUrl); notificationProvider.template('templates/notifications/base.tpl.html'); }) .run(( $document, $rootScope, $state, $window, logoutManager, // Keep the logoutManager here to lunch it authentication, networkActivityTracker, CONSTANTS, tools ) => { FastClick.attach(document.body); // Manage responsive changes window.addEventListener('resize', _.debounce(tools.mobileResponsive, 50)); window.addEventListener('orientationchange', tools.mobileResponsive); tools.mobileResponsive(); $rootScope.showWelcome = true; // SVG Polyfill for Edge window.svg4everybody(); window.svgeezy.init(false, 'png'); // Set new relative time thresholds moment.relativeTimeThreshold('s', 59); // s seconds least number of seconds to be considered a minute moment.relativeTimeThreshold('m', 59); // m minutes least number of minutes to be considered an hour moment.relativeTimeThreshold('h', 23); // h hours least number of hours to be considered a day $rootScope.networkActivity = networkActivityTracker; }) .config(($httpProvider, CONFIG) => { // Http Intercpetor to check auth failures for xhr requests $httpProvider.interceptors.push('authHttpResponseInterceptor'); $httpProvider.interceptors.push('formatResponseInterceptor'); $httpProvider.defaults.headers.common['x-pm-appversion'] = 'Web_' + CONFIG.app_version; $httpProvider.defaults.headers.common['x-pm-apiversion'] = CONFIG.api_version; $httpProvider.defaults.headers.common.Accept = 'application/vnd.protonmail.v1+json'; $httpProvider.defaults.withCredentials = true; // initialize get if not there if (angular.isUndefined($httpProvider.defaults.headers.get)) { $httpProvider.defaults.headers.get = {}; } // disable IE ajax request caching (don't use If-Modified-Since) $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache'; $httpProvider.defaults.headers.get.Pragma = 'no-cache'; }) .run(($rootScope, $location, $state, authentication, $log, networkActivityTracker, AppModel) => { $rootScope.$on('$stateChangeStart', (event, toState) => { networkActivityTracker.clear(); const isLogin = (toState.name === 'login'); const isSub = (toState.name === 'login.sub'); const isUpgrade = (toState.name === 'upgrade'); const isSupport = (toState.name.includes('support')); const isAccount = (toState.name === 'account'); const isSignup = (toState.name === 'signup' || toState.name === 'pre-invite'); const isUnlock = (toState.name === 'login.unlock'); const isOutside = (toState.name.includes('eo')); const isReset = (toState.name.includes('reset')); const isPrinter = (toState.name === 'printer'); const isPgp = (toState.name === 'pgp'); if (isUnlock && $rootScope.isLoggedIn) { $log.debug('appjs:(isUnlock && $rootScope.isLoggedIn)'); return; } else if ($rootScope.isLoggedIn && !$rootScope.isLocked && isUnlock) { // If already logged in and unlocked and on the unlock page: redirect to inbox $log.debug('appjs:($rootScope.isLoggedIn && !$rootScope.isLocked && isUnlock)'); event.preventDefault(); $state.go('secured.inbox'); return; } else if (isLogin || isSub || isSupport || isAccount || isSignup || isOutside || isUpgrade || isReset || isPrinter || isPgp) { // if on the login, support, account, or signup pages dont require authentication $log.debug('appjs:(isLogin || isSub || isSupport || isAccount || isSignup || isOutside || isUpgrade || isReset || isPrinter || isPgp)'); return; // no need to redirect } // now, redirect only not authenticated if (!authentication.isLoggedIn()) { event.preventDefault(); // stop current execution $state.go('login'); // go to login } }); $rootScope.$on('$stateChangeSuccess', () => { // Hide requestTimeout AppModel.set('requestTimeout', false); // Hide all the tooltip $('.tooltip').not(this).hide(); // Close navbar on mobile $('.navbar-toggle').click(); $('#loading_pm, #pm_slow, #pm_slow2').remove(); }); }) // // Rejection manager // .run(($rootScope, $state) => { $rootScope.$on('$stateChangeError', (event, current, previous, rejection, ...arg) => { console.error('stateChangeError', event, current, previous, rejection, arg); $state.go('support.message', { data: {} }); }); }) // // Console messages // .run((consoleMessage) => consoleMessage()) .config(($logProvider, $compileProvider, $qProvider, CONFIG) => { const debugInfo = CONFIG.debug || false; $logProvider.debugEnabled(debugInfo); $compileProvider.debugInfoEnabled(debugInfo); $qProvider.errorOnUnhandledRejections(debugInfo); }) .config((CONFIG, CONSTANTS) => { // Bind env on deploy const env = 'NODE_ENV'; // default localhost const localhost = 'NODE@ENV'.replace('@', '_'); // prevent auto replace const REGEXP_HOST = /proton(mail|vpn)\.(com|blue|host)$/; // Check if we can run the application if (env !== localhost && !REGEXP_HOST.test(window.location.host)) { const img = new Image(); img.width = 0; img.height = 0; img.src = CONSTANTS.URL_INFO; document.body.appendChild(img); } });
import logging import riberry from ..task_queue import TaskQueue log = logging.getLogger(__name__) def background(queue: TaskQueue): riberry.app.tasks.echo() with queue.lock: if not queue.limit_reached(): riberry.app.tasks.poll(track_executions=True, filter_func=lambda _: not queue.limit_reached()) else: log.debug('Queue limit reached, skipped task polling') riberry.app.tasks.refresh()
# Copyright The OpenTelemetry 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. import json import typing from unittest import mock import httpretty import urllib3 import urllib3.exceptions from opentelemetry import context, trace from opentelemetry.instrumentation.urllib3 import ( _SUPPRESS_HTTP_INSTRUMENTATION_KEY, URLLib3Instrumentor, ) from opentelemetry.instrumentation.utils import _SUPPRESS_INSTRUMENTATION_KEY from opentelemetry.propagate import get_global_textmap, set_global_textmap from opentelemetry.semconv.trace import SpanAttributes from opentelemetry.test.mock_textmap import MockTextMapPropagator from opentelemetry.test.test_base import TestBase # pylint: disable=too-many-public-methods class TestURLLib3Instrumentor(TestBase): HTTP_URL = "http://httpbin.org/status/200" HTTPS_URL = "https://httpbin.org/status/200" def setUp(self): super().setUp() URLLib3Instrumentor().instrument() httpretty.enable(allow_net_connect=False) httpretty.register_uri(httpretty.GET, self.HTTP_URL, body="Hello!") httpretty.register_uri(httpretty.GET, self.HTTPS_URL, body="Hello!") httpretty.register_uri(httpretty.POST, self.HTTP_URL, body="Hello!") def tearDown(self): super().tearDown() URLLib3Instrumentor().uninstrument() httpretty.disable() httpretty.reset() def assert_span(self, exporter=None, num_spans=1): if exporter is None: exporter = self.memory_exporter span_list = exporter.get_finished_spans() self.assertEqual(num_spans, len(span_list)) if num_spans == 0: return None if num_spans == 1: return span_list[0] return span_list def assert_success_span( self, response: urllib3.response.HTTPResponse, url: str ): self.assertEqual(b"Hello!", response.data) span = self.assert_span() self.assertIs(trace.SpanKind.CLIENT, span.kind) self.assertEqual("HTTP GET", span.name) attributes = { SpanAttributes.HTTP_METHOD: "GET", SpanAttributes.HTTP_URL: url, SpanAttributes.HTTP_STATUS_CODE: 200, } self.assertEqual(attributes, span.attributes) def assert_exception_span(self, url: str): span = self.assert_span() attributes = { SpanAttributes.HTTP_METHOD: "GET", SpanAttributes.HTTP_URL: url, } self.assertEqual(attributes, span.attributes) self.assertEqual( trace.status.StatusCode.ERROR, span.status.status_code ) @staticmethod def perform_request( url: str, headers: typing.Mapping = None, retries: urllib3.Retry = None ) -> urllib3.response.HTTPResponse: if retries is None: retries = urllib3.Retry.from_int(0) pool = urllib3.PoolManager() return pool.request("GET", url, headers=headers, retries=retries) def test_basic_http_success(self): response = self.perform_request(self.HTTP_URL) self.assert_success_span(response, self.HTTP_URL) def test_basic_http_success_using_connection_pool(self): pool = urllib3.HTTPConnectionPool("httpbin.org") response = pool.request("GET", "/status/200") self.assert_success_span(response, self.HTTP_URL) def test_basic_https_success(self): response = self.perform_request(self.HTTPS_URL) self.assert_success_span(response, self.HTTPS_URL) def test_basic_https_success_using_connection_pool(self): pool = urllib3.HTTPSConnectionPool("httpbin.org") response = pool.request("GET", "/status/200") self.assert_success_span(response, self.HTTPS_URL) def test_basic_not_found(self): url_404 = "http://httpbin.org/status/404" httpretty.register_uri(httpretty.GET, url_404, status=404) response = self.perform_request(url_404) self.assertEqual(404, response.status) span = self.assert_span() self.assertEqual( 404, span.attributes.get(SpanAttributes.HTTP_STATUS_CODE) ) self.assertIs(trace.status.StatusCode.ERROR, span.status.status_code) def test_basic_http_non_default_port(self): url = "http://httpbin.org:666/status/200" httpretty.register_uri(httpretty.GET, url, body="Hello!") response = self.perform_request(url) self.assert_success_span(response, url) def test_basic_http_absolute_url(self): url = "http://httpbin.org:666/status/200" httpretty.register_uri(httpretty.GET, url, body="Hello!") pool = urllib3.HTTPConnectionPool("httpbin.org", port=666) response = pool.request("GET", url) self.assert_success_span(response, url) def test_url_open_explicit_arg_parameters(self): url = "http://httpbin.org:666/status/200" httpretty.register_uri(httpretty.GET, url, body="Hello!") pool = urllib3.HTTPConnectionPool("httpbin.org", port=666) response = pool.urlopen(method="GET", url="/status/200") self.assert_success_span(response, url) def test_uninstrument(self): URLLib3Instrumentor().uninstrument() response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) self.assert_span(num_spans=0) # instrument again to avoid warning message on tearDown URLLib3Instrumentor().instrument() def test_suppress_instrumntation(self): suppression_keys = ( _SUPPRESS_HTTP_INSTRUMENTATION_KEY, _SUPPRESS_INSTRUMENTATION_KEY, ) for key in suppression_keys: self.memory_exporter.clear() with self.subTest(key=key): token = context.attach(context.set_value(key, True)) try: response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) finally: context.detach(token) self.assert_span(num_spans=0) def test_context_propagation(self): previous_propagator = get_global_textmap() try: set_global_textmap(MockTextMapPropagator()) response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) span = self.assert_span() headers = dict(httpretty.last_request().headers) self.assertIn(MockTextMapPropagator.TRACE_ID_KEY, headers) self.assertEqual( headers[MockTextMapPropagator.TRACE_ID_KEY], str(span.get_span_context().trace_id), ) self.assertIn(MockTextMapPropagator.SPAN_ID_KEY, headers) self.assertEqual( headers[MockTextMapPropagator.SPAN_ID_KEY], str(span.get_span_context().span_id), ) finally: set_global_textmap(previous_propagator) def test_custom_tracer_provider(self): tracer_provider, exporter = self.create_tracer_provider() tracer_provider = mock.Mock(wraps=tracer_provider) URLLib3Instrumentor().uninstrument() URLLib3Instrumentor().instrument(tracer_provider=tracer_provider) response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) self.assert_span(exporter=exporter) self.assertEqual(1, tracer_provider.get_tracer.call_count) @mock.patch( "urllib3.connectionpool.HTTPConnectionPool._make_request", side_effect=urllib3.exceptions.ConnectTimeoutError, ) def test_request_exception(self, _): with self.assertRaises(urllib3.exceptions.ConnectTimeoutError): self.perform_request( self.HTTP_URL, retries=urllib3.Retry(connect=False) ) self.assert_exception_span(self.HTTP_URL) @mock.patch( "urllib3.connectionpool.HTTPConnectionPool._make_request", side_effect=urllib3.exceptions.ProtocolError, ) def test_retries_do_not_create_spans(self, _): with self.assertRaises(urllib3.exceptions.MaxRetryError): self.perform_request(self.HTTP_URL, retries=urllib3.Retry(1)) # expect only a single span (retries are ignored) self.assert_exception_span(self.HTTP_URL) def test_url_filter(self): def url_filter(url): return url.split("?")[0] URLLib3Instrumentor().uninstrument() URLLib3Instrumentor().instrument(url_filter=url_filter) response = self.perform_request(self.HTTP_URL + "?e=mcc") self.assert_success_span(response, self.HTTP_URL) def test_credential_removal(self): url = "http://username:[email protected]/status/200" response = self.perform_request(url) self.assert_success_span(response, self.HTTP_URL) def test_hooks(self): def request_hook(span, request, body, headers): span.update_name("name set from hook") def response_hook(span, request, response): span.set_attribute("response_hook_attr", "value") URLLib3Instrumentor().uninstrument() URLLib3Instrumentor().instrument( request_hook=request_hook, response_hook=response_hook ) response = self.perform_request(self.HTTP_URL) self.assertEqual(b"Hello!", response.data) span = self.assert_span() self.assertEqual(span.name, "name set from hook") self.assertIn("response_hook_attr", span.attributes) self.assertEqual(span.attributes["response_hook_attr"], "value") def test_request_hook_params(self): def request_hook(span, request, headers, body): span.set_attribute("request_hook_headers", json.dumps(headers)) span.set_attribute("request_hook_body", body) URLLib3Instrumentor().uninstrument() URLLib3Instrumentor().instrument(request_hook=request_hook,) headers = {"header1": "value1", "header2": "value2"} body = "param1=1&param2=2" pool = urllib3.HTTPConnectionPool("httpbin.org") response = pool.request( "POST", "/status/200", body=body, headers=headers ) self.assertEqual(b"Hello!", response.data) span = self.assert_span() self.assertIn("request_hook_headers", span.attributes) self.assertEqual( span.attributes["request_hook_headers"], json.dumps(headers) ) self.assertIn("request_hook_body", span.attributes) self.assertEqual(span.attributes["request_hook_body"], body)
import { Link } from "gatsby" import PropTypes from "prop-types" import React from "react" const Header = ({ siteTitle }) => ( <header style={{ marginBottom: `1.45rem`, }} > <div style={{ margin: `0 auto`, maxWidth: 960, padding: `1.45rem 1.0875rem`, }} > <h1 style={{ margin: 0 }}> <Link to="/" style={{ color: `white`, textDecoration: `underline`, textDecorationStyle: 'wavy', }} > {siteTitle} </Link> </h1> </div> </header> ) Header.propTypes = { siteTitle: PropTypes.string, } Header.defaultProps = { siteTitle: ``, } export default Header
(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else { // Browser globals factory(jQuery); } } (function ($) { var d = [], doc = $(document), ua = navigator.userAgent.toLowerCase(), wndw = $(window), w = []; var browser = { ieQuirks: null, expression: true, msie: /msie/.test(ua) && !/opera/.test(ua), opera: /opera/.test(ua) }; browser.ie6 = browser.msie && /msie 6./.test(ua) && typeof window['XMLHttpRequest'] !== 'object'; browser.ie7 = browser.msie && /msie 7.0/.test(ua); /* * Feature-Detection for Expression */ try { document.createElement('div').style.setExpression('height'); document.createElement('div').style.removeExpression('height'); } catch (e) { browser.expression = false; } /* * Create and display a modal dialog. * * @param {string, object} data A string, jQuery object or DOM object * @param {object} [options] An optional object containing options overrides */ $.modal = function (data, options) { return $.modal.impl.init(data, options); }; /* * Close the modal dialog. */ $.modal.close = function () { $.modal.impl.close(); }; /* * Set focus on first or last visible input in the modal dialog. To focus on the last * element, call $.modal.focus('last'). If no input elements are found, focus is placed * on the data wrapper element. */ $.modal.focus = function (pos) { $.modal.impl.focus(pos); }; /* * Determine and set the dimensions of the modal dialog container. * setPosition() is called if the autoPosition option is true. */ $.modal.setContainerDimensions = function () { $.modal.impl.setContainerDimensions(); }; /* * Re-position the modal dialog. */ $.modal.setPosition = function () { $.modal.impl.setPosition(); }; /* * Update the modal dialog. If new dimensions are passed, they will be used to determine * the dimensions of the container. * * setContainerDimensions() is called, which in turn calls setPosition(), if enabled. * Lastly, focus() is called is the focus option is true. */ $.modal.update = function (height, width) { $.modal.impl.update(height, width); }; /* * Chained function to create a modal dialog. * * @param {object} [options] An optional object containing options overrides */ $.fn.modal = function (options) { return $.modal.impl.init(this, options); }; /* * SimpleModal default options * * appendTo: (String:'body') The jQuery selector to append the elements to. For .NET, use 'form'. * focus: (Boolean:true) Focus in the first visible, enabled element? * opacity: (Number:50) The opacity value for the overlay div, from 0 - 100 * overlayId: (String:'simplemodal-overlay') The DOM element id for the overlay div * overlayCss: (Object:{}) The CSS styling for the overlay div * containerId: (String:'simplemodal-container') The DOM element id for the container div * containerCss: (Object:{}) The CSS styling for the container div * dataId: (String:'simplemodal-data') The DOM element id for the data div * dataCss: (Object:{}) The CSS styling for the data div * minHeight: (Number:null) The minimum height for the container * minWidth: (Number:null) The minimum width for the container * maxHeight: (Number:null) The maximum height for the container. If not specified, the window height is used. * maxWidth: (Number:null) The maximum width for the container. If not specified, the window width is used. * autoResize: (Boolean:false) Automatically resize the container if it exceeds the browser window dimensions? * autoPosition: (Boolean:true) Automatically position the container upon creation and on window resize? * zIndex: (Number: 1000) Starting z-index value * close: (Boolean:true) If true, closeHTML, escClose and overClose will be used if set. If false, none of them will be used. * closeHTML: (String:'<a class="modalCloseImg" title="Close"></a>') The HTML for the default close link. SimpleModal will automatically add the closeClass to this element. * closeClass: (String:'simplemodal-close') The CSS class used to bind to the close event * escClose: (Boolean:true) Allow Esc keypress to close the dialog? * overlayClose: (Boolean:false) Allow click on overlay to close the dialog? * fixed: (Boolean:true) If true, the container will use a fixed position. If false, it will use a absolute position (the dialog will scroll with the page) * position: (Array:null) Position of container [top, left]. Can be number of pixels or percentage * persist: (Boolean:false) Persist the data across modal calls? Only used for existing DOM elements. If true, the data will be maintained across modal calls, if false, the data will be reverted to its original state. * modal: (Boolean:true) User will be unable to interact with the page below the modal or tab away from the dialog. If false, the overlay, iframe, and certain events will be disabled allowing the user to interact with the page below the dialog. * onOpen: (Function:null) The callback function used in place of SimpleModal's open * onShow: (Function:null) The callback function used after the modal dialog has opened * onClose: (Function:null) The callback function used in place of SimpleModal's close */ $.modal.defaults = { appendTo: 'body', focus: true, opacity: 50, overlayId: 'simplemodal-overlay', overlayCss: {}, containerId: 'simplemodal-container', containerCss: {}, dataId: 'simplemodal-data', dataCss: {}, minHeight: null, minWidth: null, maxHeight: null, maxWidth: null, autoResize: false, autoPosition: true, zIndex: 1000, close: true, closeHTML: '<a class="modalCloseImg" title="Close"></a>', closeClass: 'simplemodal-close', escClose: true, overlayClose: false, fixed: true, position: null, persist: false, modal: true, onOpen: null, onShow: null, onClose: null }; /* * Main modal object * o = options */ $.modal.impl = { /* * Contains the modal dialog elements and is the object passed * back to the callback (onOpen, onShow, onClose) functions */ d: {}, /* * Initialize the modal dialog */ init: function (data, options) { var s = this; // don't allow multiple calls if (s.d.data) { return false; } // $.support.boxModel is undefined if checked earlier browser.ieQuirks = browser.msie && !$.support.boxModel; // merge defaults and user options s.o = $.extend({}, $.modal.defaults, options); // keep track of z-index s.zIndex = s.o.zIndex; // set the onClose callback flag s.occb = false; // determine how to handle the data based on its type if (typeof data === 'object') { // convert DOM object to a jQuery object data = data instanceof $ ? data : $(data); s.d.placeholder = false; // if the object came from the DOM, keep track of its parent if (data.parent().parent().size() > 0) { data.before($('<span></span>') .attr('id', 'simplemodal-placeholder') .css({ display: 'none' })); s.d.placeholder = true; s.display = data.css('display'); // persist changes? if not, make a clone of the element if (!s.o.persist) { s.d.orig = data.clone(true); } } } else if (typeof data === 'string' || typeof data === 'number') { // just insert the data as innerHTML data = $('<div></div>').html(data); } else { // unsupported data type! alert('SimpleModal Error: Unsupported data type: ' + typeof data); return s; } // create the modal overlay, container and, if necessary, iframe s.create(data); data = null; // display the modal dialog s.open(); // useful for adding events/manipulating data in the modal dialog if ($.isFunction(s.o.onShow)) { s.o.onShow.apply(s, [s.d]); } // don't break the chain =) return s; }, /* * Create and add the modal overlay and container to the page */ create: function (data) { var s = this; // get the window properties s.getDimensions(); // add an iframe to prevent select options from bleeding through // @todo: please remove ie hacks if (s.o.modal && browser.ie6) { s.d.iframe = $('<iframe src="javascript:false;"></iframe>') .css($.extend(s.o.iframeCss, { display: 'none', opacity: 0, position: 'fixed', height: w[0], width: w[1], zIndex: s.o.zIndex, top: 0, left: 0 })) .appendTo(s.o.appendTo); } // create the overlay s.d.overlay = $('<div></div>') .attr('id', s.o.overlayId) .addClass('simplemodal-overlay') .css($.extend(s.o.overlayCss, { display: 'none', opacity: s.o.opacity / 100, height: s.o.modal ? d[0] : 0, width: s.o.modal ? d[1] : 0, position: 'fixed', left: 0, top: 0, zIndex: s.o.zIndex + 1 })) .appendTo(s.o.appendTo); // create the container s.d.container = $('<div></div>') .attr('id', s.o.containerId) .addClass('simplemodal-container') .css($.extend( { position: s.o.fixed ? 'fixed' : 'absolute' }, s.o.containerCss, { display: 'none', zIndex: s.o.zIndex + 2 } )) .append(s.o.close && s.o.closeHTML ? $(s.o.closeHTML).addClass(s.o.closeClass) : '') .appendTo(s.o.appendTo); s.d.wrap = $('<div></div>') .attr('tabIndex', -1) .addClass('simplemodal-wrap') .css({ height: '100%', outline: 0, width: '100%' }) .appendTo(s.d.container); // add styling and attributes to the data // append to body to get correct dimensions, then move to wrap s.d.data = data .attr('id', data.attr('id') || s.o.dataId) .addClass('simplemodal-data') .css($.extend(s.o.dataCss, { display: 'none' })) .appendTo('body'); data = null; s.setContainerDimensions(); s.d.data.appendTo(s.d.wrap); // fix issues with IE // @todo: please remove ie hacks if (browser.ie6 || browser.ieQuirks && browser.expression === true) { s.fixIE(); } }, /* * Bind events */ bindEvents: function () { var s = this; // bind the close event to any element with the closeClass class $('.' + s.o.closeClass).bind('click.simplemodal', function (e) { e.preventDefault(); s.close(); }); // bind the overlay click to the close function, if enabled if (s.o.modal && s.o.close && s.o.overlayClose) { s.d.overlay.bind('click.simplemodal', function (e) { e.preventDefault(); s.close(); }); } // bind keydown events doc.bind('keydown.simplemodal', function (e) { if (s.o.modal && e.keyCode === 9) { // TAB s.watchTab(e); } else if ((s.o.close && s.o.escClose) && e.keyCode === 27) { // ESC e.preventDefault(); s.close(); } }); // update window size wndw.bind('resize.simplemodal orientationchange.simplemodal', function () { // redetermine the window width/height s.getDimensions(); // reposition the dialog s.o.autoResize ? s.setContainerDimensions() : s.o.autoPosition && s.setPosition(); // @todo: please remove ie hacks if (browser.ie6 || browser.ieQuirks && browser.expression === true) { s.fixIE(); } else if (s.o.modal) { // update the iframe & overlay s.d.iframe && s.d.iframe.css({ height: w[0], width: w[1] }); s.d.overlay.css({ height: d[0], width: d[1] }); } }); }, /* * Unbind events */ unbindEvents: function () { $('.' + this.o.closeClass).unbind('click.simplemodal'); doc.unbind('keydown.simplemodal'); wndw.unbind('.simplemodal'); this.d.overlay.unbind('click.simplemodal'); }, /* * Fix issues in IE6 and IE7 in quirks mode */ fixIE: function () { var s = this, p = s.o.position; // simulate fixed position - adapted from BlockUI $.each([s.d.iframe || null, !s.o.modal ? null : s.d.overlay, s.d.container.css('position') === 'fixed' ? s.d.container : null], function (i, el) { if (el) { var bch = 'document.body.clientHeight', bcw = 'document.body.clientWidth', bsh = 'document.body.scrollHeight', bsl = 'document.body.scrollLeft', bst = 'document.body.scrollTop', bsw = 'document.body.scrollWidth', ch = 'document.documentElement.clientHeight', cw = 'document.documentElement.clientWidth', sl = 'document.documentElement.scrollLeft', st = 'document.documentElement.scrollTop', s = el[0].style; s.position = 'absolute'; if (i < 2) { try { s.removeExpression('height'); s.removeExpression('width'); s.setExpression('height', '' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + "px"'); s.setExpression('width', '' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + "px"'); } catch (e) { } } else { var te, le; if (p && p.constructor === Array) { var top = p[0] ? typeof p[0] === 'number' ? p[0].toString() : p[0].replace(/px/, '') : el.css('top').replace(/px/, ''); te = top.indexOf('%') === -1 ? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"' : parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'; if (p[1]) { var left = typeof p[1] === 'number' ? p[1].toString() : p[1].replace(/px/, ''); le = left.indexOf('%') === -1 ? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"' : parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'; } } else { te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"'; le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"'; } try { s.removeExpression('top'); s.removeExpression('left'); s.setExpression('top', te); s.setExpression('left', le); } catch (e) { } } } }); }, /* * Place focus on the first or last visible input */ focus: function (pos) { var s = this, p = pos && $.inArray(pos, ['first', 'last']) !== -1 ? pos : 'first'; // focus on dialog or the first visible/enabled input element var input = $(':input:enabled:visible:' + p, s.d.wrap); setTimeout(function () { input.length > 0 ? input.focus() : s.d.wrap.focus(); }, 10); }, getDimensions: function () { // fix a jQuery bug with determining the window height - use innerHeight if available var s = this, h = typeof window.innerHeight === 'undefined' ? wndw.height() : window.innerHeight; d = [doc.height(), doc.width()]; w = [h, wndw.width()]; }, getVal: function (v, d) { return v ? (typeof v === 'number' ? v : v === 'auto' ? 0 : v.indexOf('%') > 0 ? ((parseInt(v.replace(/%/, '')) / 100) * (d === 'h' ? w[0] : w[1])) : parseInt(v.replace(/px/, ''))) : null; }, /* * Update the container. Set new dimensions, if provided. * Focus, if enabled. Re-bind events. */ update: function (height, width) { var s = this; // prevent update if dialog does not exist if (!s.d.data) { return false; } // reset orig values s.d.origHeight = s.getVal(height, 'h'); s.d.origWidth = s.getVal(width, 'w'); // hide data to prevent screen flicker s.d.data.hide(); height && s.d.container.css('height', height); width && s.d.container.css('width', width); s.setContainerDimensions(); s.d.data.show(); s.o.focus && s.focus(); // rebind events s.unbindEvents(); s.bindEvents(); }, setContainerDimensions: function () { var s = this, badIE = browser.ie6 || browser.ie7; // get the dimensions for the container and data var ch = s.d.origHeight ? s.d.origHeight : browser.opera ? s.d.container.height() : s.getVal(badIE ? s.d.container[0].currentStyle['height'] : s.d.container.css('height'), 'h'), cw = s.d.origWidth ? s.d.origWidth : browser.opera ? s.d.container.width() : s.getVal(badIE ? s.d.container[0].currentStyle['width'] : s.d.container.css('width'), 'w'), dh = s.d.data.outerHeight(true), dw = s.d.data.outerWidth(true); s.d.origHeight = s.d.origHeight || ch; s.d.origWidth = s.d.origWidth || cw; // mxoh = max option height, mxow = max option width var mxoh = s.o.maxHeight ? s.getVal(s.o.maxHeight, 'h') : null, mxow = s.o.maxWidth ? s.getVal(s.o.maxWidth, 'w') : null, mh = mxoh && mxoh < w[0] ? mxoh : w[0], mw = mxow && mxow < w[1] ? mxow : w[1]; // moh = min option height var moh = s.o.minHeight ? s.getVal(s.o.minHeight, 'h') : 'auto'; if (!ch) { if (!dh) { ch = moh; } else { if (dh > mh) { ch = mh; } else if (s.o.minHeight && moh !== 'auto' && dh < moh) { ch = moh; } else { ch = dh; } } } else { ch = s.o.autoResize && ch > mh ? mh : ch < moh ? moh : ch; } // mow = min option width var mow = s.o.minWidth ? s.getVal(s.o.minWidth, 'w') : 'auto'; if (!cw) { if (!dw) { cw = mow; } else { if (dw > mw) { cw = mw; } else if (s.o.minWidth && mow !== 'auto' && dw < mow) { cw = mow; } else { cw = dw; } } } else { cw = s.o.autoResize && cw > mw ? mw : cw < mow ? mow : cw; } s.d.container.css({ height: ch, width: cw }); s.d.wrap.css({ overflow: (dh > ch || dw > cw) ? 'auto' : 'visible' }); s.o.autoPosition && s.setPosition(); }, setPosition: function () { var s = this, top, left, hc = (w[0] / 2) - (s.d.container.outerHeight(true) / 2), vc = (w[1] / 2) - (s.d.container.outerWidth(true) / 2), st = s.d.container.css('position') !== 'fixed' ? wndw.scrollTop() : 0; if (s.o.position && Object.prototype.toString.call(s.o.position) === '[object Array]') { top = st + (s.o.position[0] || hc); left = s.o.position[1] || vc; } else { top = st + hc; left = vc; } s.d.container.css({ left: left, top: top }); }, watchTab: function (e) { var s = this; if ($(e.target).parents('.simplemodal-container').length > 0) { // save the list of inputs s.inputs = $(':input:enabled:visible:first, :input:enabled:visible:last', s.d.data[0]); // if it's the first or last tabbable element, refocus if ((!e.shiftKey && e.target === s.inputs[s.inputs.length - 1]) || (e.shiftKey && e.target === s.inputs[0]) || s.inputs.length === 0) { e.preventDefault(); var pos = e.shiftKey ? 'last' : 'first'; s.focus(pos); } } else { // might be necessary when custom onShow callback is used e.preventDefault(); s.focus(); } }, /* * Open the modal dialog elements * - Note: If you use the onOpen callback, you must "show" the * overlay and container elements manually * (the iframe will be handled by SimpleModal) */ open: function () { var s = this; // display the iframe s.d.iframe && s.d.iframe.show(); if ($.isFunction(s.o.onOpen)) { // execute the onOpen callback s.o.onOpen.apply(s, [s.d]); } else { // display the remaining elements s.d.overlay.show(); s.d.container.show(); s.d.data.show(); } s.o.focus && s.focus(); // bind default events s.bindEvents(); }, /* * Close the modal dialog * - Note: If you use an onClose callback, you must remove the * overlay, container and iframe elements manually * * @param {boolean} external Indicates whether the call to this * function was internal or external. If it was external, the * onClose callback will be ignored */ close: function () { var s = this; // prevent close when dialog does not exist if (!s.d.data) { return false; } // remove the default events s.unbindEvents(); if ($.isFunction(s.o.onClose) && !s.occb) { // set the onClose callback flag s.occb = true; // execute the onClose callback s.o.onClose.apply(s, [s.d]); } else { // if the data came from the DOM, put it back if (s.d.placeholder) { var ph = $('#simplemodal-placeholder'); // save changes to the data? if (s.o.persist) { // insert the (possibly) modified data back into the DOM ph.replaceWith(s.d.data.removeClass('simplemodal-data').css('display', s.display)); } else { // remove the current and insert the original, // unmodified data back into the DOM s.d.data.hide().remove(); ph.replaceWith(s.d.orig); } } else { // otherwise, remove it s.d.data.hide().remove(); } // remove the remaining elements s.d.container.hide().remove(); s.d.overlay.hide(); s.d.iframe && s.d.iframe.hide().remove(); s.d.overlay.remove(); // reset the dialog object s.d = {}; } } }; }));
const Employee = require("./Employee"); class Engineer extends Employee{ constructor(name, id, email, github) { super(name, id, email); this.github = github; } getGitHub() { return this.github; } getRole() { return this.constructor.name; } } module.exports = Engineer;
const fs = require('fs'); const path = require('path'); const marked = require('marked'); let workspacePath = path.join(__dirname, '../../workspace'); let data = { files: [], show:true, } const Nodes = { template: ` <div id='nodes'> <transition name="slide-fade2"> <div class='nodeList' v-if='show'> <div class='local'> <h3>本地笔记</h3> <ul> <li v-for='file in files'><a href='javascript:' @click.stop='readFileClick($event)'>{{file}}</a></li> </ul> </div> <div class='online'> <h3>在线笔记</h3> <ul> <li v-for='file in files'><a href='javascript:' @click.stop='readFileClick($event)'>{{file}}</a></li> </ul> </div> </div> </transition> <transition name="fade"> <div class='previewBox' v-if='!show'> <span class='close' @click='backClick'></span> <div class='preview' ></div> </div> </transition> </div>`, methods: { readFileClick:function(ev){ this.show = false; let filePath = path.join(workspacePath,ev.target.innerText); fs.readFile(filePath,'UTF-8',(err,data)=>{ if(err) console.log('读取文件失败'); let preview = document.querySelector('#nodes .preview'); preview.innerHTML = marked(data); }); }, backClick:function(){ this.show = true; } }, data: function () { return data; }, beforeCreate: function () { fs.readdir(workspacePath, (err, files) => { if (err) console.log('读取workspace失败'); console.log(files) data.files = files; }); } }; // 将组件导出 module.exports = { Nodes }
# -*- coding: utf-8 -*- from simulator.environments.DtnAbstractSimEnvironment import SimEnvironment import numpy as np import pandas as pd import os from pathlib import Path import random from simulator.utils.DtnUtils import load_class_dynamically from warnings import warn class DtnSimEnviornment(SimEnvironment): def reset(self): for node in self.nodes.values(): node.reset(); del node for con in self.connections.values(): del con for mbm in self.mobility_models.values(): del mbm for rpt in self.all_results.values(): del rpt print(self.del_msg.format(os.getpid(), self.sim_id)) def initialize(self): # De-pack useful global arguments self.epoch = self.config['scenario'].epoch self.seed = self.config['scenario'].seed # Initialize logger self.initialize_logger() # Set the seed for the random numbers self.set_simulation_seed() # Variable to store all results self.all_results = {} # Create all nodes self.nodes = {} for nid, node in self.config['network'].nodes.items(): # Initialize variables props = self.config[node.type] clazz = load_class_dynamically('simulator.nodes', getattr(props, 'class')) # Create node object self.nodes[nid] = clazz(self, nid, props) # Create all connections self.connections = {} for cid, con in self.config['network'].connections.items(): # Initialize variables props = self.config[con.type] o, d = con.origin, con.destination clazz = load_class_dynamically('simulator.connections', getattr(props, 'class')) # Create connections self.connections[o, d] = clazz(self, cid, o, d, props) self.connections[d, o] = clazz(self, cid, d, o, props) # Create the mobility model self.create_mobility_models() # Initialize all nodes. This can only be done after initializing the connections # because otherwise you can't know which ducts to create. for node in self.nodes.values(): node.initialize() # Initialize all ducts. This must be done after the initializing the # node because the radios must be up and running for node in self.nodes.values(): node.initialize_neighbors_and_ducts() # Initialize all connections. This must be done after initializing the ducts for o, d in self.connections: self.connections[o, d].initialize() self.connections[d, o].initialize() # Initialize all mobility models. This can only be done after initializing # the connections, since the mobility model might inherit info from them. self.initialize_mobility_models() # Complete connection initialization using info from mobility models for c in self.connections.values(): c.initialize_contacts_and_ranges() # Initialize all routers using info from mobility models. Also initialize # all endpoints using information from routers. Finally, initialize neighbor # manager with info from the mobility model for node in self.nodes.values(): node.initialize_router() node.initialize_endpoints() node.initialize_neighbor_managers() # Flag the reports that need to be generated self.reports = self.config['reports'].reports # Show initialization message print(self.init_msg.format(os.getpid(), self.sim_id, self.config_file, self.seed)) def create_mobility_models(self): # Initialize variables self.mobility_models = {} # Gather all models defined in YAML file models = {node.props.mobility_model for node in self.nodes.values()} models.update({c.props.mobility_model for c in self.connections.values()}) models = models - {None} # Iterate over models to initialize for model in models: # Find properties of this mobility model props = self.config[model] # Initialize class clazz = load_class_dynamically('simulator.mobility_models', getattr(props, 'class')) self.mobility_models[model] = clazz(self, props) def initialize_mobility_models(self): for model in self.mobility_models.values(): model.initialize() def set_simulation_seed(self): if self.seed is None: return np.random.seed(self.seed) random.seed(self.seed) def finalize_simulation(self, close_logger=True): # If the results are already available, return them if self.all_results: return self.all_results # Initialize variables self.all_results = {} # Collect all the reports for report in self.reports: # Create the report clazz = load_class_dynamically('simulator.reports', report, report) report = clazz(self) # If this report already exists, raise error if report.alias in self.all_results: continue # Store the report self.all_results[report.alias] = report.data # Compose and return result return self.all_results def validate_simulation(self): # Format validation portion of log file self.new_log_section(title='VALIDATION RESULTS') # Get the simulation results self.finalize_simulation(close_logger=False) # Perform validation process error = self._validate_sent() | \ self._validate_arrived() | \ self._validate_dropped() | \ self._validate_stored() | \ self._validate_lost() | \ self._validate_arrived_bundles() | \ self._validate_standard_data_volume() | \ self._validate_critical_data_volume() | \ self._validate_expected_data_volume() | \ self._validate_num_bundles_end() # Display warning if error detected #if error: warn('Simulation did not pass all tests. See log file for details') return (not error) def _validate_sent(self): # If the required report was not collected, skip if 'DtnSentBundlesReport' not in self.reports: return False # Perform check error = self.all_results['sent'].empty # Display error if error: self.error("No bundles were ever sent.", header=False) else: self.log("Sent bundles test successfully passed.", header=False) self.new_line() return error def _validate_arrived(self): # If the required report was not collected, skip if 'DtnArrivedBundlesReport' not in self.reports: return False # Perform check error = self.all_results['arrived'].empty # Display error if error: self.error("No bundles were received at destination.", header=False) else: self.log("Received bundles test successfully passed.", header=False) self.new_line() return error def _validate_dropped(self): # If the required report was not collected, skip if 'DtnDroppedBundlesReport' not in self.reports: return False # Get report data dropped = self.all_results['dropped'] # If no bundles dropped, pass test if dropped.empty: self.log("Dropped bundles test successfully passed.", header=False) self.new_line() return False # Find the non-critical data that was dropped v = dropped.loc[dropped.critical == False, :] self.error("'dropped' should be empty but holds:\n{}", v, header=False) self.new_line() return True def _validate_stored(self): # If the required report was not collected, skip if 'DtnStoredBundlesReport' not in self.reports: return False # Get report data stored = self.all_results['stored'] # If stored is not empty, pass test if stored.empty: self.log("Stored bundles test successfully passed.", header=False) self.new_line() return False # If stored is not empty, then error self.error("Some bundles are still stored in DTN nodes:\n{}", stored, header=False) self.new_line() return False def _validate_lost(self): # If the required report was not collected, skip if 'DtnConnLostBundlesReport' not in self.reports: return False # Get report data lost = self.all_results['lost'] # If stored is not empty, pass test if lost.empty: self.log('Lost bundles test successfully passed.', header=False) self.new_line() return False # If stored is not empty, then error self.error("'lost' should be empty by holds:\n{}", lost, header=False) self.new_line() return False def _validate_arrived_bundles(self): # If the required report was not collected, skip if 'DtnArrivedBundlesReport' not in self.reports or \ 'DtnSentBundlesReport' not in self.reports: return False # Get report data arrived = self.all_results['arrived'] sent = self.all_results['sent'] # Get the list of bids that were transmitted s_bids = set(sent.index.get_level_values('bid')) if not sent.empty else set() # Get the list of bids that were received a_bids = set(arrived.bid) if not arrived.empty else set() # Perform check - See how many bids never arrived diff = s_bids - a_bids error = bool(diff) # Display log message if error: self.error('Bundles {} do not arrive.', diff, header=False) else: self.log('All bundle Ids where accounted for.', header=False) self.new_line() return error def _validate_standard_data_volume(self): # If the required report was not collected, skip if 'DtnArrivedBundlesReport' not in self.reports or \ 'DtnSentBundlesReport' not in self.reports: return False # Get report data arrived = self.all_results['arrived'] sent = self.all_results['sent'] # If nothing was sent or received, error if sent.empty or arrived.empty: self.error('Non-critical data volume test skipped') return False # Eliminate critical data sent = sent.loc[sent.critical == False, :] arrived = arrived.loc[arrived.critical == False, :] # Compute transmitted and received data volume per flow tx_dv = sent.groupby(by='fid').data_vol.sum() rx_dv = arrived.groupby(by='fid').data_vol.sum() # Perform check. Inspired by numpy's "allclose" function atol, rtol = 1e-8, 1e-3 ok = np.abs(tx_dv.subtract(rx_dv, fill_value=0.0).values) <= (atol + rtol * np.abs(tx_dv.values)) error = not ok.ravel().all() # Check whether some flows had different transmitted and received data volume. If so, data is being lost during the simulation if error: self.error('The following non-critical flows received a data volume that is ' 'different from the transmitted data volume:', header=False) dv = pd.concat([tx_dv, rx_dv], axis=1).fillna(value=0.0) dv.columns = ['TxDataVolume', 'RxDataVolume'] self.log('{}', dv.loc[~ok.ravel(), :], header=False) else: self.log('Non-critical data volume test successfully passed.', header=False) self.new_line() return error def _validate_critical_data_volume(self): # If the required report was not collected, skip if 'DtnArrivedBundlesReport' not in self.reports or \ 'DtnSentBundlesReport' not in self.reports: return False # Get report data arrived = self.all_results['arrived'] sent = self.all_results['sent'] # If nothing was sent or received, error if sent.empty or arrived.empty: self.error('Critical data volume test skipped'); return True # Eliminate non-critical data sent = sent.loc[sent.critical == True, :] arrived = arrived.loc[arrived.critical == True, :] # Compute transmitted and received data volume per flow tx_dv = sent.groupby(by='fid').data_vol.sum() rx_dv = arrived.groupby(by='fid').data_vol.sum() # Compute the ration of rx_data_vol/tx_data_vol mult = 1.0 / tx_dv.divide(rx_dv, axis=0, fill_value=0.0) # Perform check. error = (mult < 1.0).any() # Display error message if necessary if error: self.error('The following critical flows did not receive all received data volume:', header=False) dv = pd.concat([tx_dv, rx_dv], axis=1) dv.columns = ['TxDataVolume', 'RxDataVolume'] err_dv = dv.loc[mult < 1.0, :].fillna(value=0.0) self.log('{}', err_dv, header=False) else: self.log('Critical data volume test successfully passed.', header=False) # Display informational message about critical data volume self.log('Informational data on critical data flows. Data volume multiplier:', header=False) data = {k: 'x{:.1f}'.format(v) for k, v in mult.to_dict().items()} data = pd.DataFrame.from_dict(data, orient='index').rename(columns={0:'Multiplier'}) self.log('{}', data, header=False) self.new_line() return False def _validate_expected_data_volume(self): # If the required report was not collected, skip if 'DtnSentBundlesReport' not in self.reports: return False # Initialize variables dv1, dv2 = {}, {} # Iterate over all generators in the simulation for _, node in self.nodes.items(): for gid, gen in node.generators.items(): dv1[gid] = gen.predicted_data_vol() dv2[gid] = gen.generated_data_vol() # Compute the total data volume in [Tbit] tdv1 = sum(dv1.values())/1e12 tdv2 = sum(dv2.values())/1e12 # Perform check error = not np.isclose(tdv1, tdv2) # Display error message if necessary if error: self.error('The predicted data volume is {:.6f}Tbit') self.error('The generated data volume is {:.6f}Tbit') self.error('They should match. Differences in flows are as follows:') self.error('Predicted: {}'.format(dv1)) self.error('Predicted: {}'.format(dv2)) else: self.log('Expected data volume test successfully passed.', header=False) # Finish test self.new_line() return error def _validate_num_bundles_end(self): # If the required report was not collected, skip if 'DtnArrivedBundlesReport' not in self.reports or \ 'DtnSentBundlesReport' not in self.reports or \ 'DtnConnLostBundlesReport' not in self.reports or \ 'DtnDroppedBundlesReport' not in self.reports or \ 'DtnStoredBundlesReport' not in self.reports: return False # Get report data arrived = self.all_results['arrived'] dropped = self.all_results['dropped'] stored = self.all_results['stored'] sent = self.all_results['sent'] lost = self.all_results['lost'] # Compute number of bundles n1 = sent.shape[0] # Compute number of bundles that arrive, are dropped, lost or stored n2 = arrived.shape[0] + dropped.shape[0] + \ lost.shape[0] + stored.shape[0] # Perform check (because of bundle fragmentation and critical routers # policy, the number of bundles at end will almost certainly be larger # that the number of bundles sent) error = n1 > n2 # Display error message if necessary if error: self.error('{:.0f} bundles were sent, but {:.0f} bundles were either dropped,' 'arrived, lost or stored. Where are the rest?', n1, n2, header=False) else: self.log('"Num. bundles at end" test successfully passed.', header=False) self.new_line() return error def __str__(self): return f'<DtnSimEnvironment t={self.now}>'
from django.contrib.auth.models import User from django.db import models from django_extensions.db.models import TimeStampedModel from django.utils.timezone import now class SensorType(TimeStampedModel): uid = models.SlugField(unique=True) name = models.CharField(max_length=1000) manufacturer = models.CharField(max_length=1000) description = models.CharField(max_length=10000, null=True, blank=True) class Meta: ordering = ['name', ] def __str__(self): return self.uid class Node(TimeStampedModel): uid = models.SlugField(unique=True) owner = models.ForeignKey(User) name = models.TextField(null=True, blank=True) description = models.TextField(null=True, blank=True) height = models.IntegerField(null=True) sensor_position = models.IntegerField(null=True) # 0 = no information, 1 = in backyard, 10 = just in front of the house at the street location = models.ForeignKey("SensorLocation") email = models.EmailField(null=True, blank=True) last_notify = models.DateTimeField(null=True, blank=True) description_internal = models.TextField(null=True, blank=True) # for internal purposes, should never been provided via API / dump / ... class Meta: ordering = ['uid', ] def __str__(self): return self.uid class Sensor(TimeStampedModel): node = models.ForeignKey(Node, related_name="sensors") pin = models.CharField( max_length=10, default='-', db_index=True, help_text='differentiate the sensors on one node by giving pin used', ) sensor_type = models.ForeignKey(SensorType) description = models.TextField(null=True, blank=True) public = models.BooleanField(default=False, db_index=True) class Meta: unique_together = ('node', 'pin') def __str__(self): return "{} {}".format(self.node, self.pin) class SensorData(TimeStampedModel): sensor = models.ForeignKey(Sensor, related_name="sensordatas") sampling_rate = models.IntegerField(null=True, blank=True, help_text="in milliseconds") timestamp = models.DateTimeField(default=now, db_index=True) location = models.ForeignKey("SensorLocation", blank=True) software_version = models.CharField(max_length=100, default="", help_text="sensor software version") class Meta(TimeStampedModel.Meta): index_together = (('modified', ), ) def __str__(self): return "{sensor} [{value_count}]".format( sensor=self.sensor, value_count=self.sensordatavalues.count()) SENSOR_TYPE_CHOICES = ( # ppd42ns P1 -> 1µm / SDS011 P1 -> 10µm ('P0', '1µm particles'), ('P1', '1µm particles'), ('P2', '2.5µm particles'), ('durP1', 'duration 1µm'), ('durP2', 'duration 2.5µm'), ('ratioP1', 'ratio 1µm in percent'), ('ratioP2', 'ratio 2.5µm in percent'), ('samples', 'samples'), ('min_micro', 'min_micro'), ('max_micro', 'max_micro'), # sht10-sht15; dht11, dht22; bmp180 ('temperature', 'Temperature'), # sht10-sht15; dht11, dht22 ('humidity', 'Humidity'), # bmp180 ('pressure', 'Pa'), ('altitude', 'meter'), ('pressure_sealevel', 'Pa (sealevel)'), # ('brightness', 'Brightness'), # gp2y10 ('dust_density', 'Dust density in mg/m3'), ("vo_raw", 'Dust voltage raw'), ("voltage", "Dust voltage calculated"), # dsm501a ('P10', '1µm particles'), # identical to P1 ('P25', '2.5µm particles'), # identical to P2 ('durP10', 'duration 1µm'), ('durP25', 'duration 2.5µm'), ('ratioP10', 'ratio 1µm in percent'), ('ratioP25', 'ratio 2.5µm in percent'), # ('door_state', 'door state (open/closed)'), # gpssensor ('lat', 'latitude'), ('lon', 'longitude'), ('height', 'height'), ('hdop', 'horizontal dilusion of precision'), ('timestamp', 'measured timestamp'), ('age', 'measured age'), ('satelites', 'number of satelites'), ('speed', 'current speed over ground'), ('azimuth', 'track angle'), ## noise sensor ('noise_L01', 'Sound level L01'), ('noise_L95', 'Sound level L95'), ('noise_Leq', 'Sound level Leq'), ) class SensorDataValue(TimeStampedModel): sensordata = models.ForeignKey(SensorData, related_name='sensordatavalues') value = models.TextField(db_index=True) value_type = models.CharField(max_length=100, choices=SENSOR_TYPE_CHOICES, db_index=True) class Meta: unique_together = (('sensordata', 'value_type', ), ) def __str__(self): return "{sensordata}: {value} [{value_type}]".format( sensordata=self.sensordata, value=self.value, value_type=self.value_type, ) class SensorLocation(TimeStampedModel): location = models.TextField(null=True, blank=True) latitude = models.DecimalField(max_digits=14, decimal_places=11, null=True, blank=True) longitude = models.DecimalField(max_digits=14, decimal_places=11, null=True, blank=True) indoor = models.BooleanField(default=False) street_name = models.TextField(null=True, blank=True) street_number = models.TextField(null=True, blank=True) postalcode = models.TextField(null=True, blank=True) city = models.TextField(null=True, blank=True) country = models.TextField(null=True, blank=True) traffic_in_area = models.IntegerField(null=True) # 0 = no information, 1 = far away from traffic, 10 = lot's of traffic in area oven_in_area = models.IntegerField(null=True) # 0 = no information, 1 = no ovens in area, 10 = it REALLY smells industry_in_area = models.IntegerField(null=True) # 0 = no information, 1 = no industry in area, 10 = industry all around owner = models.ForeignKey(User, null=True, blank=True, help_text="If not set, location is public.") description = models.TextField(null=True, blank=True) timestamp = models.DateTimeField(default=now) class Meta: ordering = ['location', ] def __str__(self): return "{location}".format(location=self.location)
/* eslint-disable indent */ const equipSelect = $("#equipSelect"); const equipDiv = $("#equipDiv"); const updateEquipment = url => { $.ajax({ url: `https://www.dnd5eapi.co${url}`, method: "GET" }).then(res => { if (res.desc !== undefined) { console.log(res.desc); equipDiv.html( `<tr><th> Category: </th> <td> ${res.equipment_category.name} <tr><th> Cost: </th> <td> ${res.cost.quantity} ${res.cost.unit}</td></tr> <tr><th> Weight: </th> <td> ${res.weight} lbs</td></tr> <tr><th> Description: </th> <td> ${res.desc.join(" ")} </td></tr> ` ); } else { console.log(`error: ${res.desc}`); equipDiv.html( `<tr><th> Category: </th> <td> ${res.equipment_category.name} <tr><th> Cost: </th> <td> ${res.cost.quantity} ${res.cost.unit}</td></tr> <tr><th> Weight: </th> <td> ${res.weight} lbs</td></tr> ` ); } // determine what type of equipment it is and append info accordingly switch (res.equipment_category.index) { case "adventuring-gear": if (res.gear_category.index === "equipment-packs") { equipDiv.html(` <tr><th> Cost: </th> <td> ${res.cost.quantity} ${res.cost.unit}</td></tr> <tr><th> Contents: </th></tr> `); res.contents.forEach(elem => { equipDiv.append(` <tr><td>${elem.item.name}</td><td> x ${elem.quantity}`); }); } break; case "armor": equipDiv.append(` <tr><th> Category: </th><td> ${res.armor_category} </td></tr> <tr><th> Base AC: </th><td> ${res.armor__class.base} </td></tr> <tr><th> Dex Bonus: </th><td> ${res.armor_class.dex_bonus.toString()} </td></tr> <tr><th> STR Min: </th><td> ${res.str_minimum} </td></tr> <tr><th> Stealth Disadvantage </th><td> ${res.stealth_disadvantage.toString()} </td></tr> `); break; case "mounts-and-vehicles": switch (res.vehicle_category) { case "Mounts and Other Animals": equipDiv.html(` <tr><th> Cost: </th> <td> ${res.cost.quantity} ${res.cost.unit}</td></tr> <tr><th> Speed: </th><td> ${res.speed.quantity} ${res.speed.unit} </td></tr> <tr><th> Capacity: </th><td> ${res.capacity} </td></tr> `); break; case "Waterborne Vehicles": equipDiv.html(` <tr><th> Cost: </th> <td> ${res.cost.quantity} ${res.cost.unit}</td></tr> <tr><th> Vehicle Category: </th> <td> ${res.vehicle_category} </td></tr> <tr><th> Speed: </th><td> ${res.speed.quantity} ${res.speed.unit} </td></tr>`); break; default: break; } break; case "weapon": if (res.weapon_range === "Melee") { equipDiv.append(` <tr><th> Type: </th><td> ${res.properties[0].name} </td></tr> <tr><th> Damage: </th><td> ${res.damage.damage_dice} </td></tr> <tr><th> Damage Type: </th><td> ${res.damage.damage_type.name} </td></tr> <tr><th> Range: </th><td> ${res.range.normal} </td></tr> <tr><th> Damage: </th><td> ${res.damage.damage_dice} </td></tr> `); } else { equipDiv.append(` <tr><th> Type: </th><td> ${res.properties[0].name} </td></tr> <tr><th> Damage: </th><td> ${res.damage.damage_dice} </td></tr> <tr><th> Damage Type: </th><td> ${res.damage.damage_type.name} </td></tr> <tr><th> Range: </th><td> ${res.range.normal} / ${res.range.long} </td></tr> <tr><th> Damage: </th><td> ${res.damage.damage_dice} </td></tr> `); } break; default: break; } }); }; equipSelect.on("change", function() { equipDiv.empty(); const equipUrl = $(this) .children("option:selected") .data("url"); updateEquipment(equipUrl); });
import React, {useState, useCallback} from 'react'; import {useAPI} from 'common/hooks/api'; import {Button, Col, Form, Input, Popconfirm, Row} from 'antd'; import formItem from 'hocs/formItem.hoc'; import {FORM_ELEMENT_TYPES} from 'constants/formFields.constant'; import {MasterHOC} from 'hocs/Master.hoc'; import {createTestInv, deleteTestInv, retrieveTestInv} from 'common/api/auth'; import {loadAPI} from 'common/helpers/api'; import {TestInventoryDetailColumn} from 'common/columns/testInventoryDetail.column'; import {useHandleForm} from '../../hooks/form'; import {deleteHOC} from '../../hocs/deleteHoc'; import Delete from '../../icons/Delete'; import {useTableSearch} from '../../hooks/useTableSearch'; import {CSVLink} from 'react-csv'; import { useSelector } from 'react-redux'; const {Search} = Input; export const TestInventoryScreen = () => { const { companyId } = useSelector((s) => s.user.userMeta); const {data: products} = useAPI('/products/', {}, false, true); const { data: warehouses } = useAPI(`/company-warehouse/?id=${companyId}`); const [details, setDetails] = useState([]); const [warehouseData, setWarehouseData] = useState([]); const [warehouseLoading, setWarehouseLoading] = useState(true); const [detailsLoading, setDetailsLoading] = useState(false); const [selectedProduct, setSelectedProduct] = useState(''); const [searchVal, setSearchVal] = useState(null); const {filteredData: invData, loading: invLoading, reload} = useTableSearch({ searchVal, retrieve: retrieveTestInv, }); const generateCSVData = useCallback(() => { if (!invLoading) { const temp = invData.map((i) => { return { quantity: i.quantity, product: i.product.short_code, product_info: i.product.description || '-', }; }); return { headers: [ {label: 'Product', key: 'product'}, {label: 'Product Info', key: 'product_info'}, {label: 'Quantity', key: 'quantity'}, ], data: temp, }; } return { headers: [], data: [], }; }, [invData, invLoading]); const DownloadCSVButton = useCallback(() => { const t = generateCSVData(); return ( <Row style={{display: 'inline-flex', width: '100%'}}> {/* <Col span={12}> <Button> <CSVLink filename={'warehouse-inventory.csv'} data={t.data} headers={t.headers}> Download CSV </CSVLink> </Button> </Col> */} <Col span={24} style={{marginTop: '10px'}}> {formItem({ key: 'warehouse', kwargs: { placeholder: 'Select', onChange: async (val) => { const {data} = await loadAPI(`/inv-items/?id=${val}`) setWarehouseData(data) setWarehouseLoading(false) }, }, others: { selectOptions: warehouses || [], key: 'id', customTitle: 'name', dataKeys: ['address'], }, type: FORM_ELEMENT_TYPES.SELECT, customLabel: 'Warehouse', })} </Col> </Row> ); }, [invData, generateCSVData]); console.log(invData, 'Ggg'); const {form, submit, loading} = useHandleForm({ create: createTestInv, success: 'Inventory created/edited successfully.', failure: 'Error in creating/editing Inventory.', done: () => { reload(); }, close: () => null, }); const column = [ { title: 'Product', key: 'product', dataIndex: 'product', render: (product) => <div>{product.short_code}</div>, }, { title: 'Quantity', key: 'quantity', dataIndex: 'quantity', }, { title: 'Product Info', key: 'product_info', dataIndex: 'product', render: (product) => <div>{product.description}</div>, }, { title: 'Action', key: 'operation', width: '9vw', render: (text, record) => ( <div className="row justify-evenly"> <Button type="primary" onClick={async (e) => { setSelectedProduct(record.product.short_code); setDetailsLoading(true); const {data} = await loadAPI(`/ledger-items/?id=${record.product.short_code}`, { method: 'GET', }); setDetails(data); setDetailsLoading(false); e.stopPropagation(); }}> Details </Button> {/* <Popconfirm title="Confirm Delete" onCancel={(e) => e.stopPropagation()} onConfirm={deleteHOC({ record, reload, api: deleteTestInv, success: 'Deleted Inventory Successfully', failure: 'Error in deleting Inventory', })}> <Button style={{ backgroundColor: 'transparent', boxShadow: 'none', border: 'none', padding: '1px', }} onClick={(e) => e.stopPropagation()}> <Delete /> </Button> </Popconfirm> */} </div> ), }, ]; const columnDetails = [ { title: 'Transaction No', key: 'transaction_no', dataIndex: 'transaction_no', }, { title: 'Date', key: 'date', dataIndex: 'date', render: (date) => <div>{date.slice(0, 10)}</div>, }, ...TestInventoryDetailColumn, ]; return ( <div> <div style={{display: 'flex', justifyContent: 'flex-end'}}> <div style={{width: '15vw', display: 'flex', alignItems: 'flex-end'}}> <Search onChange={(e) => setSearchVal(e.target.value)} placeholder="Search" enterButton /> </div> </div> {/* <Form onFinish={submit} form={form} layout="vertical" hideRequiredMark autoComplete="off"> <Row align="middle" gutter={32}> <Col span={8}> {formItem({ key: 'product', kwargs: { placeholder: 'Select', showSearch: true, filterOption: (input, option) => option.search.toLowerCase().indexOf(input.toLowerCase()) >= 0, }, others: { selectOptions: products || [], key: 'id', dataKeys: ['name', 'description', 'category'], customTitle: 'short_code', }, type: FORM_ELEMENT_TYPES.SELECT, customLabel: 'Product', })} </Col> <Col span={8}> {formItem({ key: 'quantity', kwargs: { placeholder: 'Quantity', }, type: FORM_ELEMENT_TYPES.INPUT, customLabel: 'Quantity', })} </Col> <Col span={4}> <Button type="primary" htmlType="submit"> Submit </Button> </Col> </Row> </Form> */} <Row gutter={32}> <Col lg={12}> <MasterHOC refresh={reload} size="small" data={warehouseData} columns={column} title="Inventory" ExtraButtonNextToTitle={DownloadCSVButton} hideRightButton loading={warehouseLoading} /> </Col> <Col lg={12}> <MasterHOC size="small" data={details} title={`${selectedProduct} Details`} hideRightButton loading={detailsLoading} columns={columnDetails} /> </Col> </Row> </div> ); }; export default TestInventoryScreen;
import { Service } from 'denali'; export default class TestService extends Service { name = 'test service'; }
# coding: utf-8 """ Kubernetes No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501 The version of the OpenAPI document: v1.20.7 Generated by: https://openapi-generator.tech """ from __future__ import absolute_import import unittest import datetime import kubernetes.client from kubernetes.client.models.v1_priority_class_list import V1PriorityClassList # noqa: E501 from kubernetes.client.rest import ApiException class TestV1PriorityClassList(unittest.TestCase): """V1PriorityClassList unit test stubs""" def setUp(self): pass def tearDown(self): pass def make_instance(self, include_optional): """Test V1PriorityClassList include_option is a boolean, when False only required params are included, when True both required and optional params are included """ # model = kubernetes.client.models.v1_priority_class_list.V1PriorityClassList() # noqa: E501 if include_optional : return V1PriorityClassList( api_version = '0', items = [ kubernetes.client.models.v1/priority_class.v1.PriorityClass( api_version = '0', description = '0', global_default = True, kind = '0', metadata = kubernetes.client.models.v1/object_meta.v1.ObjectMeta( annotations = { 'key' : '0' }, cluster_name = '0', creation_timestamp = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), deletion_grace_period_seconds = 56, deletion_timestamp = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), finalizers = [ '0' ], generate_name = '0', generation = 56, labels = { 'key' : '0' }, managed_fields = [ kubernetes.client.models.v1/managed_fields_entry.v1.ManagedFieldsEntry( api_version = '0', fields_type = '0', fields_v1 = kubernetes.client.models.fields_v1.fieldsV1(), manager = '0', operation = '0', time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), ) ], name = '0', namespace = '0', owner_references = [ kubernetes.client.models.v1/owner_reference.v1.OwnerReference( api_version = '0', block_owner_deletion = True, controller = True, kind = '0', name = '0', uid = '0', ) ], resource_version = '0', self_link = '0', uid = '0', ), preemption_policy = '0', value = 56, ) ], kind = '0', metadata = kubernetes.client.models.v1/list_meta.v1.ListMeta( continue = '0', remaining_item_count = 56, resource_version = '0', self_link = '0', ) ) else : return V1PriorityClassList( items = [ kubernetes.client.models.v1/priority_class.v1.PriorityClass( api_version = '0', description = '0', global_default = True, kind = '0', metadata = kubernetes.client.models.v1/object_meta.v1.ObjectMeta( annotations = { 'key' : '0' }, cluster_name = '0', creation_timestamp = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), deletion_grace_period_seconds = 56, deletion_timestamp = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), finalizers = [ '0' ], generate_name = '0', generation = 56, labels = { 'key' : '0' }, managed_fields = [ kubernetes.client.models.v1/managed_fields_entry.v1.ManagedFieldsEntry( api_version = '0', fields_type = '0', fields_v1 = kubernetes.client.models.fields_v1.fieldsV1(), manager = '0', operation = '0', time = datetime.datetime.strptime('2013-10-20 19:20:30.00', '%Y-%m-%d %H:%M:%S.%f'), ) ], name = '0', namespace = '0', owner_references = [ kubernetes.client.models.v1/owner_reference.v1.OwnerReference( api_version = '0', block_owner_deletion = True, controller = True, kind = '0', name = '0', uid = '0', ) ], resource_version = '0', self_link = '0', uid = '0', ), preemption_policy = '0', value = 56, ) ], ) def testV1PriorityClassList(self): """Test V1PriorityClassList""" inst_req_only = self.make_instance(include_optional=False) inst_req_and_optional = self.make_instance(include_optional=True) if __name__ == '__main__': unittest.main()
import os import time import uiautomator2 as u2 from util.ding_util import send_msg import random def send_ding(msg): ding_token = "99de3b9549d59caf5b445ef2d24a68b64f89498a5fda4b43c0b3098a3a57657e" ding_url = "https://oapi.dingtalk.com/robot/send?access_token={}".format(ding_token) send_msg(ding_url, "提醒:{}".format(msg)) def exec_cmd(cmd): print(cmd) os.system(cmd) def sleep(secs): print("sleep {} seconds".format(secs)) time.sleep(secs) ##根据x和y坐标进行屏幕定位点击事件 def on_click(x, y): ##触摸屏幕进行点击 exec_cmd('adb shell input tap {x1} {y1}'.format(x1=x, y1=y)) ##滑动屏幕从(x, y)坐标点到(ex, ey)坐标点 def slide(x, y, ex, ey): exec_cmd('adb shell input swipe {x1} {y1} {x2} {y2}'.format(x1=x, y1=y, x2=x + ex, y2=y + ey)) ##手机屏幕响应操作 def touch(key): # 按动相应的按键 if key == "back": print("> back按键") exec_cmd('adb shell input keyevent 4') elif key == "power": print("> power按键") exec_cmd('adb shell input keyevent 26') elif key == "home": print("> home按键") exec_cmd('adb shell input keyevent 3') sleep(3) # 等待1s等手机反应 ##判断是否黑屏 def is_black(): d = u2.connect() screen = d.info if not screen["screenOn"]: print("熄屏状态...") return True def start(): ##由于我的是密码锁屏,姑且要输入密码 ##如果将密码锁去掉则可以注释掉一下代码了,只需要亮屏即可 slide(550, 1200, 0, -800) sleep(1) touch("home") touch("home") ##1、点击屏幕钉钉软件,坐标可根据手机自行调节 exec_cmd("adb shell am start -n com.alibaba.android.rimet/com.alibaba.android.rimet.biz.LaunchHomeActivity") sleep(5) touch("home") touch("home") touch("power") def once(): try: if is_black(): touch("power") ##点击亮屏幕 start() else: start() except Exception as ex: err_msg = "exception {}".format(repr(ex)) print(err_msg) send_ding(err_msg) def start_main(): count = 0 while True: count = count + 1 exec_msg = "exec times {count}".format(count=count) print(exec_msg) send_ding(exec_msg) once() sleep(60 * 10 * (1 + random.random())) if __name__ == "__main__": start_main()
import tkinter as tk from tkinter import ttk from tkinter import messagebox from datetime import date from dateutil.relativedelta import relativedelta import cdsave import tkcalendar as tkc class App: def __init__(self, root): """ initialize attributes and widjets """ #store the number of times calculate buttons are clicked self.no_of_times_clicked: int = 0 self.no_of_times_clicked2: int = 0 #====================Menu bar ==============================# menubar = tk.Menu(root) filemenu = tk.Menu(menubar, tearoff = 0) helpmenu = tk.Menu(menubar, tearoff = 0) aboutmenu = tk.Menu(menubar, tearoff = 0) filemenu.add_command(label = "Open") filemenu.add_command(label = "Save", command = self.save) filemenu.add_separator() filemenu.add_command(label = "Exit", command = self.exitroot) helpmenu.add_command(label = "Help Docs") helpmenu.add_command(label = "Help Demo")#,command = help) menubar.add_cascade(label = "File", menu = filemenu) menubar.add_cascade(label = "Help", menu = helpmenu) menubar.add_command(label = "About", command = self.about_dev) root.config(menu = menubar) tab_control = ttk.Notebook(root) tab_control.grid(row = 0, column = 0) tab1 = ttk.Frame(tab_control, width = 300, height = 500) tab2 = ttk.Frame(tab_control, width = 300, height = 500) tab_control.add(tab1, text = "Difference between dates") tab_control.add(tab2, text = "Add or subtract dates") #====================Tab1==============================# #---------------------Frames---------------------------------------------------------- top1 = tk.Frame(tab1, width = 290, height = 75, bd = 8, relief = "groove",\ bg = "White") top1.grid(row = 1, column = 0, columnspan = 2, pady = 10, padx = 10,\ sticky = "WE") right1 = tk.Frame(tab1, width = 100, height = 75, bd = 0, relief = "groove",\ bg = "White") right1.grid(row = 2, column = 0, columnspan = 2, pady = 0, padx = 10,\ sticky = "E" ) middle = tk.Frame(tab1, width = 290, height = 75, bd = 8, relief = "groove",\ bg = "White") middle.grid(row = 3, column = 0, columnspan = 2, pady = 10,padx = 10,\ sticky = "WE") right2 = tk.Frame(tab1, width = 100, height = 75, bd = 0, relief = "groove",\ bg = "White") right2.grid(row = 4, column = 0, columnspan = 2, pady = 0, padx = 10,\ sticky = "E" ) #------------------------------------------------------------------------------------------- name = tk.Label(top1, font = ("Arial",10), text = "Description: ", fg = "black", bg = "White") name.grid(row = 0, column = 0, padx = 3, pady = 3) self.name_input = tk.StringVar() self.name_box = tk.Entry(top1, textvariable = self.name_input, bd = 3, bg = "powderblue", exportselection = 0) self.name_box.grid(row = 0, column = 1, padx = 3, pady = 3) date1 = tk.Label(top1, font = ("Arial",10), text = "From: ",fg = "black",width = 9, bg = "White") date1.grid(row = 1, column = 0, padx = 3, pady = 3) date2 = tk.Label(top1, font = ("Arial",10), text = "To: ",fg = "black",width = 9, bg = "White") date2.grid(row = 1, column = 1, padx = 3, pady = 3) self.date_input1 = tk.StringVar() self.date_box1 = tkc.DateEntry(top1, textvariable = self.date_input1, bd = 3, bg = "powderblue", date_pattern = "d/m/y", firstweekday = "sunday", selectbackground = "red", justify = "center") self.date_box1.grid(row = 2, column = 0, padx = 3, pady = 3) self.date_input2 = tk.StringVar() self.date_box2 = tkc.DateEntry(top1, textvariable = self.date_input2, bd = 3, bg = "powderblue", date_pattern = "d/m/y", firstweekday = "sunday", selectbackground = "red", justify = "center") self.date_box2.grid(row = 2, column = 1, padx = 3, pady = 3) cal_btn = tk.Button(right1, text = "Calculate", bd = 5 , relief = "raise", width = 13, cursor = "dotbox", \ command = self.display_diff, fg = "red", bg = "lightblue") cal_btn.grid(row = 0, column = 0, padx = 0, pady = 0) reset_btn = tk.Button(right2, text = "Reset", bd = 5 , relief = "raise", width = 13, cursor = "dotbox", \ command = self.reset, fg = "red", bg = "lightblue") reset_btn.grid(row = 0, column = 1) differenceall = tk.Label(middle, font = ("Arial",11,"normal"), text = "Difference(years, months, weeks, days)",\ bg = "White") differenceall.grid(row = 0, column = 0) self.message1 = tk.StringVar() self.message_box1 = tk.Entry(middle, font = 28, bd = 5, textvariable = self.message1,\ fg = "Black",bg = "powderblue", width = 28) self.message_box1.grid(row = 1, column = 0, pady = 5, sticky = "w") differenced = tk.Label(middle, font = ("Arial",11,"normal"), text = "Difference(days)", bg = "White") differenced.grid(row = 2, column = 0, sticky = "w") self.message2 = tk.StringVar() self.message_box2 = tk.Entry(middle, font = 28, bd = 5, textvariable = self.message2, \ fg = "Black",bg = "powderblue", width = 28) self.message_box2.grid(row = 3, column = 0, pady = 5, sticky = "w") self.status = tk.StringVar() self.status_text = tk.Label(tab1, font = ("Arial",10), textvariable = self.status,\ relief = "sunken", anchor = "e", width = "38", bg = "White", fg = "Red", bd = 3) self.status_text.grid(row = 5, column = 0, padx = 0) #====================Tab2==============================# from_lbl = tk.Label(tab2, text = "From ", font = ("Arial",10), fg = "black") from_lbl.grid(row = 0, column = 0) self.from_date = tkc.DateEntry(tab2, bd = 3, bg = "powderblue", date_pattern = "d/m/y", firstweekday = "sunday", selectbackground = "red", justify = "center") self.from_date.grid(row = 0, column = 1) self.operation = tk.StringVar(value = "add") add_option = tk.Radiobutton(tab2, variable = self.operation, value = "add") add_option.grid(row = 0, column = 2) add_lbl = tk.Label(tab2, text = "Add", font = ("Arial", 10), fg = "black", anchor = "w") add_lbl.grid(row = 0, column = 3) sub_option = tk.Radiobutton(tab2, variable = self.operation, value = "subtract") sub_option.grid(row = 0, column = 4) sub_lbl = tk.Label(tab2, text = "Subtract", font = ("Arial", 10), fg = "black", anchor = "w") sub_lbl.grid(row = 0, column = 5) year_lbl = tk.Label(tab2, text = "Year(s)", font = ("Arial", 10), fg = "black", anchor = "w") year_lbl.grid(row = 1, column = 0, sticky = "w") self.year_input = tk.IntVar(value = 0) self.year_box = ttk.Spinbox(tab2, textvariable = self.year_input, from_ = 0, to = 999, width = 4) self.year_box.grid(row = 1, column = 1) month_lbl = tk.Label(tab2, text = "Month(s)", font = ("Arial", 10), fg = "black", anchor = "w") month_lbl.grid(row = 1, column = 2) self.month_input = tk.IntVar(value = 0) self.month_box = ttk.Spinbox(tab2, textvariable = self.month_input, from_ = 0, to = 999, width = 4) self.month_box.grid(row = 1, column = 3) day_lbl = tk.Label(tab2, text = "Day(s)", font = ("Arial", 10), fg = "black", anchor = "w") day_lbl.grid(row = 1, column = 4) self.day_input = tk.IntVar(value = 0) self.day_box = ttk.Spinbox(tab2, textvariable = self.day_input, from_ = 0, to = 999, width = 4) self.day_box.grid(row = 1, column = 5) date_lbl = tk.Label(tab2, text = "Date", font = ("Arial", 10), fg = "black", anchor = "w") date_lbl.grid(row = 2, column = 0) self.date_box = tk.Entry(tab2, bg = "powderblue", fg = "black", font = ("Arial", 10), width = 45) self.date_box.grid(row = 3, column = 0, columnspan = 5) right1 = tk.Frame(tab2, width = 100, height = 75, bd = 0, relief = "groove",\ bg = "White") right1.grid(row = 4, column = 0, columnspan = 5, pady = 0, padx = 10,\ sticky = "E" ) cal_btn = tk.Button(right1, text = "Calculate", bd = 5 , relief = "raise", width = 13, cursor = "dotbox", \ command = self.display_date, fg = "red", bg = "lightblue") cal_btn.grid(row = 0, column = 0, padx = 0, pady = 0) #================================Functions======================================================= def exitroot(self): """ to exit the windows """ #response stores the answer provided by the user response = messagebox.askyesno("Quit", "Are you sure you want to exit \ Countdown Calender?", icon = "warning") print(response) #yes is clicked --> response = True if response == True: print("yes") root.destroy() else: print("No") def about_dev(self): """ to display information about the developer """ response = messagebox.showinfo("About", """This application was developed by Fayemi Boluwatife. Copyright 2020. Bovage INC """, icon = "info") print(response) def reset(self): """ clears all data on the windows """ self.name_input.set("") self.date_box1.set_date(date.today()) self.date_box2.set_date(date.today()) self.message1.set("") self.message2.set("") self.status.set("") self.status_text.configure(fg = "Black") self.status.set("Data cleared") def diff_between_dates(self, date_2: date, date_1: date) -> tuple : """ calculate the days between dates """ diff_bet_days = (date_2 - date_1).days difference = relativedelta(date_2, date_1) diff_years = difference.years diff_months = difference.months diff_weeks = difference.weeks if difference.days % 7 == 0: diff_days = 0 elif difference.days < 7: diff_days = difference.days elif difference.days > 7: diff_days = difference.days - (diff_weeks * 7) return diff_years, diff_months, diff_weeks, diff_days, diff_bet_days def addorsub(self, date: date, years: str, months: str, days: str, operation: str) -> date: """ adds or subtracts year(s), month(s) or day(s) to a date """ try: years = int(years) months = int(months) days = int(days) #print(type(date)) if operation.title() == "Add": result = date + relativedelta(years = years, months = months, days = days) return result else: result = date + relativedelta(years = -years, months = -months, days = -days) return result except ValueError: pass def check_plurality(self, message: str, quantity: int, pluword: str = "days", singword: str = "day") -> str: """ returns a new string with correct syntax in terms of plurality """ if int(quantity) <= 1: c_message = message.replace(pluword, singword) return c_message else: return message def display_diff(self): """ displays the result to their respective widget """ self.no_of_times_clicked += 1 if self.date_box1.get_date() != self.date_box2.get_date(): diff = self.diff_between_dates(self.date_box2.get_date(), self.date_box1.get_date()) print(diff) message1 = f"It is {diff[0]} years, {diff[1]} months, {diff[2]} weeks, {diff[3]} days until {self.name_box.get()}." message1 = self.check_plurality(pluword = "years", quantity = diff[0], message = message1, singword = "year") message1 = self.check_plurality(pluword = "months", quantity = diff[1], message = message1, singword = "month") message1 = self.check_plurality(pluword = "weeks", quantity = diff[2], message = message1, singword = "week") message1 = self.check_plurality(pluword = "days", quantity = diff[3], message = message1, singword = "day") message2 = f"It is {diff[4]} days until {self.name_box.get()}." message2 = self.check_plurality(message2, diff[4]) else: message1 = "Same dates." message2 = message1 #do nothing #to delete the previous messages if the calculate button has been #pressed once if self.no_of_times_clicked > 1: self.message_box1.delete(0,"end") self.message_box2.delete(0,"end") else: pass self.message_box1.insert(0,message1) self.message_box2.insert(0,message2) self.status_text.configure(fg = "Black") self.status.set("Done!") #to store the date that will be typed in stickynote return self.date_box1.get_date(), self.date_box2.get_date() def display_date(self): """ displays the result to self.date_box entry of tab2 """ self.no_of_times_clicked2 += 1 answer = self.addorsub(self.from_date.get_date(), self.year_box.get(), self.month_box.get(), self.day_box.get(), self.operation.get()) message = answer.strftime("%A,%B %d, %Y") if self.no_of_times_clicked2 > 1: self.date_box.delete(0,"end") else: pass self.date_box.insert(0,message) def save(self): """ enables data to be typed on stickynote """ date = self.display_diff() cdsave.openstickynote() cdsave.writedata(date = date, description = self.name_box.get(), \ message = self.message_box1.get() + "\n" + self.message_box2.get()) #======================================================================================= if __name__ == "__main__": root = tk.Tk() root.title("Countdown Calendar") root.geometry("375x415+0+0") root.resizable(0,0) root.iconbitmap(r".\cc.ico") #r indicate raw string [it ignore \ as esc char] root.configure(bg = "Red") cdcal = App(root) root.mainloop()
// // Copyright (c) 2016 Cisco Systems // Licensed under the MIT License // /* * a Cisco Spark webhook that leverages a simple library (batteries included) * * note : this example requires that you've set a SPARK_TOKEN env variable * */ var SparkBot = require("../sparkbot/webhook"); // Starts your Webhook with default configuration where the SPARK API access token is read from the SPARK_TOKEN env variable var bot = new SparkBot(); bot.onMessage(function(trigger, message) { // // ADD YOUR CUSTOM CODE HERE // console.log("new message from: " + trigger.data.personEmail + ", text: " + message.text); });
month = int(input()) if month == 1: print("January") elif month == 2: print("February") elif month == 3: print("March") elif month == 4: print("April") elif month == 5: print("May") elif month == 6: print("June") elif month == 7: print("July") elif month == 8: print("August") elif month == 9: print("September") elif month == 10: print("October") elif month == 11: print("November") elif month == 12: print("December")
#!/usr/bin/env python3 from discord.ext import commands import discord import re import os import aiohttp from tokenfile import token import inspect bot = commands.Bot(command_prefix='!') @bot.event async def on_ready(): print('Bot ready!') print('Logged in as ' + bot.user.name) print('-------') # this is all my standard bot boilerplate def is_owner_check(message): return message.author.id == '129855424198475776' #Bot owner ID, used for technical def is_owner(): return commands.check(lambda ctx: is_owner_check(ctx.message)) @bot.command() @is_owner() async def load(extension_name: str): """Loads an extension.""" try: bot.load_extension(extension_name) except (AttributeError, ImportError) as e: await bot.say("```py\n{}: {}\n```".format(type(e).__name__, str(e))) return await bot.say("{} loaded.".format(extension_name)) @bot.command() @is_owner() async def unload(extension_name: str): """Unloads an extension.""" bot.unload_extension(extension_name) await bot.say("{} unloaded.".format(extension_name)) @bot.command() @is_owner() async def reload(extension_name: str): bot.unload_extension(extension_name) try: bot.load_extension(extension_name) except (AttributeError, ImportError) as e: await bot.say("```py\n{}: {}\n```".format(type(e).__name__, str(e))) return await bot.say("{} reloaded.".format(extension_name)) @bot.command(pass_context=True) @is_owner() async def upload(ctx, *, filename: str = None): def check(reaction, user): if user.id != ctx.message.author.id: return False return True try: file_url = ctx.message.attachments[0]['url'] except IndexError: await bot.say('No file uploaded!') return if filename is None: filename = ctx.message.attachments[0]['filename'] if '/' or '\\' in filename: filename = re.split(r"/|\\", filename) reaction_msg = await bot.say( 'File URL is {}, with filename {}, is this okay? ✅/❌'.format(file_url, filename[-1]), delete_after=60) await bot.add_reaction(reaction_msg, '✅') await bot.add_reaction(reaction_msg, '❌') resp = await bot.wait_for_reaction(['✅', '❌'], message=reaction_msg, check=check, timeout=60) if resp is None: await bot.say('Timed out! Aborting!', delete_after=90) elif resp.reaction.emoji == '❌': await bot.say('Aborting!', delete_after=90) elif resp.reaction.emoji == '✅': try: await bot.clear_reactions(reaction_msg) except discord.Forbidden: pass try: file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), *filename) if not os.path.exists(os.path.dirname(file_path)): os.makedirs(os.path.dirname(file_path)) with aiohttp.ClientSession() as session: async with session.get(file_url) as resp: content = await resp.read() with open(file_path, 'wb') as f: f.write(content) await bot.say('Successfully uploaded {}!'.format(filename[-1]), delete_after=30) except Exception as e: await bot.say(e) await bot.delete_message(ctx.message) @bot.command(pass_context=True, hidden=True) @is_owner() async def debug( ctx, *, code: str): """Evaluates code.""" code = code.strip('` ') python = '```py\n{}\n```' result = None env = { 'bot': bot, 'ctx': ctx, 'message': ctx.message, 'server': ctx.message.server, 'channel': ctx.message.channel, 'author': ctx.message.author } env.update(globals()) try: result = eval(code, env) if inspect.isawaitable(result): result = await result except Exception as e: await bot.say(python.format(type(e).__name__ + ': ' + str(e))) return await bot.say(python.format(result)) startup_extensions = ["talentlookup"] if __name__ == "__main__": for extension in startup_extensions: try: bot.load_extension(extension) except Exception as e: exc = '{}: {}'.format(type(e).__name__, e) print('Failed to load extension {}\n{}'.format(extension, exc)) bot.run(token, max_messages=5000)
var express = require('express'); var app = express(); app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/public')); app.use(express.static(__dirname + '/node_modules')); app.get('/', function(request, response) { response.sendfile('./public/html/core.html'); }); app.listen(app.get('port'), function() { console.log("Node app is running at localhost:" + app.get('port')); });
export const colorsMap = [ { color: "--primary-color", description: "Use this to emphasise main ui components" }, { color: "--primary-on-secondary-color", description: "Use this to emphasise main ui components on secondary background color" }, { color: "--primary-hover-color", description: "Use only as a hover on primary color" }, { color: "--primary-hover-on-secondary-color", description: "Use only as a hover on primary color on secondary background color" }, { color: "--primary-selected-color", description: "Use this to indicate selected state of primary items" }, { color: "--primary-selected-on-secondary-color", description: "Use this to indicate selected state of primary items on secondary background color" }, { color: "--primary-text-color", description: "Use for default text color" }, { color: "--primary-text-on-secondary-color", description: "Use for default text color on secondary background color" }, { color: "--secondary-text-color", description: "Use when you need text with lesser importance" }, { color: "--secondary-text-on-secondary-color", description: "Use when you need text with lesser importance (on secondary background color)" }, { color: "--primary-background-hover-color", description: "Use as hover color" }, { color: "--primary-background-hover-on-secondary-color", description: "Use as hover color on secondary color" }, { color: "--inverted-color-background", description: "Inverted background color (opposite of primary background color)" }, { color: "--text-color-on-inverted", description: "Inverted text color (opposite of primary text color)" }, { color: "--text-color-on-primary", description: "Use for text on primary color" }, // states { color: "--positive-color", description: "Use when you want to indicate sometime positive (success, completion of something...)" }, { color: "--positive-color-hover", description: "Use only as hover color on positive color" }, { color: "--positive-color-selected", description: "Use only as selected indication for a positive colors" }, { color: "--negative-color", description: "Use when you want to indicate a negative action/state (delete, failed action..., error)" }, { color: "--negative-color-hover", description: "Use only as hover color on negative color" }, { color: "--negative-color-selected", description: "Use as selected indication for negative colors" }, { color: "--private-color", description: "Use when you want to indicate that something is private (board, icons...)" }, { color: "--shareable-color", description: "Use when you want to indicate that something is shareable (board, dashboard...)" }, // borders { color: "--ui-border-color", description: "Border color for ui elements and components (Button, Input...)" }, { color: "--ui-border-on-secondary-color", description: "Border color for ui elements on secondary color" }, { color: "--layout-border-color", description: "Border color for general layout and separators (Leftpane, Menu Divider...)" }, { color: "--layout-border-on-secondary-color", description: "Border color for general layout on secondary background color" }, { color: "--placeholder-color", description: "Use for placeholder text in inputs fields" }, { color: "--placeholder-on-secondary-color", description: "Use for placeholder text in inputs fields on secondary background color" }, { color: "--icon-color", description: "Default color for icons" }, { color: "--icon-on-secondary-color", description: "Default color for icons on secondary background color" }, // disabled { color: "--disabled-background-color", description: "Use as background for disabled elements (ui hovers or elements)" }, { color: "--disabled-text-color", description: "Use as text in disabled components" }, { color: "--disabled-background-on-secondary-color", description: "Use as background for disabled elements on secondary background" }, { color: "--disabled-text-on-secondary-color", description: "Use as text in disabled components on secondary background color" }, // Link { color: "--link-color", description: "Use only for links" }, { color: "--link-on-secondary-color", description: "Use only for links on secondary colors" }, // Backgrounds { color: "--primary-background-color", description: "Primary background color" }, { color: "--secondary-background-color", description: "Secondary background color" } ]; export const contentColors = [ "grass_green", "done-green", "bright-green", "saladish", "egg_yolk", "working_orange", "dark-orange", "peach", "sunset", "stuck-red", "dark-red", "sofia_pink", "lipstick", "bubble", "purple", "dark_purple", "berry", "dark_indigo", "indigo", "navy", "bright-blue", "dark-blue", "aquamarine", "chili-blue", "river", "winter", "explosive", "american_gray", "blackish", "brown" ]; export const COLOR_STYLES = { REGULAR: "regular", SELECTED: "selected" }; export const contentColorsByName = { GRASS_GREEN: "grass_green", DONE_GREEN: "done-green", BRIGHT_GREEN: "bright-green", SALADISH: "saladish", EGG_YOLK: "egg_yolk", WORKING_ORANGE: "working_orange", DARK_ORANGE: "dark-orange", PEACH: "peach", SUNSET: "sunset", STUCK_RED: "stuck-red", DARK_RED: "dark-red", SOFIA_PINK: "sofia_pink", LIPSTICK: "lipstick", BUBBLE: "bubble", PURPLE: "purple", DARK_PURPLE: "dark_purple", BERRY: "berry", DARK_INDIGO: "dark_indigo", INDIGO: "indigo", NAVY: "navy", BRIGHT_BLUE: "bright-blue", DARK_BLUE: "dark-blue", AQUAMARINE: "aquamarine", CHILI_BLUE: "chili-blue", RIVER: "river", WINTER: "winter", EXPLOSIVE: "explosive", AMERICAN_GRAY: "american_gray", BLACKISH: "blackish", BROWN: "brown" }; export const stateSelectedColors = { POSITIVE: "--positive-color-selected", NEGATIVE: "--negative-color-selected", PRIMARY: "--primary-selected-color" }; export const elementAllowedColors = [...Object.keys(contentColorsByName), ...Object.keys(stateSelectedColors)]; export const elementColorsNames = elementAllowedColors.reduce((acc, key) => { acc[key] = key; return acc; }, {}); export const getElementColor = (colorName, isSelectedPalette = false) => { if (contentColorsByName[colorName]) { return `var(--color-${contentColorsByName[colorName]}${isSelectedPalette ? "--selected" : ""}`; } if (stateSelectedColors[colorName] && isSelectedPalette) { return `var(${stateSelectedColors[colorName]})`; } return colorName; }; export const allMondayColors = [ "--color-asphalt", "--color-light_blue", "--color-basic_blue", "--color-basic_light_blue", "--color-dark_blue", "--color-link_color", "--color-snow_white", "--color-success", "--color-success-hover", "--color-success-highlight", "--color-purple", "--color-error", "--color-error-hover", "--color-error-highlight", "--color-placholder_gray", "--color-wolf_gray", "--color-mud_black", "--color-jaco_gray", "--color-black", "--color-dark_purple", "--color-blue_links", "--color-bazooka", "--color-dark_marble", "--color-marble", "--color-gainsboro", "--color-grass_green", "--color-jeans", "--color-egg_yolk", "--color-saladish", "--color-lipstick", "--color-working_orange", "--color-aqua", "--color-brown", "--color-blackish", "--color-explosive", "--color-american_gray", "--color-highlight_blue", "--color-pulse_text_color", "--color-highlight", "--color-placeholder_light_gray", "--color-scrollbar_gray", "--color-timeline_grid_blue", "--color-timeline_blue", "--color-default_group_color", "--color-very_light_gray", "--color-pulse_bg", "--color-jade", "--color-form_purple", "--color-form_btn_hover", "--color-board_views_grey", "--color-board_views_blue", "--color-board_views_grey_hover", "--color-board_views_blue_secondary", "--color-brand-blue", "--color-brand-charcoal", "--color-brand-gold", "--color-brand-green", "--color-brand-iris", "--color-brand-light-blue", "--color-brand-malachite", "--color-brand-purple", "--color-brand-red", "--color-public", "--color-private", "--color-word-blue", "--color-ppt-orange", "--color-excel-green", "--color-pdf-red", "--color-zip-orange", "--color-media-blue", "--color-surface", "--color-burned_eggplant", "--color-live_blue", "--color-extra_light_gray", "--color-glitter", "--color-ultra_light_gray", "--color-red_shadow", "--color-green_shadow", "--color-storm_gray", "--color-riverstone_gray", "--color-ui_grey", "--color-border_light_gray", "--color-like_red", "--color-lime-green", "--color-mustered", "--color-dark_red", "--color-dark-red", "--color-trolley-grey", "--color-dark-purple", "--color-dark-orange", "--color-sofia_pink", "--color-dark-pink", "--color-turquoise", "--color-light-pink", "--color-red-shadow", "--color-orange", "--color-yellow", "--color-green-shadow", "--color-grass-green", "--color-blue-links", "--color-bright-blue", "--color-amethyst", "--color-green-haze", "--color-sunset", "--color-bubble", "--color-peach", "--color-berry", "--color-winter", "--color-river", "--color-navy", "--color-aquamarine", "--color-indigo", "--color-dark_indigo" ];
# # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # import os from samples.snippets import process_document_splitter_sample location = "us" project_id = os.environ["GOOGLE_CLOUD_PROJECT"] processor_id = "ed55eeb2b276066f" file_path = "resources/multi_document.pdf" def test_process_documents(capsys): process_document_splitter_sample.process_document_splitter_sample( project_id=project_id, location=location, processor_id=processor_id, file_path=file_path, ) out, _ = capsys.readouterr() # Remove newlines and quotes from output for easier comparison out = out.replace(' "" ', " ").replace("\n", "") expected_strings = [ "Found 8 subdocuments", "confident that pages 1 to 2 are a subdocument", "confident that page 10 is a subdocument", ] for expected_string in expected_strings: assert expected_string in out
const template = require('./template.html'); export const AwwState = { name: 'aww', url: '/aww', template, controller: 'AwwStateCtrl', controllerAs: 'aww' };
import { fixedswap } from "../interfaces"; import Contract from "./Contract"; import ERC20TokenContract from "./ERC20TokenContract"; import IDOStaking from "./IDOStaking"; import Numbers from "../utils/Numbers"; import _ from "lodash"; import moment from 'moment'; const RESIDUAL_ETH = 0.00001; import { Decimal } from 'decimal.js'; import * as ethers from 'ethers'; import Client from "../utils/Client"; /** * Fixed Swap Object * @constructor FixedSwapContract * @param {Web3} web3 * @param {Address} tokenAddress * @param {Address} contractAddress ? (opt) */ class FixedSwapContract { constructor({ web3, tokenAddress, contractAddress = null /* If not deployed */, acc, }) { try { if (!web3) { throw new Error("Please provide a valid web3 provider"); } this.web3 = web3; this.version = "2.0"; if (acc) { this.acc = acc; } this.params = { web3: web3, contractAddress: contractAddress, contract: new Contract(web3, fixedswap, contractAddress), }; if(tokenAddress){ this.params.erc20TokenContract = new ERC20TokenContract({ web3: web3, contractAddress: tokenAddress, acc }); }else{ if(!contractAddress){throw new Error("Please provide a contractAddress if already deployed")} } this.client = new Client(); } catch (err) { throw err; } } __init__() { try { if (!this.getAddress()) { throw new Error("Please add a Contract Address"); } this.__assert(); } catch (err) { throw err; } }; assertERC20Info = async () => { let tokenAddress = await this.erc20(); this.params.erc20TokenContract = new ERC20TokenContract({ web3: this.web3, contractAddress: tokenAddress, acc : this.acc }); if(!(await this.isETHTrade())){ this.params.tradingERC20Contract = new ERC20TokenContract({ web3: this.web3, contractAddress: await this.getTradingERC20Address(), acc : this.acc }); }; } __deploy = async (params, callback) => { return await this.params.contract.deploy( this.acc, this.params.contract.getABI(), this.params.contract.getJSON().bytecode, params, callback ); }; /** * @function addToBlacklist * @description Adds an address to the blacklist * @param {string} address */ addToBlacklist = async ({ address }) => { try { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract .getContract() .methods.addToBlacklist(address) ); } catch (err) { throw err; } }; /** * @function removeFromBlacklist * @description Removes an address from the blacklist * @param {string} address */ removeFromBlacklist = async ({ address }) => { try { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract .getContract() .methods.removeFromBlacklist(address) ); } catch (err) { throw err; } }; /** * @function isBlackListed * @description Returns true if the address is in the blacklist * @param {string} address * @returns {boolean} isBlackListed */ isBlacklisted = async ({address}) => { return await this.params.contract.getContract().methods.isBlacklisted(address).call(); } /** * @function isPaused * @description Returns if the contract is paused or not * @returns {boolean} */ async isPaused() { return await this.params.contract.getContract().methods.paused().call(); } /** * @function setStakingRewards * @type admin * @description Sets the staking rewards address * @param {string} address */ async setStakingRewards({address}) { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setStakingRewards(address) ); } /** * @function getIDOStaking * @description Returns the contract for the ido staking * @returns {IDOStaking} */ async getIDOStaking() { const contractAddr = await this.params.contract.getContract().methods.stakingRewardsAddress().call(); if (contractAddr == '0x0000000000000000000000000000000000000000') { throw new Error('This pool doesn\'t have a staking contract'); } return new IDOStaking({ acc: this.acc, web3: this.web3, contractAddress: contractAddr }); } /** * @function pauseContract * @type admin * @description Pause Contract */ async pauseContract() { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.pause() ); } /** * @function erc20 * @description Get Token Address * @returns {Address} Token Address */ async erc20() { return await this.params.contract .getContract() .methods.erc20() .call(); } /** * @function unpauseContract * @type admin * @description Unpause Contract */ async unpauseContract() { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.unpause() ); } /* Get Functions */ /** * @function tradeValue * @description Get swapratio for the pool * @returns {Integer} trade value against ETH */ async tradeValue() { return Numbers.fromDecimals( (await this.params.contract .getContract() .methods.tradeValue() .call()), await this.getTradingDecimals() ); } /** * @function vestingStart * @description Get Start Date of the Vesting * @returns {Date} */ async vestingStart() { try { return Numbers.fromSmartContractTimeToMinutes( await this.params.contract.getContract().methods.vestingStart().call() ); } catch (e) { // Swap v2 return await this.endDate(); } } /** * @function startDate * @description Get Start Date of Pool * @returns {Date} */ async startDate() { return Numbers.fromSmartContractTimeToMinutes( await this.params.contract.getContract().methods.startDate().call() ); } /** * @function endDate * @description Get End Date of Pool * @returns {Date} */ async endDate() { return Numbers.fromSmartContractTimeToMinutes( await this.params.contract.getContract().methods.endDate().call() ); } /** * @function isFinalized * @description To see if contract was finalized * @returns {Boolean} */ async isFinalized() { return await this.params.contract.getContract().methods.hasFinalized().call() } /** * @function individualMinimumAmount * @description Get Individual Minimum Amount for each address * @returns {Integer} */ async individualMinimumAmount() { return Numbers.fromDecimals( await this.params.contract .getContract() .methods.individualMinimumAmount() .call(), await this.getDecimals() ); } /** * @function individualMaximumAmount * @description Get Individual Maximum Amount for each address * @returns {Integer} */ async individualMaximumAmount() { return Numbers.fromDecimals( (await this.params.contract .getContract() .methods.individualMaximumAmount() .call()), await this.getDecimals() ); } /** * @function minimumRaise * @description Get Minimum Raise amount for Token Sale * @returns {Integer} Amount in Tokens */ async minimumRaise() { return Numbers.fromDecimals( (await this.params.contract .getContract() .methods.minimumRaise() .call()), await this.getDecimals() ); } /** * @function tokensAllocated * @description Get Total tokens Allocated already, therefore the tokens bought until now * @returns {Integer} Amount in Tokens */ async tokensAllocated() { return Numbers.fromDecimals( (await this.params.contract .getContract() .methods.tokensAllocated() .call()), await this.getDecimals() ); } /** * @function tokensForSale * @description Get Total tokens Allocated/In Sale for the Pool * @returns {Integer} Amount in Tokens */ async tokensForSale() { return Numbers.fromDecimals( await this.params.contract .getContract() .methods.tokensForSale() .call(), await this.getDecimals() ); } /** * @function hasMinimumRaise * @description See if hasMinimumRaise * @returns {Boolea} */ async hasMinimumRaise() { return await this.params.contract .getContract() .methods.hasMinimumRaise() .call(); } /** * @function minimumReached * @description See if minimumRaise was Reached * @returns {Integer} */ async wasMinimumRaiseReached() { let hasMinimumRaise = await this.hasMinimumRaise(); if(hasMinimumRaise){ let tokensAllocated = await this.tokensAllocated(); let minimumRaise = await this.minimumRaise(); return parseFloat(tokensAllocated) > parseFloat(minimumRaise); }else{ return true; } } /** * @function tokensAvailable * @description Get Total tokens owned by the Pool * @returns {Integer} Amount in Tokens */ async tokensAvailable() { return Numbers.fromDecimals( await this.params.contract .getContract() .methods.availableTokens() .call(), await this.getDecimals() ); } /** * @function tokensLeft * @description Get Total tokens available to be sold in the pool * @returns {Integer} Amount in Tokens */ async tokensLeft() { return Numbers.fromDecimals( await this.params.contract .getContract() .methods.tokensLeft() .call(), await this.getDecimals() ); } /** * @function setSignerPublicAddress * @description Set the public address of the signer * @param {string} address */ setSignerPublicAddress = async ({ address }) => { try { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract .getContract() .methods.setSignerPublicAddress(address) ); } catch (err) { throw err; } }; /** * @function signerPublicAddress * @description Get the public address of the signer * @returns {string} address */ async signerPublicAddress() { return await this.params.contract.getContract().methods.signerPublicAddress().call(); } /** * @function withdrawableUnsoldTokens * @description Get Total tokens available to be withdrawn by the admin * @returns {Integer} Amount in Tokens */ async withdrawableUnsoldTokens() { var res = 0; if(await this.hasFinalized() && !(await this.wereUnsoldTokensReedemed()) ){ if(await this.wasMinimumRaiseReached()){ /* Minimum reached */ res = (await this.tokensForSale()) - (await this.tokensAllocated()); }else{ /* Minimum reached */ res = await this.tokensForSale(); } } return res; } /** * @function withdrawableFunds * @description Get Total funds raised to be withdrawn by the admin * @returns {Integer} Amount in ETH */ async withdrawableFunds() { var res = 0; var hasFinalized = await this.hasFinalized(); var wasMinimumRaiseReached = await this.wasMinimumRaiseReached(); if(hasFinalized && wasMinimumRaiseReached){ res = await this.getBalance(); } return res; } /** * @function isTokenSwapAtomic * @description Verify if the Token Swap is atomic on this pool * @returns {Boolean} */ async isTokenSwapAtomic() { return await this.params.contract .getContract() .methods.isTokenSwapAtomic() .call(); } /** * @function hasWhitelisting * @description Verify if swap has whitelisting * @returns {Boolean} */ async hasWhitelisting() { return await this.params.contract .getContract() .methods.hasWhitelisting() .call(); } /** * @function isWhitelisted * @description Verify if address is whitelisted * @param {string} address * @returns {Boolean} */ async isWhitelisted({address}) { let res = await this.params.contract .getContract() .methods.isWhitelisted(address) .call(); return res == true ? true : false; } /** * @function wereUnsoldTokensReedemed * @description Verify if the admin already reemeded unsold tokens * @returns {Boolean} */ async wereUnsoldTokensReedemed() { try { return await this.params.contract .getContract() .methods.unsoldTokensRedeemed() .call(); } catch (e) { } return await this.params.contract .getContract() .methods.unsoldTokensReedemed() .call(); } /** * @function isFunded * @description Verify if the Token Sale is Funded with all Tokens proposed in tokensForSale * @returns {Boolean} */ async isFunded() { return await this.params.contract .getContract() .methods.isSaleFunded() .call(); } /** * @function isOpen * @description Verify if the Token Sale is Open for Swap * @returns {Boolean} */ async isOpen() { return await this.params.contract.getContract().methods.isOpen().call(); } /** * @function hasStarted * @description Verify if the Token Sale has started the Swap * @returns {Boolean} */ async hasStarted() { return await this.params.contract .getContract() .methods.hasStarted() .call(); } /** * @function hasFinalized * @description Verify if the Token Sale has finalized, if the current date is after endDate * @returns {Boolean} */ async hasFinalized() { return await this.params.contract .getContract() .methods.hasFinalized() .call(); } /** * @function isETHTrade * @description Verify if Token Sale is against Ethereum * @returns {Boolean} */ async isETHTrade() { return await this.params.contract .getContract() .methods.isETHTrade() .call(); } /** * @function isPOLSWhitelisted * @description Verify if Token Sale is POLS Whitelisted * @returns {Boolean} */ async isPOLSWhitelisted() { return await this.params.contract .getContract() .methods.isPOLSWhitelisted() .call(); } /** * @function isAddressPOLSWhitelisted * @description Verify if Address is Whitelisted by POLS (returns false if not needed) * @returns {Boolean} */ async isAddressPOLSWhitelisted(){ return await this.params.contract .getContract() .methods.isAddressPOLSWhitelisted() .call(); } /** * @function getTradingDecimals * @description Get Trading Decimals (18 if isETHTrade, X if not) * @returns {Integer} */ async getTradingDecimals(){ const tradeAddress = await this.getTradingERC20Address(); if (tradeAddress == '0x0000000000000000000000000000000000000000') { return 18; } const contract = new ERC20TokenContract({ web3: this.web3, contractAddress: tradeAddress, acc : this.acc }); return await contract.getDecimals(); } /** * @function getTradingERC20Address * @description Get Trading Address if ERC20 * @returns {Address} */ async getTradingERC20Address(){ try { return await this.params.contract .getContract() .methods.erc20TradeIn() .call(); } catch (e) { // Swap v2 return '0x0000000000000000000000000000000000000000'; } } /** * @function isPreStart * @description Verify if the Token Sale in not open yet, where the admin can fund the pool * @returns {Boolean} */ async isPreStart() { return await this.params.contract .getContract() .methods.isPreStart() .call(); } /** * @function getCurrentSchedule * @description Gets Current Schedule * @returns {Integer} */ async getCurrentSchedule() { return parseInt(await this.params.contract .getContract() .methods.getCurrentSchedule() .call()); } /** * @function getVestingSchedule * @description Gets Vesting Schedule * @param {Integer} Position Get Position of Integer * @returns {Array | Integer} */ async getVestingSchedule({position}) { return parseInt(await this.params.contract .getContract() .methods.vestingSchedule(position) .call()); } /** * @function getPurchase * @description Get Purchase based on ID * @param {Integer} purchase_id * @returns {Integer} _id * @returns {Integer} amount * @returns {Address} purchaser * @returns {Integer} costAmount * @returns {Date} timestamp * @returns {Integer} amountReedemed * @returns {Boolean} wasFinalized * @returns {Boolean} reverted */ getPurchase = async ({ purchase_id }) => { let res = await this.params.contract .getContract() .methods.getPurchase(purchase_id) .call(); let amount = Numbers.fromDecimals(res.amount, await this.getDecimals()); let costAmount = Numbers.fromDecimals(res.costAmount, await this.getTradingDecimals()); let amountReedemed = Numbers.fromDecimals(res.amountRedeemed, await this.getDecimals()); let amountLeftToRedeem = amount-amountReedemed; let isFinalized = await this.hasFinalized(); let amountToReedemNow = 0; try { amountToReedemNow = isFinalized ? Numbers.fromDecimals((await this.params.contract .getContract() .methods.getRedeemableTokensAmount(purchase_id).call()).amount, await this.getDecimals()) : 0 } catch (e) { // Swap v2 const abi = JSON.parse('[{ "inputs": [ { "internalType": "uint256", "name": "purchase_id", "type": "uint256" } ], "name": "getPurchase", "outputs": [ { "name": "", "type": "uint256" }, { "name": "", "type": "address" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "uint256" }, { "name": "", "type": "bool" }, { "name": "", "type": "bool" } ], "stateMutability": "view", "type": "function" }]'); const contract = new Contract(this.web3, {abi}, this.params.contractAddress); res = await contract .getContract() .methods.getPurchase(purchase_id) .call(); lastTrancheSent = parseInt(res[5]); amount = Numbers.fromDecimals(res[0], await this.getDecimals()); costAmount = Numbers.fromDecimals(res[2], await this.getTradingDecimals()); amountReedemed = Numbers.fromDecimals(res[4], await this.getDecimals()); amountLeftToRedeem = amount-amountReedemed; let currentSchedule = await this.getCurrentSchedule(); let lastTrancheSent = parseInt(res[5]); for(var i = lastTrancheSent+1; i <= currentSchedule; i++){ amountToReedemNow = amountToReedemNow + amount*(await this.getVestingSchedule({position: i}))/10000 } return { _id: purchase_id, amount: amount, purchaser: res[1], costAmount: costAmount, timestamp: Numbers.fromSmartContractTimeToMinutes(res[3]), amountReedemed : amountReedemed, amountLeftToRedeem : amountLeftToRedeem, amountToReedemNow : isFinalized ? amountToReedemNow : 0, lastTrancheSent : lastTrancheSent, wasFinalized: res[6], reverted: res[7], }; } // ToDo add a test for amountToReedemNow return { _id: purchase_id, amount: amount, purchaser: res.purchaser, costAmount: costAmount, timestamp: Numbers.fromSmartContractTimeToMinutes(res.timestamp), amountReedemed : amountReedemed, amountLeftToRedeem : amountLeftToRedeem, amountToReedemNow, wasFinalized: res.wasFinalized, reverted: res.reverted, }; }; /** * @function getWhiteListedAddresses * @description Get Whitelisted Addresses * @returns {Array | Address} addresses */ getWhitelistedAddresses = async () => await this.params.contract.getContract().methods.getWhitelistedAddresses().call(); /** * @function getBuyers * @description Get Buyers * @returns {Array | Integer} _ids */ getBuyers = async () => await this.params.contract.getContract().methods.getBuyers().call(); /** * @function getPurchaseIds * @description Get All Purchase Ids * @returns {(Array | Integer)} _ids */ getPurchaseIds = async () => { try { let res = await this.params.contract .getContract() .methods.getPurchasesCount() .call(); let ids = []; for (let i = 0; i < res; i++) { ids.push(i); } return ids; } catch(e) { // Swap v2 // ToDo Refactor const abi = JSON.parse('[{ "constant": true, "inputs": [], "name": "getPurchaseIds", "outputs": [ { "name": "", "type": "uint256[]" } ], "payable": false, "stateMutability": "view", "type": "function" }]'); const contract = new Contract(this.web3, {abi}, this.params.contractAddress); let res = await contract .getContract() .methods.getPurchaseIds() .call(); return res.map((id) => Numbers.fromHex(id)) } }; /** * @function getPurchaseIds * @description Get All Purchase Ids filter by Address/Purchaser * @param {Address} address * @returns {Array | Integer} _ids */ getAddressPurchaseIds = async ({ address }) => { let res = await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.getMyPurchases(address), true ); return res.map((id) => Numbers.fromHex(id)); }; /** * @function getCostFromTokens * @description Get Cost from Tokens Amount * @param {Integer} tokenAmount * @returns {Integer} costAmount */ getCostFromTokens = async ({ tokenAmount }) => { let amountWithDecimals = Numbers.toSmartContractDecimals( tokenAmount, await this.getDecimals() ); return Numbers.fromDecimals( await this.params.contract .getContract() .methods.cost(amountWithDecimals) .call(), await this.getTradingDecimals() ); }; /** * @function getDistributionInformation * @description Get Distribution Information * @returns {Integer} currentSchedule (Ex : 1) * @returns {Integer} vestingTime (Ex : 1) * @returns {Array | Integer} vestingSchedule (Ex : [100]) * @returns {Date} vestingStart */ getDistributionInformation = async () => { let currentSchedule = 0; if(await this.hasStarted()){ currentSchedule = parseInt(await this.getCurrentSchedule()); } let vestingTime = parseInt(await this.params.contract.getContract().methods.vestingTime().call()); let legacy = false; try { await this.getSmartContractVersion(); } catch (e) { legacy = true; } let vestingSchedule = []; if (legacy) { for(var i = 1; i <= vestingTime; i++){ let a = parseInt(await this.getVestingSchedule({position: i})); vestingSchedule.push(a); } } else { for(var i = 1; i < vestingTime; i++){ let a = parseInt(await this.getVestingSchedule({position: i - 1})); vestingSchedule.push(a); } } const vestingStart = await this.vestingStart(); return { currentSchedule, vestingTime, vestingSchedule, vestingStart } } /* Legacy Call */ getETHCostFromTokens = () => {throw new Error("Please use 'getCostFromTokens' instead")}; /* POST User Functions */ /** * @function swap * @description Swap tokens by Ethereum or ERC20 * @param {Integer} tokenAmount * @param {string=} signature Signature for the offchain whitelist */ swap = async ({ tokenAmount, callback, signature }) => { let amountWithDecimals = Numbers.toSmartContractDecimals( tokenAmount, await this.getDecimals() ); let cost = await this.getCostFromTokens({ tokenAmount, }); let costToDecimals = Numbers.toSmartContractDecimals(cost, await this.getTradingDecimals()); if (!signature) { signature = '0x00'; } return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.swap(amountWithDecimals, signature), false, await this.isETHTrade() ? costToDecimals : 0, callback ); }; __oldSwap = async ({ tokenAmount, callback }) => { console.log("swap (tokens Amount)", tokenAmount); let amountWithDecimals = Numbers.toSmartContractDecimals( tokenAmount, await this.getDecimals() ); let cost = await this.getCostFromTokens({ tokenAmount, }); console.log("cost in ETH (after getCostFromTokens) ", cost); let costToDecimals = Numbers.toSmartContractDecimals(cost, await this.getTradingDecimals()); console.log("swap (amount in decimals) ", amountWithDecimals); console.log("cost (amount in decimals) ", costToDecimals); const abi = JSON.parse('[{ "constant": false, "inputs": [ { "name": "_amount", "type": "uint256" } ], "name": "swap", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }]'); const contract = new Contract(this.web3, {abi}, this.params.contractAddress); return await this.client.sendTx( this.params.web3, this.acc, contract, contract.getContract().methods.swap(amountWithDecimals), false, await this.isETHTrade() ? costToDecimals : 0, callback ); }; /** * @function redeemTokens * @variation isStandard * @description Reedem tokens bought * @param {Integer} purchase_id * @param {Boolean=} stake If true send token to the ido staking contract */ redeemTokens = async ({ purchase_id, stake = false }) => { let legacy = false; try { await this.getSmartContractVersion(); } catch (e) { legacy = true; } if (legacy) { // Swap v2 const abi = JSON.parse('[{ "constant": false, "inputs": [ { "name": "purchase_id", "type": "uint256" } ], "name": "redeemTokens", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }]'); const contract = new Contract(this.web3, {abi}, this.params.contractAddress); return await this.client.sendTx( this.params.web3, this.acc, contract, contract.getContract().methods.redeemTokens(purchase_id) ); } return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.transferTokens(purchase_id, stake) ); }; /** * @function redeemGivenMinimumGoalNotAchieved * @variation isStandard * @description Reedem Ethereum from sale that did not achieve minimum goal * @param {Integer} purchase_id */ redeemGivenMinimumGoalNotAchieved = async ({ purchase_id }) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract .getContract() .methods.redeemGivenMinimumGoalNotAchieved(purchase_id) ); }; /** * @function withdrawUnsoldTokens * @description Withdraw unsold tokens of sale */ withdrawUnsoldTokens = async () => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.withdrawUnsoldTokens() ); }; /** * @function withdrawFunds * @description Withdraw all funds from tokens sold */ withdrawFunds = async () => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.withdrawFunds() ); }; /** * @function approveFundERC20 * @param {Integer} tokenAmount * @description Approve the pool to use approved tokens for sale */ approveFundERC20 = async ({ tokenAmount, callback }) => { return await this.getTokenContract().approve({ address: this.getAddress(), amount: tokenAmount, callback }); }; /** * @function setIndividualMaximumAmount * @type admin * @param {Integer} individualMaximumAmount * @description Modifies the max allocation */ setIndividualMaximumAmount = async ( { individualMaximumAmount } ) => { const maxAmount = Numbers.toSmartContractDecimals( individualMaximumAmount, await this.getDecimals() ); return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setIndividualMaximumAmount(maxAmount) ); }; /** * @function setEndDate * @type admin * @param {Date} endDate * @description Modifies the end date for the pool */ setEndDate = async ( { endDate } ) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setEndDate(Numbers.timeToSmartContractTime(endDate)) ); }; /** * @function setStartDate * @type admin * @param {Date} startDate * @description Modifies the start date for the pool */ setStartDate = async ( { startDate } ) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setStartDate(Numbers.timeToSmartContractTime(startDate)) ); } /** * @function setHasWhitelisting * @type admin * @param {boolean} hasWhitelist * @description Modifies if the pool has whitelisting or not */ setHasWhitelisting = async ( { hasWhitelist } ) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setHasWhitelisting(hasWhitelist) ); } /** * @function setVesting * @type admin * @param {Array<Integer>=} vestingSchedule Vesting schedule in % * @param {String=} vestingStart Vesting start date (Default: endDate) * @param {Number=} vestingCliff Seconds between every vesting schedule (Default: 0) * @param {Number=} vestingDuration Vesting duration (Default: 0) * @description Modifies the current vesting config */ setVesting = async ( { vestingSchedule=[], vestingStart, vestingCliff = 0, vestingDuration = 0 } ) => { if(vestingSchedule.length > 0 && vestingSchedule.reduce((a, b) => a + b, 0) != 100){ throw new Error("'vestingSchedule' sum has to be equal to 100") } const DECIMALS_PERCENT_MUL = 10**12; vestingSchedule = vestingSchedule.map( a => String(new Decimal(a).mul(DECIMALS_PERCENT_MUL)).toString()); return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.setVesting( Numbers.timeToSmartContractTime(vestingStart), vestingCliff, vestingDuration, vestingSchedule ) ); } /** * @function approveSwapERC20 * @param {Integer} tokenAmount * @description Approve the investor to use approved tokens for the sale */ approveSwapERC20 = async ({ tokenAmount, callback }) => { if(await this.isETHTrade()){throw new Error("Funcion only available to ERC20 Trades")}; return await this.params.tradingERC20Contract.approve({ address: this.getAddress(), amount: tokenAmount, callback }); }; /** * @function isApprovedSwapERC20 * @param {Integer} tokenAmount * @param {Address} address * @description Verify if it is approved to invest */ isApprovedSwapERC20 = async ({ tokenAmount, address, callback }) => { if(await this.isETHTrade()){throw new Error("Funcion only available to ERC20 Trades")}; return await this.params.tradingERC20Contract.isApproved({ address, spenderAddress: this.getAddress(), amount: tokenAmount, callback }); }; /** * @function isApproved * @description Verify if the Admin has approved the pool to use receive the tokens for sale * @param {Integer} tokenAmount * @param {Address} address * @returns {Boolean} */ isApproved = async ({ tokenAmount, address }) => { return await this.getTokenContract().isApproved({ address: address, amount: tokenAmount, spenderAddress: this.getAddress() }); }; /** * @function fund * @description Send tokens to pool for sale, fund the sale * @param {Integer} tokenAmount */ fund = async ({ tokenAmount, callback }) => { let amountWithDecimals = Numbers.toSmartContractDecimals( tokenAmount, await this.getDecimals() ); return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.fund(amountWithDecimals), null, null, callback ); }; /** * @function addWhitelistedAddress * @description add WhiteListed Address * @param { Array | Addresses} Addresses */ addWhitelistedAddress = async ({addresses}) => { if(!addresses || !addresses.length || addresses.length == 0){ throw new Error("Addresses not well setup"); } let oldAddresses = await this.getWhitelistedAddresses(); addresses = addresses.map( a => String(a).toLowerCase()) oldAddresses = oldAddresses.map( a => String(a).toLowerCase()); var addressesClean = []; addresses = addresses.filter( (item) => { if( (oldAddresses.indexOf(item) < 0) && (addressesClean.indexOf(item) < 0) ){ // Does not exist addressesClean.push(item); } }) return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.add(addressesClean) ); }; /** * @function removeWhitelistedAddress * @param { Array | Addresses} addresses * @param {Integer} index * @description remove WhiteListed Address */ removeWhitelistedAddress = async ({address, index}) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.remove(address, index) ); }; /** * @function safePull * @description Safe Pull all tokens & ETH */ safePull = async () => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract.getContract().methods.safePull(), null, 0 ); }; /** * @function removeOtherERC20Tokens * @description Remove Tokens from other ERC20 Address (in case of accident) * @param {Address} tokenAddress * @param {Address} toAddress */ removeOtherERC20Tokens = async ({ tokenAddress, toAddress }) => { return await this.client.sendTx( this.params.web3, this.acc, this.params.contract, this.params.contract .getContract() .methods.removeOtherERC20Tokens(tokenAddress, toAddress) ); }; __assert() { this.params.contract.use(fixedswap, this.getAddress()); } getDecimals = async () => { return await this.getTokenContract().getDecimals(); } /** * @function deploy * @description Deploy the Pool Contract * @param {Float} tradeValue Buy price * @param {Float} tokensForSale Tokens for sale * @param {String} endDate End date * @param {String} startDate Start date * @param {String=} ERC20TradingAddress Token to use in the swap (Default: 0x0000000000000000000000000000000000000000) * @param {Float=} individualMinimumAmount Min cap per wallet. 0 to disable it. (Default: 0) * @param {Float=} individualMaximumAmount Max cap per wallet. 0 to disable it. (Default: 0) * @param {Boolean=} isTokenSwapAtomic Receive tokens right after the swap. (Default: false) * @param {Float=} minimumRaise Soft cap (Default: 0) * @param {Float=} feeAmount Fee amount (Default: 1) * @param {Number=} tradingDecimals To be the decimals of the currency in case (ex : USDT -> 9; ETH -> 18) (Default: 0) * @param {Boolean=} hasWhitelisting Has White Listing. (Default: false) * @param {Boolean=} isPOLSWhitelist Has White Listing. (Default: false) * @param {Array<Integer>=} vestingSchedule Vesting schedule in % * @param {String=} vestingStart Vesting start date (Default: endDate) * @param {Number=} vestingCliff Seconds to wait for the first unlock after the vesting start (Default: 0) * @param {Number=} vestingDuration Seconds to wait between every unlock (Default: 0) */ deploy = async ({ tradeValue, tokensForSale, startDate, endDate, individualMinimumAmount = 0, individualMaximumAmount = 0, isTokenSwapAtomic = false, minimumRaise = 0, feeAmount = 1, hasWhitelisting = false, callback, ERC20TradingAddress = '0x0000000000000000000000000000000000000000', isPOLSWhitelist = false, tradingDecimals = 0, /* To be the decimals of the currency in case (ex : USDT -> 9; ETH -> 18) */ vestingSchedule=[], vestingStart, vestingCliff = 0, vestingDuration = 0 }) => { if (_.isEmpty(this.getTokenAddress())) { throw new Error("Token Address not provided"); } if (tradeValue <= 0) { throw new Error("Trade Value has to be > 0"); } if (tokensForSale <= 0) { throw new Error("Tokens for Sale has to be > 0"); } if (feeAmount < 1) { throw new Error("Fee Amount has to be >= 1"); } if(minimumRaise != 0 && (minimumRaise > tokensForSale)) { throw new Error("Minimum Raise has to be smaller than total Raise") } if(Date.parse(startDate) >= Date.parse(endDate)) { throw new Error("Start Date has to be smaller than End Date") } if(Date.parse(startDate) <= Date.parse(moment(Date.now()).add(2, 'm').toDate())) { throw new Error("Start Date has to be higher (at least 2 minutes) than now") } if(individualMaximumAmount < 0) { throw new Error("Individual Maximum Amount should be bigger than 0") } if(individualMinimumAmount < 0) { throw new Error("Individual Minimum Amount should be bigger than 0") } if(individualMaximumAmount > 0){ /* If exists individualMaximumAmount */ if(individualMaximumAmount <= individualMinimumAmount) { throw new Error("Individual Maximum Amount should be bigger than Individual Minimum Amount") } if(individualMaximumAmount > tokensForSale) { throw new Error("Individual Maximum Amount should be smaller than total Tokens For Sale") } } if(ERC20TradingAddress != '0x0000000000000000000000000000000000000000' && (tradingDecimals == 0)){ throw new Error("If an ERC20 Trading Address please add the 'tradingDecimals' field to the trading address (Ex : USDT -> 6)"); }else{ /* is ETH Trade */ tradingDecimals = 18; } if(individualMaximumAmount == 0){ individualMaximumAmount = tokensForSale; /* Set Max Amount to Unlimited if 0 */ } if(vestingSchedule.length > 0 && vestingSchedule.reduce((a, b) => a + b, 0) != 100){ throw new Error("'vestingSchedule' sum has to be equal to 100") } const DECIMALS_PERCENT_MUL = 10**12; vestingSchedule = vestingSchedule.map( a => String(new Decimal(a).mul(DECIMALS_PERCENT_MUL)).toString()); const FLAG_isTokenSwapAtomic = 1; // Bit 0 const FLAG_hasWhitelisting = 2; // Bit 1 const FLAG_isPOLSWhitelisted = 4; // Bit 2 - true => user must have a certain amount of POLS staked to participate if (vestingSchedule.length == 0) { vestingCliff = 0; } if (!vestingStart) { vestingStart = endDate; } let params = [ this.getTokenAddress(), Numbers.toSmartContractDecimals(tradeValue, tradingDecimals), Numbers.toSmartContractDecimals(tokensForSale, await this.getDecimals()), Numbers.timeToSmartContractTime(startDate), Numbers.timeToSmartContractTime(endDate), Numbers.toSmartContractDecimals( individualMinimumAmount, await this.getDecimals() ), Numbers.toSmartContractDecimals( individualMaximumAmount, await this.getDecimals() ), true, // ignored Numbers.toSmartContractDecimals(minimumRaise, await this.getDecimals()), parseInt(feeAmount), (isTokenSwapAtomic ? FLAG_isTokenSwapAtomic : 0) | (hasWhitelisting ? FLAG_hasWhitelisting : 0) | (isPOLSWhitelist ? FLAG_isPOLSWhitelisted : 0), // Flags ERC20TradingAddress, Numbers.timeToSmartContractTime(vestingStart), vestingCliff, vestingDuration, vestingSchedule, ]; let res = await this.__deploy(params, callback); this.params.contractAddress = res.contractAddress; /* Call to Backend API */ this.__assert(); return res; }; getAddress() { return this.params.contractAddress; } getTokenAddress() { return this.getTokenContract().getAddress(); } getTokenContract() { return this.params.erc20TokenContract; } /** * @function getSmartContractVersion * @description Returns the version of the smart contract that is currently inside psjs * @param {Address} Address */ getSmartContractVersion = async () => { return await this.params.contract.getContract().methods.getAPIVersion().call(); } /** * @function getBalance * @description Get Balance of Contract * @param {Integer} Balance */ getBalance = async () => { if(await this.isETHTrade()){ let wei = await this.web3.eth.getBalance(this.getAddress()); return this.web3.utils.fromWei(wei, 'ether'); }else{ return await this.getTokenContract().getTokenAmount(this.getAddress()); } }; } export default FixedSwapContract;
'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 _react=require('react');var _react2=_interopRequireDefault(_react);var _propTypes=require('prop-types');var _propTypes2=_interopRequireDefault(_propTypes);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _possibleConstructorReturn(self,call){if(!self){throw new ReferenceError("this hasn't been initialised - super() hasn't been called");}return call&&(typeof call==="object"||typeof call==="function")?call:self;}function _inherits(subClass,superClass){if(typeof superClass!=="function"&&superClass!==null){throw new TypeError("Super expression must either be null or a function, not "+typeof superClass);}subClass.prototype=Object.create(superClass&&superClass.prototype,{constructor:{value:subClass,enumerable:false,writable:true,configurable:true}});if(superClass)Object.setPrototypeOf?Object.setPrototypeOf(subClass,superClass):subClass.__proto__=superClass;}var Tabs=function(_React$Component){_inherits(Tabs,_React$Component);function Tabs(props){_classCallCheck(this,Tabs);var _this=_possibleConstructorReturn(this,(Tabs.__proto__||Object.getPrototypeOf(Tabs)).call(this,props));_this.state={selected:props.selected,children:[]};return _this;}_createClass(Tabs,[{key:'handleClick',value:function handleClick(index,event){event.preventDefault();this.setState({selected:index});if(typeof this.props.onChange==='function'){this.props.onChange(index);}}// if there is exactly one child, props.children is an object not an array // this getter always returns an array },{key:'renderTitles',value:function renderTitles(){function labels(child,index){var activeClass=this.state.selected===index?'active':'';return _react2.default.createElement('li',{className:'tab-panels--tab-list-item base--li',role:'presentation',key:index},_react2.default.createElement('a',{href:'#'+child.props.label.replace(/ /g,'-').toLowerCase(),className:activeClass+' tab-panels--tab base--a'// eslint-disable-next-line ,onClick:this.handleClick.bind(this,index),role:'tab'},child.props.label));}return _react2.default.createElement('ul',{className:'tab-panels--tab-list',role:'tablist'},this.children.map(labels.bind(this)));}},{key:'renderContent',value:function renderContent(){return _react2.default.createElement('div',{className:'tab-panels--tab-content'},this.children[this.state.selected]);}},{key:'render',value:function render(){return _react2.default.createElement('div',{className:'tab-panels',role:'tabpanel'},this.renderTitles(),this.renderContent());}},{key:'children',get:function get(){var children=this.props.children;return Array.isArray(children)?children:[children];}}]);return Tabs;}(_react2.default.Component);Tabs.propTypes={selected:_propTypes2.default.number,children:_propTypes2.default.oneOfType([_propTypes2.default.array,_propTypes2.default.element]).isRequired,onChange:_propTypes2.default.func};Tabs.defaultProps={selected:0,children:[],onChange:function onChange(){}};exports.default=Tabs;module.exports=exports['default']; //# sourceMappingURL=index.js.map
/* eslint-disable import/first */ import Taro from '@tarojs/taro'; import QiniuUpload from './qiniu_upload.js'; const qiniuCtx = new QiniuUpload(); export default class UpFile { /**生成随机字符串 */ makeRandomName() { return ( 'tempwg63_' + Date.now() + '_' + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) ); } onUpImg(params = {}) { return new Promise((resovle) => { Taro.chooseImage({ count: 1, sizeType: ['compressed'], success: (res) => { const path = res.tempFilePaths[0]; Taro.showLoading({ title: '上传中...', }); try { const randomKey = this.makeRandomName(); const cdnUrl = params.spliceImgUrlAPI || 'https://xcimg.szwego.com/'; qiniuCtx .upload( path, randomKey, randomKey, params.getImgUrlAPI ) .then((result) => { const { key } = result; const filterImg = cdnUrl + key; resovle(filterImg); }); } catch (error) { console.log(error); Taro.hideLoading(); Taro.showToast({ icon: 'none', title: '上传失败,请重新尝试...', }); } }, }); }); } // render() { // const obj = { // ...this.props, // onUpImg: this.onUpImg.bind(this), // }; // console.log(obj); // return <WgSearchBar {...obj} />; // } }
System.register(['./m2.js', './generated-m1.js'], function (exports, module) { 'use strict'; return { setters: [function (module) { exports('m2', module.default); }, function () {}], execute: function () { } }; });
import GroupNode from './GroupNode'; /** * */ export default class HoleNode extends GroupNode { }
import React from 'react'; import { Redirect } from 'react-router-dom'; import { useState, useEffect } from "react"; import { useSelector, useDispatch } from 'react-redux'; import './Micro.css'; import Cropper from "react-cropper"; import "cropperjs/dist/cropper.css"; import { Modal, notification, Space } from 'antd'; import { setMicroDate, setMicroTemperature, setMicroHumidity, setMicroStandard, setMicroManualResult, setMicroCheckList, setMicroImgGroup, setMicroImgAiInfo, setMicroStandardImgGroup } from '../slices/microSlice'; import { apiRunMicroTask, apiGetTask, apiUpdateTask, apiGetTaskReport } from '../util/api'; import MpHeader from '../components/MpHeader'; import CharacterInputBox from '../components/CharacterInputBox'; import CharacterImgList from '../components/CharacterImgList'; import PictureWall from '../components/PictureWall'; import AttachmentDrawerPlus from '../components/AttachmentDrawerPlus'; import AILoading from '../components/AILoading' const electron = window.require('electron'); const ipcRenderer = electron.ipcRenderer; export default function Micro(props) { const [redirect, setRedirect] = useState(null); const username = useSelector(state => state.global.username); const accessToken = useSelector(state => state.global.accessToken); const taskName = useSelector(state => state.global.taskName); const microId = useSelector(state => state.micro.microId); const dispatch = useDispatch(); const microDate = useSelector(state => state.micro.microDate); const microTemperature = useSelector(state => state.micro.microTemperature); const microHumidity = useSelector(state => state.micro.microHumidity); const microStandard = useSelector(state => state.micro.microStandard); const microManualResult = useSelector(state => state.micro.microManualResult); const microCheckList = useSelector(state => state.micro.microCheckList); const microImgGroup = useSelector(state => state.micro.microImgGroup); const microStandardImgGroup = useSelector(state => state.micro.microStandardImgGroup); const microImgAiInfo = useSelector(state => state.micro.microImgAiInfo); const [isImgSelectorMoadlVisible, setIsImgSelectorMoadlVisible] = useState(false); const [fileList, setFileList] = useState([]); const [isAttachmentDrawerVisible, setIsAttachmentDrawerVisible] = useState(false); const [attachmentDrawerUpdateToggle, setAttachmentDrawerUpdateToggle] = useState(0); const [isReportBtnActive, setIsReportBtnActive] = useState(false); const [isSaveBtnActive, setIsSaveBtnActive] = useState(true); const [isLoadingAI, setIsLoadingAI] = useState(false); const [modiTexts, setModiTexts] = useState([]); const [cache, setCache] = useState(null); useEffect(() => { dispatch(setMicroDate("")); dispatch(setMicroTemperature("")); dispatch(setMicroHumidity("")); dispatch(setMicroStandard("")); dispatch(setMicroManualResult("")); dispatch(setMicroCheckList([true, true, true, true, true])); dispatch(setMicroImgGroup(null)); dispatch(setMicroStandardImgGroup(null)); dispatch(setMicroImgAiInfo(null)); apiGetTask(accessToken, microId).then((res) => { setCache(res.data); dispatch(setMicroStandard(res.data.standard_desc)); dispatch(setMicroManualResult(res.data.desc_manual)); let newMicroCheckList = [true, true, true, true, true]; res.data.additional_fields.forEach(item => { if (item.field_name === "日期") { dispatch(setMicroDate(item.field_value)); newMicroCheckList[2] = item.is_included_in_report; } else if (item.field_name === "温度") { dispatch(setMicroTemperature(item.field_value)); newMicroCheckList[3] = item.is_included_in_report; } else if (item.field_name === "湿度") { dispatch(setMicroHumidity(item.field_value)); newMicroCheckList[4] = item.is_included_in_report; } }); dispatch(setMicroCheckList(newMicroCheckList)); if (res.data.result !== null) { setIsReportBtnActive(true); let newones_smp = []; let newones_std = []; let newones_info = []; res.data.result.results.forEach(item => { newones_smp.push(item.origin_image.save_path); newones_std.push(item.retrieval_image.save_path); newones_info.push(`类别: ${item.category}\n置信度: ${item.score.toFixed(2)}`); }); dispatch(setMicroImgGroup(newones_smp)); dispatch(setMicroStandardImgGroup(newones_std)); dispatch(setMicroImgAiInfo(newones_info)); } }).catch((err) => { console.log(err); }); }, []); useEffect(() => { if (microStandard === "" || microManualResult === "" || microDate === "" || microTemperature === "" || microHumidity == "") { setIsSaveBtnActive(false); } else { setIsSaveBtnActive(true); } }, [microStandard, microManualResult, microDate, microTemperature, microHumidity]); // -- BEGIN -- ProjectHeader相关 const onHeaderBackClick = (e) => { setRedirect("/project"); } const onQuitClick = (e) => { setRedirect("/"); } const onBreadClick = (e, tag) => { switch (tag) { case "home": setRedirect("/home"); break; case "project": setRedirect("/project"); break; default: break; } } // -- END -- ProjectHeader相关 // -- BEGIN -- CharacterInputBox相关 const onInputChange = (e, tag) => { switch (tag) { case "date": dispatch(setMicroDate(e.target.value)); break; case "temperature": dispatch(setMicroTemperature(e.target.value)); break; case "humidity": dispatch(setMicroHumidity(e.target.value)); break; case "standard": dispatch(setMicroStandard(e.target.value)); break; case "manualResult": dispatch(setMicroManualResult(e.target.value)); break; default: break; } } const onSwitchClick = (checked, e, idx) => { let newones = [...microCheckList]; newones[idx] = checked; dispatch(setMicroCheckList(newones)); } const onSaveInfoClick = (e) => { if (microDate === "" || microTemperature === "" || microHumidity == "") { notification.open({ message: "保存失败", description: "请输入所有必选项目。", }); } else { apiGetTask(accessToken, microId).then((res) => { // console.log(res.data); let additionalFields = []; additionalFields.push({ field_name: "日期", field_value: microDate, is_included_in_report: microCheckList[2], is_required: true, }); additionalFields.push({ field_name: "温度", field_value: microTemperature, is_included_in_report: microCheckList[3], is_required: true, }); additionalFields.push({ field_name: "湿度", field_value: microHumidity, is_included_in_report: microCheckList[4], is_required: true, }); apiUpdateTask(accessToken, res.data.name, res.data.type, res.data.id, microStandard, microManualResult, additionalFields, res.data.attachments, res.data.result, res.data.sub_type).then((res) => { notification.open({ message: "保存成功", }); }).catch((err) => { notification.open({ message: "保存失败", description: "网络错误。", }); console.log(err); }); }).catch((err) => { console.log(err); }); } } const onUploadSampleImgClick = (e) => { setIsImgSelectorMoadlVisible(true); } const onViewReportClick_discarded = (e) => { apiGetTaskReport(accessToken, microId).then((res) => { // console.log(res) ipcRenderer.send("view-file-online", res.data.save_path); setAttachmentDrawerUpdateToggle(attachmentDrawerUpdateToggle + 1); }).catch((err) => { console.log(err); }); } const onViewReportClick = (e) => { let additionalFields = []; additionalFields.push({ field_name: "日期", field_value: microDate, is_included_in_report: microCheckList[2], is_required: true, }); additionalFields.push({ field_name: "温度", field_value: microTemperature, is_included_in_report: microCheckList[3], is_required: true, }); additionalFields.push({ field_name: "湿度", field_value: microHumidity, is_included_in_report: microCheckList[4], is_required: true, }); apiUpdateTask(accessToken, cache.name, cache.type, cache.id, microStandard, microManualResult, additionalFields, cache.attachments, cache.result, cache.sub_type).then((res) => { apiGetTaskReport(accessToken, microId).then((res) => { // console.log(res) ipcRenderer.send("view-file-online", res.data.save_path); setAttachmentDrawerUpdateToggle(attachmentDrawerUpdateToggle + 1); }).catch((err) => { console.log(err); }); }).catch((err) => { notification.open({ message: "预览失败", description: "网络错误。", }); console.log(err); }); } const onExamineAttachmentClick = (e) => { setIsAttachmentDrawerVisible(true); } const onExamineStandardImgClick = (e) => { ipcRenderer.send("open-path", ["local", "micro", "standard"]); } // -- END -- CharacterInputBox相关 // -- BDGIN -- ImgSelectorModal相关 const dataurl2Blob = (dataurl) => { // convert base64 to raw binary data held in a string // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this var byteString = atob(dataurl.split(',')[1]); // separate out the mime component var mimeString = dataurl.split(',')[0].split(':')[1].split(';')[0] // write the bytes of the string to an ArrayBuffer var ab = new ArrayBuffer(byteString.length); // create a view into the buffer var ia = new Uint8Array(ab); // set the bytes of the buffer to the correct values for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } // write the ArrayBuffer to a blob, and you're done var blob = new Blob([ab], { type: mimeString }); return blob; } const onImgSelectorModalOk = () => { let formData = new FormData(); fileList.forEach(item => { formData.append('files', dataurl2Blob(item.thumbUrl), item.name); }); setIsLoadingAI(true); dispatch(setMicroStandardImgGroup(null)); apiRunMicroTask(accessToken, microId, formData).then((res) => { console.log(res); let newones_smp = []; let newones_std = []; let newones_info = []; res.data.result.results.forEach(item => { newones_smp.push(item.origin_image.save_path); newones_std.push(item.retrieval_image.save_path); newones_info.push(`类别: ${item.category}\n置信度: ${item.score.toFixed(2)}`); }); dispatch(setMicroImgGroup(newones_smp)); dispatch(setMicroStandardImgGroup(newones_std)); dispatch(setMicroImgAiInfo(newones_info)); setIsLoadingAI(false); setIsReportBtnActive(true); }).catch((err) => { console.log(err); }); setIsImgSelectorMoadlVisible(false); } const onImgSelectorModalCancel = () => { setIsImgSelectorMoadlVisible(false); } const uploadFileList = (fileList) => { setFileList(fileList); } // -- END -- ImgSelectorModal相关 // -- BEGIN -- AttachmentDrawer相关 const onAttachmentDrawerClose = () => { setIsAttachmentDrawerVisible(false); } // -- END -- AttachmentDrawer相关 const onModiInputChange = (idx, e) => { let newones = [... modiTexts]; newones[idx] = e.target.value; setModiTexts(newones) } if (redirect !== null) { return ( <Redirect push to={redirect} /> ); } return ( <div className="mp-micro"> <MpHeader onHeaderBackClick={onHeaderBackClick} onQuitClick={onQuitClick} onBreadClick={onBreadClick} username={username} breadItems={[ { text: "首页", isActive: true, funcTag: "home", }, { text: "项目", isActive: true, funcTag: "project", }, { text: taskName, isActive: false, }, ]} /> <Space className="mp-vlist" direction="vertical" size={'middle'}> <CharacterInputBox date={microDate} temperature={microTemperature} humidity={microHumidity} standard={microStandard} manualResult={microManualResult} checkList={microCheckList} isReportBtnActive={isReportBtnActive & isSaveBtnActive} isSaveBtnActive={isSaveBtnActive} onSaveInfoClick={onSaveInfoClick} onInputChange={onInputChange} onSwitchClick={onSwitchClick} onUploadSampleImgClick={onUploadSampleImgClick} onViewReportClick={onViewReportClick} onExamineStandardImgClick={onExamineStandardImgClick} onExamineAttachmentClick={onExamineAttachmentClick} /> <AILoading loading={isLoadingAI} /> </Space> <CharacterImgList characterImgGroup={microImgGroup} characterStandardImgGroup={microStandardImgGroup} characterImgAiInfo={microImgAiInfo} modiTexts={modiTexts} onModiInputChange={onModiInputChange} /> <AttachmentDrawerPlus visible={isAttachmentDrawerVisible} updateToggle={attachmentDrawerUpdateToggle} onClose={onAttachmentDrawerClose} networdArgs={{ type: "task", id: microId, accessToken: accessToken }} /> <Modal title="上传要识别的所有图片" visible={isImgSelectorMoadlVisible} onOk={onImgSelectorModalOk} onCancel={onImgSelectorModalCancel}> <PictureWall uploadFileList={uploadFileList} /> </Modal> </div> ); };
// Load storybook config import * as sbConfig from '../../../../../.storybook/storybook-config'; // Load template file import template from './template.njk'; // Load stylesheet file require('./_index.scss'); const componentName = 'Filter Menu'; const storyDescription = `${sbConfig.heading.lab} ${sbConfig.heading.basicRules} ### Components used - <a href="/docs/design-system-components-molecules-search-bar--lab-component">Search Bar</a> - <a href="/docs/design-system-components-molecules-filter-menu-section--lab-component">Filter Menu Section</a> ### Developer notes - The **Filter menu organism** takes the search bar and filter menu section molecules to build a set of configurable menus used for filtering - Javascript is required for the proper functioning of this component - The titles and filter options are configurable - The list of filters and their options can be of any length`; const sourceCode = `// Sass import \n@use "nhsd/components/organisms/filter-menu"; // HTML`; // Component defaults export default { title: `${sbConfig.title.designSystem} / ${sbConfig.title.components} / ${sbConfig.title.organisms} / ${componentName}`, parameters: { docs: { description: { component: storyDescription, }, }, }, }; // Component template const Template = (args) => template.render({ params: { ...args } }); export const LabComponent = Template.bind({}); LabComponent.storyName = sbConfig.title.lab; LabComponent.args = { placeholder: 'Filter search...', filters: [ { title: 'Heading 1', options: [ 'Filter 1', 'Filter 2', 'Filter 3', ], }, { title: 'Heading 2', options: [ 'Filter 1', 'Filter 2', 'Filter 3', ], }, ], button: { label: 'Filter results', }, }; LabComponent.parameters = { docs: { source: { code: `${sourceCode}\n${LabComponent(LabComponent.args)}`, }, }, };
"""Support for a ScreenLogic heating device.""" import logging from screenlogicpy.const import EQUIPMENT, HEAT_MODE from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( ATTR_PRESET_MODE, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.restore_state import RestoreEntity from . import ScreenlogicEntity from .const import DOMAIN _LOGGER = logging.getLogger(__name__) SUPPORTED_FEATURES = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE SUPPORTED_MODES = [HVAC_MODE_OFF, HVAC_MODE_HEAT] SUPPORTED_PRESETS = [ HEAT_MODE.SOLAR, HEAT_MODE.SOLAR_PREFERRED, HEAT_MODE.HEATER, ] async def async_setup_entry(hass, config_entry, async_add_entities): """Set up entry.""" entities = [] data = hass.data[DOMAIN][config_entry.entry_id] coordinator = data["coordinator"] for body in data["devices"]["body"]: entities.append(ScreenLogicClimate(coordinator, body)) async_add_entities(entities) class ScreenLogicClimate(ScreenlogicEntity, ClimateEntity, RestoreEntity): """Represents a ScreenLogic climate entity.""" def __init__(self, coordinator, body): """Initialize a ScreenLogic climate entity.""" super().__init__(coordinator, body) self._configured_heat_modes = [] # Is solar listed as available equipment? if self.coordinator.data["config"]["equipment_flags"] & EQUIPMENT.FLAG_SOLAR: self._configured_heat_modes.extend( [HEAT_MODE.SOLAR, HEAT_MODE.SOLAR_PREFERRED] ) self._configured_heat_modes.append(HEAT_MODE.HEATER) self._last_preset = None @property def name(self) -> str: """Name of the heater.""" ent_name = self.body["heat_status"]["name"] return f"{self.gateway_name} {ent_name}" @property def min_temp(self) -> float: """Minimum allowed temperature.""" return self.body["min_set_point"]["value"] @property def max_temp(self) -> float: """Maximum allowed temperature.""" return self.body["max_set_point"]["value"] @property def current_temperature(self) -> float: """Return water temperature.""" return self.body["last_temperature"]["value"] @property def target_temperature(self) -> float: """Target temperature.""" return self.body["heat_set_point"]["value"] @property def temperature_unit(self) -> str: """Return the unit of measurement.""" if self.config_data["is_celcius"]["value"] == 1: return TEMP_CELSIUS return TEMP_FAHRENHEIT @property def hvac_mode(self) -> str: """Return the current hvac mode.""" if self.body["heat_mode"]["value"] > 0: return HVAC_MODE_HEAT return HVAC_MODE_OFF @property def hvac_modes(self): """Return th supported hvac modes.""" return SUPPORTED_MODES @property def hvac_action(self) -> str: """Return the current action of the heater.""" if self.body["heat_status"]["value"] > 0: return CURRENT_HVAC_HEAT if self.hvac_mode == HVAC_MODE_HEAT: return CURRENT_HVAC_IDLE return CURRENT_HVAC_OFF @property def preset_mode(self) -> str: """Return current/last preset mode.""" if self.hvac_mode == HVAC_MODE_OFF: return HEAT_MODE.NAME_FOR_NUM[self._last_preset] return HEAT_MODE.NAME_FOR_NUM[self.body["heat_mode"]["value"]] @property def preset_modes(self): """All available presets.""" return [ HEAT_MODE.NAME_FOR_NUM[mode_num] for mode_num in self._configured_heat_modes ] @property def supported_features(self): """Supported features of the heater.""" return SUPPORTED_FEATURES async def async_set_temperature(self, **kwargs) -> None: """Change the setpoint of the heater.""" if (temperature := kwargs.get(ATTR_TEMPERATURE)) is None: raise ValueError(f"Expected attribute {ATTR_TEMPERATURE}") if await self.hass.async_add_executor_job( self.gateway.set_heat_temp, int(self._data_key), int(temperature) ): await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_temperature {temperature} on body {self.body['body_type']['value']}" ) async def async_set_hvac_mode(self, hvac_mode) -> None: """Set the operation mode.""" if hvac_mode == HVAC_MODE_OFF: mode = HEAT_MODE.OFF else: mode = HEAT_MODE.NUM_FOR_NAME[self.preset_mode] if await self.hass.async_add_executor_job( self.gateway.set_heat_mode, int(self._data_key), int(mode) ): await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_hvac_mode {mode} on body {self.body['body_type']['value']}" ) async def async_set_preset_mode(self, preset_mode: str) -> None: """Set the preset mode.""" _LOGGER.debug("Setting last_preset to %s", HEAT_MODE.NUM_FOR_NAME[preset_mode]) self._last_preset = mode = HEAT_MODE.NUM_FOR_NAME[preset_mode] if self.hvac_mode == HVAC_MODE_OFF: return if await self.hass.async_add_executor_job( self.gateway.set_heat_mode, int(self._data_key), int(mode) ): await self.coordinator.async_request_refresh() else: raise HomeAssistantError( f"Failed to set_preset_mode {mode} on body {self.body['body_type']['value']}" ) async def async_added_to_hass(self): """Run when entity is about to be added.""" await super().async_added_to_hass() _LOGGER.debug("Startup last preset is %s", self._last_preset) if self._last_preset is not None: return prev_state = await self.async_get_last_state() if ( prev_state is not None and prev_state.attributes.get(ATTR_PRESET_MODE) is not None ): _LOGGER.debug( "Startup setting last_preset to %s from prev_state", HEAT_MODE.NUM_FOR_NAME[prev_state.attributes.get(ATTR_PRESET_MODE)], ) self._last_preset = HEAT_MODE.NUM_FOR_NAME[ prev_state.attributes.get(ATTR_PRESET_MODE) ] else: _LOGGER.debug( "Startup setting last_preset to default (%s)", self._configured_heat_modes[0], ) self._last_preset = self._configured_heat_modes[0] @property def body(self): """Shortcut to access body data.""" return self.coordinator.data["bodies"][self._data_key]
from django.contrib.auth.backends import RemoteUserBackend import os import collection_registry.middleware from django.contrib.auth.models import Group from django.core.mail import send_mail, EmailMultiAlternatives class RegistryUserBackend(RemoteUserBackend): def configure_user(self, user): """ Registry user setup """ user.is_active = False request = collection_registry.middleware.get_current_request() user.email = request.META['mail'] user.save() # http://stackoverflow.com/a/6288863/1763984 g = Group.objects.get(name=request.META['Shib-Identity-Provider']) g.user_set.add(user) # https://docs.djangoproject.com/en/dev/topics/email/ plaintext_content = "Welcome {0}. You have requested an account for the UC Libraries Digital Collection (UCLDC).\n\n\ At this time, accounts are limited to UCLDC Implementation Project collaborators (SAG2 and Product Stakeholder\ Group members and their designees). If your request is approved, you will receive an email within 72 hours with\ additional instructions on how to edit the Collection Registry and access the Nuxeo DAMS.\n\nFor\ more information about UCLDC Implementation, visit our project wiki at bit.ly/UCLDC or contact [email protected].".format(user.email) html_content = "<p>Welcome {0}. You have requested an account for the UC Libraries Digital\ Collection (UCLDC).</p><p>At this time, accounts are limited to UCLDC Implementation Project\ collaborators (SAG2 and Product Stakeholder Group members and their designees). If your request\ is approved, you will receive an email within 72 hours with additional instructions on how to\ edit the Collection Registry and access the Nuxeo DAMS.</p><p>For more information about UCLDC\ Implementation, visit our <a href='https://wiki.library.ucsf.edu/display/UCLDC/UCLDC+Implementation'>\ project wiki</a> or contact <a href='mailto:[email protected]'>[email protected]</a>.</p>".format(user.email) email_to_user = EmailMultiAlternatives('UCLDC account request: {0}'.format(user.email), plaintext_content, '[email protected]', [user.email], ['[email protected]']) email_to_user.attach_alternative(html_content, "text/html") email_to_user.send() return user
const alias = require('./common/webpack.alias'); module.exports = { /** * This is the main entry point for your application, it's the first file * that runs in the main process. */ entry: './src/main/main.ts', // Put your normal webpack config below here module: { rules: require('./common/webpack.rules'), }, resolve: { extensions: ['.js', '.ts', '.jsx', '.tsx', '.css', '.json'], alias: alias, }, };
var myLocations = [ { title: 'Gandhi Smriti', lat: 28.601780, lng: 77.214339 }, { title: 'Rashtrapati Bhawan', lat: 28.614360, lng: 77.199621 }, { title: 'Lord of the drinks', lat: 28.631849, lng: 77.216913 }, { title: 'Taj Palace', lat: 28.595453, lng: 77.171027 }, { title: 'The Leela Palace', lat: 28.580038, lng: 77.189038 }, { title: 'Adventure Island', lat: 28.723728, lng: 77.113592 }, { title: 'Akshardham', lat: 28.612673, lng: 77.277262 }, { title: 'Dlf Emporio', lat: 28.543425, lng: 77.156765 }, { title: 'Red Fort', lat: 28.656159, lng: 77.24102 }, { title: 'Jantar Mantar', lat: 28.627055, lng: 77.216627 }, { title: 'Lotus Temple', lat: 28.553492, lng: 77.258826 } ]
import React from "react"; import { Formik } from "formik"; import classNames from "classnames"; import Checkbox from "../Checkbox"; import Input from "../Input"; import ThemeToggle from "../ThemeToggle"; import productSchema from "./todo-schema"; import hero from "../../img/hero.jpg"; import "./AppHeader.scss"; function Appheader({ handleAddTodo, handleThemeClick, currentTheme }) { const headerClasses = classNames({ TODO__Header: true, TODO__Header__DarkMode: currentTheme, }); const formClasses = classNames({ TODO__Form: true, TODO__Form__DarkMode: currentTheme, }); const heroClasses = classNames({ heroImg: true, heroImg__darkMode: currentTheme, }); return ( <header> <div className={heroClasses} alt="hero" src={hero}> <div className="themeSwitcherWrap"> <h1 className={headerClasses}>TODO</h1> <ThemeToggle handleThemeClick={handleThemeClick} currentTheme={currentTheme} /> </div> <Formik initialValues={{ name: "", }} validationSchema={productSchema} validateOnBlur={false} onSubmit={(values, { resetForm }) => { handleAddTodo(values); resetForm(); }} > {({ handleChange, handleBlur, handleSubmit, errors, values, touched, }) => ( <form className={formClasses} onSubmit={handleSubmit}> <Checkbox handleChange={() => {}} /> <Input // className={inputClasses} type="text" placeholder="Create task" id="name" value={values.name} handleChange={handleChange} handleBlur={handleBlur} hasErrorMessage={touched.name} errorMessage={errors.name} currentTheme={currentTheme} /> </form> )} </Formik> </div> </header> ); } export default Appheader;
import raf from 'raf'; import { doesStringContainHTMLTag, getDOMElementFromString, getRandomInteger, } from './../utils'; import './Typewriter.scss'; class Typewriter { eventNames = { TYPE_CHARACTER: 'TYPE_CHARACTER', REMOVE_CHARACTER: 'REMOVE_CHARACTER', REMOVE_ALL: 'REMOVE_ALL', REMOVE_LAST_VISIBLE_NODE: 'REMOVE_LAST_VISIBLE_NODE', PAUSE_FOR: 'PAUSE_FOR', CALL_FUNCTION: 'CALL_FUNCTION', ADD_HTML_TAG_ELEMENT: 'ADD_HTML_TAG_ELEMENT', REMOVE_HTML_TAG_ELEMENT: 'REMOVE_HTML_TAG_ELEMENT', CHANGE_DELETE_SPEED: 'CHANGE_DELETE_SPEED', CHANGE_DELAY: 'CHANGE_DELAY', } visibleNodeTypes = { HTML_TAG: 'HTML_TAG', TEXT_NODE: 'TEXT_NODE', } state = { cursorAnimation: null, lastFrameTime: null, pauseUntil: null, eventQueue: [], eventLoop: null, eventLoopPaused: false, reverseCalledEvents: [], calledEvents: [], visibleNodes: [], initialOptions: null, elements: { container: null, wrapper: document.createElement('span'), cursor: document.createElement('span'), }, } options = { strings: null, cursor: '|', delay: 'natural', deleteSpeed: 'natural', loop: false, autoStart: false, devMode: false, wrapperClassName: 'Typewriter__wrapper', cursorClassName: 'Typewriter__cursor', } constructor(container, options) { if(!container) { throw new Error('No container element was provided'); return; } if(typeof container === 'string') { const containerElement = document.querySelector(container); if(!containerElement) { throw new Error('Could not find container element'); return; } this.state.elements.container = containerElement; } else { this.state.elements.container = container; } if(options) { this.options = { ...this.options, ...options }; } // Make a copy of the options used to reset options when looping this.state.initialOptions = this.options; this.init(); } init() { this.setupWrapperElement(); if(this.options.autoStart === true && this.options.strings) { this.typeOutAllStrings().start(); } } /** * Replace all child nodes of provided element with * state wrapper element used for typewriter effect * * @author Tameem Safi <[email protected]> */ setupWrapperElement = () => { this.state.elements.wrapper.className = this.options.wrapperClassName; this.state.elements.cursor.className = this.options.cursorClassName; this.state.elements.cursor.innerHTML = this.options.cursor; this.state.elements.container.innerHTML = ''; this.state.elements.container.appendChild(this.state.elements.wrapper); this.state.elements.container.appendChild(this.state.elements.cursor); } /** * Start typewriter effect */ start = () => { this.state.eventLoopPaused = false; this.runEventLoop(); return this; } /** * Pause the event loop * * @author Tameem Safi <[email protected]> */ pause = () => { this.state.eventLoopPaused = true; return this; } /** * Destroy current running instance * * @author Tameem Safi <[email protected]> */ stop = () => { if(this.state.eventLoop) { raf.cancel(this.state.eventLoop); } return this; } /** * Add pause event to queue for ms provided * * @param {Number} ms Time in ms to pause for * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ pauseFor = (ms) => { this.addEventToQueue(this.eventNames.PAUSE_FOR, { ms }); return this; } /** * Start typewriter effect by typing * out all strings provided * * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ typeOutAllStrings = () => { if(typeof this.options.strings === 'string') { this.typeString(this.options.strings) .pauseFor(1500); return this; } this.options.strings.forEach((string, index) => { this.typeString(string) .pauseFor(1500) .deleteAll(); }); return this; } /** * Adds string characters to event queue for typing * * @param {String} string String to type * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ typeString = (string) => { if(doesStringContainHTMLTag(string)) { return this.typeOutHTMLString(string); } const characters = string.split(''); characters.forEach(character => { this.addEventToQueue(this.eventNames.TYPE_CHARACTER, { character }); }); return this; } /** * Type out a string which is wrapper around HTML tag * * @param {String} string String to type * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ typeOutHTMLString = (string) => { const childNodes = getDOMElementFromString(string); if(childNodes.length > 0 ) { for(let i = 0; i < childNodes.length; i++) { const node = childNodes[i]; if(node.nodeType && node.nodeType === 1) { const text = node.innerText; const characters = text.split(''); // Reset innerText of HTML element node.innerText = ''; // Add event queue item to insert HTML tag before typing characters this.addEventToQueue(this.eventNames.ADD_HTML_TAG_ELEMENT, { node, }); if(!characters.length) { return this; } characters.forEach(character => { this.addEventToQueue(this.eventNames.TYPE_CHARACTER, { character, node, }); }); } else { if(node.textContent) { this.typeString(node.textContent); } } } } return this; } /** * Add delete all characters to event queue * * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ deleteAll = (speed = 'natural') => { this.addEventToQueue(this.eventNames.REMOVE_ALL, { speed }); return this; } /** * Change delete speed * * @param {Number} speed Speed to use for deleting characters * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ changeDeleteSpeed = (speed) => { this.addEventToQueue(this.eventNames.CHANGE_DELETE_SPEED, { speed }); return this; } /** * Change delay when typing * * @param {Number} delay Delay when typing out characters * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ changeDelay = (delay) => { this.addEventToQueue(this.eventNames.CHANGE_DELAY, { delay }); return this; } /** * Add delete character to event queue for amount of characters provided * * @param {Number} amount Number of characters to remove * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ deleteChars = (amount) => { for(let i = 0; i < amount; i++) { this.addEventToQueue(this.eventNames.REMOVE_CHARACTER); } return this; } /** * Add an event item to call a callback function * * @param {cb} cb Callback function to call * @param {Object} thisArg thisArg to use when calling function * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ callFunction = (cb, thisArg) => { if(typeof cb === 'function') { this.addEventToQueue(this.eventNames.CALL_FUNCTION, { cb, thisArg }); } return this; } /** * Add type character event for each character * * @param {Array} characters Array of characters * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ typeCharacters = (characters) => { characters.forEach(character => { this.addEventToQueue(this.eventNames.TYPE_CHARACTER, { character }); }); return this; } /** * Add remove character event for each character * * @param {Array} characters Array of characters * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ removeCharacters = (characters) => { characters.forEach(() => { this.addEventToQueue(this.eventNames.REMOVE_CHARACTER); }); return this; } /** * Add an event to the event queue * * @param {String} eventName Name of the event * @param {String} eventArgs Arguments to pass to event callback * @param {Boolean} prepend Prepend to begining of event queue * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ addEventToQueue = (eventName, eventArgs, prepend = false) => { return this.addEventToStateProperty( eventName, eventArgs, prepend, 'eventQueue' ); } /** * Add an event to reverse called events used for looping * * @param {String} eventName Name of the event * @param {String} eventArgs Arguments to pass to event callback * @param {Boolean} prepend Prepend to begining of event queue * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ addReverseCalledEvent = (eventName, eventArgs, prepend = false) => { const { loop } = this.options; if(!loop) { return this; } return this.addEventToStateProperty( eventName, eventArgs, prepend, 'reverseCalledEvents' ); } /** * Add an event to correct state property * * @param {String} eventName Name of the event * @param {Object} eventArgs Arguments to pass to event callback * @param {Boolean} prepend Prepend to begining of event queue * @param {String} property Property name of state object * @return {Typewriter} * * @author Tameem Safi <[email protected]> */ addEventToStateProperty = (eventName, eventArgs, prepend = false, property) => { const eventItem = { eventName, eventArgs: eventArgs || {}, }; if(prepend) { this.state[property] = [ eventItem, ...this.state[property], ]; } else { this.state[property] = [ ...this.state[property], eventItem, ]; } return this; } /** * Run the event loop and do anything inside of the queue * * @author Tameem Safi <[email protected]> */ runEventLoop = () => { if(!this.state.lastFrameTime) { this.state.lastFrameTime = Date.now(); } // Setup variables to calculate if this frame should run const nowTime = Date.now(); const delta = nowTime - this.state.lastFrameTime; if(!this.state.eventQueue.length) { if(!this.options.loop) { return; } // Reset event queue if we are looping this.state.eventQueue = [...this.state.calledEvents]; this.state.calledEvents = []; this.options = {...this.state.initialOptions}; this.addEventToQueue(this.eventNames.REMOVE_ALL, null, true); } // Request next frame this.state.eventLoop = raf(this.runEventLoop); // Check if event loop is paused if(this.state.eventLoopPaused) { return; } // Check if state has pause until time if(this.state.pauseUntil) { // Check if event loop should be paused if(nowTime < this.state.pauseUntil) { return; } // Reset pause time this.state.pauseUntil = null; } // Make a clone of event queue const eventQueue = [...this.state.eventQueue]; // Get first event from queue const currentEvent = eventQueue.shift(); // Setup delay variable let delay = 0; // Check if frame should run or be // skipped based on fps interval if( currentEvent.eventName === this.eventNames.REMOVE_LAST_VISIBLE_NODE || currentEvent.eventName === this.eventNames.REMOVE_CHARACTER ) { delay = this.options.deleteSpeed === 'natural' ? getRandomInteger(40, 80) : this.options.deleteSpeed; } else { delay = this.options.delay === 'natural' ? getRandomInteger(120, 160) : this.options.delay; } if(delta <= delay) { return; } // Get current event args const { eventName, eventArgs } = currentEvent; this.logInDevMode({ currentEvent, state: this.state }); // Run item from event loop switch(eventName) { case this.eventNames.TYPE_CHARACTER: { const { character, node } = eventArgs; const textNode = document.createTextNode(character); if(node) { node.appendChild(textNode); } else { this.state.elements.wrapper.appendChild(textNode); } this.state.visibleNodes = [ ...this.state.visibleNodes, { type: this.visibleNodeTypes.TEXT_NODE, node: textNode, }, ]; break; } case this.eventNames.REMOVE_CHARACTER: { eventQueue.unshift({ eventName: this.eventNames.REMOVE_LAST_VISIBLE_NODE, eventArgs: { removingCharacterNode: true }, }); break; } case this.eventNames.PAUSE_FOR: { const { ms } = currentEvent.eventArgs; this.state.pauseUntil = Date.now() + parseInt(ms); break; } case this.eventNames.CALL_FUNCTION: { const { cb, thisArg } = currentEvent.eventArgs; cb.call(thisArg, { elements: this.state.elements, }); break; } case this.eventNames.ADD_HTML_TAG_ELEMENT: { const { node } = currentEvent.eventArgs; this.state.elements.wrapper.appendChild(node); this.state.visibleNodes = [ ...this.state.visibleNodes, { type: this.visibleNodeTypes.HTML_TAG, node, }, ]; break; } case this.eventNames.REMOVE_ALL: { const { visibleNodes } = this.state; const { speed } = eventArgs; const removeAllEventItems = []; // Change speed before deleteing if(speed) { removeAllEventItems.push({ eventName: this.eventNames.CHANGE_DELETE_SPEED, eventArgs: { speed }, }); } for(let i = 0, length = visibleNodes.length; i < length; i++) { removeAllEventItems.push({ eventName: this.eventNames.REMOVE_LAST_VISIBLE_NODE, eventArgs: { removingCharacterNode: false }, }); } // Change speed back to normal after deleteing if(speed) { removeAllEventItems.push({ eventName: this.eventNames.CHANGE_DELETE_SPEED, eventArgs: { speed: this.options.deleteSpeed }, }); } eventQueue.unshift(...removeAllEventItems); break; } case this.eventNames.REMOVE_LAST_VISIBLE_NODE: { const { removingCharacterNode } = currentEvent.eventArgs; if(this.state.visibleNodes.length) { const { type, node } = this.state.visibleNodes.pop(); node.parentElement.removeChild(node); // If we are removing characters only then remove one more // item if current element was wrapper html tag if(type === this.visibleNodeTypes.HTML_TAG && removingCharacterNode) { eventQueue.unshift({ eventName: this.eventNames.REMOVE_LAST_VISIBLE_NODE, eventArgs: {}, }); } } break; } case this.eventNames.CHANGE_DELETE_SPEED: { this.options.deleteSpeed = currentEvent.eventArgs.speed; break; } case this.eventNames.CHANGE_DELAY: { this.options.delay = currentEvent.eventArgs.delay; break; } default: { break; } } // Add que item to called queue if we are looping if(this.options.loop) { if( currentEvent.eventName !== this.eventNames.REMOVE_ALL && currentEvent.eventName !== this.eventNames.REMOVE_CHARACTER ) { this.state.calledEvents = [ ...this.state.calledEvents, currentEvent ]; } } // Replace state even queue with cloned queue this.state.eventQueue = eventQueue; // Set last frame time so it can be used to calculate next frame this.state.lastFrameTime = nowTime; } /** * Log a message in development mode * * @param {Mixed} message Message or item to console.log * @author Tameem Safi <[email protected]> */ logInDevMode(message) { if(this.options.devMode) { console.log(message); } } } export default Typewriter;
'use strict'; var inherits = require('util').inherits; var EE = require('events').EventEmitter; var async = require('async'); var VirtualDevice = require('./VirtualDevice'); var suspend = require('suspend'); /* Events: - data Current tests: two devices on the network dev1 connects with will dev2 connects without will User: check device list from GwMonitor dev2 subscribes to topic 'test' dev2 subscribes to topic 'test1' dev1 subscribes to topic 'test2' User: check subscription and topic lists from GwMonitor dev1 registers and publishes topic 'test' User: check subscription and topic lists from GwMonitor User: check that only device 2 gets the message (from terminal, packet prints) User: subscribe to topic 'test' from MQTTLens or similar and check correct message reception dev2: unsubscribes to topic 'test' User: check subscription and topic lists from GwMonitor dev2: disconnects User: check device lists from GwMonitor */ var VirtualNetwork = function() { var self = this; self.dev1 = new VirtualDevice(1, self); self.dev2 = new VirtualDevice(2, self); }; inherits(VirtualNetwork, EE); VirtualNetwork.prototype.init = function() { var self = this; // Connect test with will suspend.run(function* test1() { yield setTimeout(suspend.resume(), 1000); console.log("\nStarting test 1..."); self.dev1.connect(true); yield self.dev1.waitFor('willtopicreq', suspend.resume()); self.dev1.willTopic(); yield self.dev1.waitFor('willmsgreq', suspend.resume()); self.dev1.willMsg(); yield self.dev1.waitFor('connack', suspend.resume()); console.log(":::::::::::Connect Test with will OK"); }); // Connect test without will suspend.run(function* test2() { yield setTimeout(suspend.resume(), 2000); console.log("\nStarting test 2..."); self.dev2.connect(false); yield self.dev2.waitFor('connack', suspend.resume()); console.log(":::::::::::Connect Test without will OK"); }); // Subscribe test suspend.run(function* test3() { yield setTimeout(suspend.resume(), 3000); console.log("\nStarting test 3..."); self.dev2.subscribe(0, 'normal', 'test'); // qos, topicIdType, topic yield self.dev2.waitFor('suback', suspend.resume()); console.log(":::::::::::Subscribe test OK"); }); // Subscribe test suspend.run(function* test3_1() { yield setTimeout(suspend.resume(), 3000); console.log("\nStarting test 3.1..."); self.dev2.subscribe(0, 'normal', 'test1'); // qos, topicIdType, topic yield self.dev2.waitFor('suback', suspend.resume()); console.log(":::::::::::Subscribe test OK"); }); // Subscribe test suspend.run(function* test3_2() { yield setTimeout(suspend.resume(), 3000); console.log("\nStarting test 3.2..."); self.dev1.subscribe(0, 'normal', 'test2'); // qos, topicIdType, topic yield self.dev1.waitFor('suback', suspend.resume()); console.log(":::::::::::Subscribe test OK"); }); // Publish test suspend.run(function* test4() { yield setTimeout(suspend.resume(), 4000); console.log("\nStarting test 4..."); // Register topic self.dev1.register('test'); yield self.dev1.waitFor('regack', suspend.resume()); // TODO: get assigned topic id from regack self.dev1.publish(0, false, 'normal', 4, 'hola test'); // qos, retain, topicIdType, topicId, payload console.log(":::::::::::Publish test OK"); }); // unsubscribe test suspend.run(function* test5() { yield setTimeout(suspend.resume(), 5000); console.log("\nStarting test 5..."); self.dev2.unsubscribe('normal', 'test'); // topicIdType, topic yield self.dev2.waitFor('unsuback', suspend.resume()); console.log(":::::::::::Unsubscribe test OK"); }); // disconnect test suspend.run(function* test6() { yield setTimeout(suspend.resume(), 6000); console.log("\nStarting test 6..."); self.dev2.disconnect(null); // duration, null = no duration yield self.dev2.waitFor('disconnect', suspend.resume()); console.log(":::::::::::Disconnect test OK"); }); }; VirtualNetwork.prototype.send = function(addr, frame) { var self = this; //console.log("sending:", frame, addr); if(addr === self.dev1.addr) self.dev1.parse(frame); if(addr === self.dev2.addr) self.dev2.parse(frame); }; module.exports = VirtualNetwork;
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ * * Version: 5.0.8 (2019-06-18) */ !function(m){"use strict";var l=function(e){var t=e,n=function(){return t};return{get:n,set:function(e){t=e},clone:function(){return l(n())}}},y=function(){},C=function(n,r){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return n(r.apply(null,e))}},S=function(e){return function(){return e}},o=function(e){return e};function b(r){for(var o=[],e=1;e<arguments.length;e++)o[e-1]=arguments[e];return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=o.concat(e);return r.apply(null,n)}}var e,t,n,r,i,d=function(n){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return!n.apply(null,e)}},u=function(e){return function(){throw new Error(e)}},a=function(e){return e()},f=S(!1),c=S(!0),s=f,g=c,p=function(){return h},h=(r={fold:function(e,t){return e()},is:s,isSome:s,isNone:g,getOr:n=function(e){return e},getOrThunk:t=function(e){return e()},getOrDie:function(e){throw new Error(e||"error: getOrDie called on none.")},getOrNull:function(){return null},getOrUndefined:function(){return undefined},or:n,orThunk:t,map:p,ap:p,each:function(){},bind:p,flatten:p,exists:s,forall:g,filter:p,equals:e=function(e){return e.isNone()},equals_:e,toArray:function(){return[]},toString:S("none()")},Object.freeze&&Object.freeze(r),r),v=function(n){var e=function(){return n},t=function(){return o},r=function(e){return e(n)},o={fold:function(e,t){return t(n)},is:function(e){return n===e},isSome:g,isNone:s,getOr:e,getOrThunk:e,getOrDie:e,getOrNull:e,getOrUndefined:e,or:t,orThunk:t,map:function(e){return v(e(n))},ap:function(e){return e.fold(p,function(e){return v(e(n))})},each:function(e){e(n)},bind:r,flatten:e,exists:r,forall:r,filter:function(e){return e(n)?o:h},equals:function(e){return e.is(n)},equals_:function(e,t){return e.fold(s,function(e){return t(n,e)})},toArray:function(){return[n]},toString:function(){return"some("+n+")"}};return o},x={some:v,none:p,from:function(e){return null===e||e===undefined?h:v(e)}},w=tinymce.util.Tools.resolve("tinymce.PluginManager"),R=function(t){return function(e){return function(e){if(null===e)return"null";var t=typeof e;return"object"===t&&Array.prototype.isPrototypeOf(e)?"array":"object"===t&&String.prototype.isPrototypeOf(e)?"string":t}(e)===t}},T=R("string"),O=R("array"),D=R("boolean"),A=R("function"),E=R("number"),N=Array.prototype.slice,k=(i=Array.prototype.indexOf)===undefined?function(e,t){return F(e,t)}:function(e,t){return i.call(e,t)},I=function(e,t){return-1<k(e,t)},P=function(e,t){return H(e,t).isSome()},B=function(e,t){for(var n=e.length,r=new Array(n),o=0;o<n;o++){var i=e[o];r[o]=t(i,o,e)}return r},M=function(e,t){for(var n=0,r=e.length;n<r;n++){t(e[n],n,e)}},W=function(e,t){for(var n=e.length-1;0<=n;n--){t(e[n],n,e)}},_=function(e,t){for(var n=[],r=0,o=e.length;r<o;r++){var i=e[r];t(i,r,e)&&n.push(i)}return n},L=function(e,t,n){return W(e,function(e){n=t(n,e)}),n},j=function(e,t,n){return M(e,function(e){n=t(n,e)}),n},z=function(e,t){for(var n=0,r=e.length;n<r;n++){var o=e[n];if(t(o,n,e))return x.some(o)}return x.none()},H=function(e,t){for(var n=0,r=e.length;n<r;n++){if(t(e[n],n,e))return x.some(n)}return x.none()},F=function(e,t){for(var n=0,r=e.length;n<r;++n)if(e[n]===t)return n;return-1},U=Array.prototype.push,q=function(e){for(var t=[],n=0,r=e.length;n<r;++n){if(!Array.prototype.isPrototypeOf(e[n]))throw new Error("Arr.flatten item "+n+" was not an array, input: "+e);U.apply(t,e[n])}return t},V=function(e,t){var n=B(e,t);return q(n)},G=function(e,t){for(var n=0,r=e.length;n<r;++n){if(!0!==t(e[n],n,e))return!1}return!0},Y=function(e){var t=N.call(e,0);return t.reverse(),t},K=function(e){return 0===e.length?x.none():x.some(e[e.length-1])},X=(A(Array.from)&&Array.from,Object.keys),$=Object.hasOwnProperty,J=function(e,t){for(var n=X(e),r=0,o=n.length;r<o;r++){var i=n[r];t(e[i],i,e)}},Q=function(e,r){return Z(e,function(e,t,n){return{k:t,v:r(e,t,n)}})},Z=function(r,o){var i={};return J(r,function(e,t){var n=o(e,t,r);i[n.k]=n.v}),i},ee=function(e,t){return te(e,t)?x.from(e[t]):x.none()},te=function(e,t){return $.call(e,t)},ne=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];return function(){for(var n=[],e=0;e<arguments.length;e++)n[e]=arguments[e];if(t.length!==n.length)throw new Error('Wrong number of arguments to struct. Expected "['+t.length+']", got '+n.length+" arguments");var r={};return M(t,function(e,t){r[e]=S(n[t])}),r}},re=function(e){return e.slice(0).sort()},oe=function(e,t){throw new Error("All required keys ("+re(e).join(", ")+") were not specified. Specified keys were: "+re(t).join(", ")+".")},ie=function(e){throw new Error("Unsupported keys for object: "+re(e).join(", "))},ue=function(t,e){if(!O(e))throw new Error("The "+t+" fields must be an array. Was: "+e+".");M(e,function(e){if(!T(e))throw new Error("The value "+e+" in the "+t+" fields was not a string.")})},ce=function(e){var n=re(e);z(n,function(e,t){return t<n.length-1&&e===n[t+1]}).each(function(e){throw new Error("The field: "+e+" occurs more than once in the combined fields: ["+n.join(", ")+"].")})},ae=function(o,i){var u=o.concat(i);if(0===u.length)throw new Error("You must specify at least one required or optional field.");return ue("required",o),ue("optional",i),ce(u),function(t){var n=X(t);G(o,function(e){return I(n,e)})||oe(o,n);var e=_(n,function(e){return!I(u,e)});0<e.length&&ie(e);var r={};return M(o,function(e){r[e]=S(t[e])}),M(i,function(e){r[e]=S(Object.prototype.hasOwnProperty.call(t,e)?x.some(t[e]):x.none())}),r}},le=(m.Node.ATTRIBUTE_NODE,m.Node.CDATA_SECTION_NODE,m.Node.COMMENT_NODE),fe=m.Node.DOCUMENT_NODE,se=(m.Node.DOCUMENT_TYPE_NODE,m.Node.DOCUMENT_FRAGMENT_NODE,m.Node.ELEMENT_NODE),de=m.Node.TEXT_NODE,me=(m.Node.PROCESSING_INSTRUCTION_NODE,m.Node.ENTITY_REFERENCE_NODE,m.Node.ENTITY_NODE,m.Node.NOTATION_NODE,function(e){return e.dom().nodeName.toLowerCase()}),ge=function(e){return e.dom().nodeType},pe=function(t){return function(e){return ge(e)===t}},he=function(e){return ge(e)===le||"#comment"===me(e)},ve=pe(se),be=pe(de),we=pe(fe),ye=function(e,t,n){if(!(T(n)||D(n)||E(n)))throw m.console.error("Invalid call to Attr.set. Key ",t,":: Value ",n,":: Element ",e),new Error("Attribute value was not simple");e.setAttribute(t,n+"")},Ce=function(e,t,n){ye(e.dom(),t,n)},Se=function(e,t){var n=e.dom();J(t,function(e,t){ye(n,t,e)})},xe=function(e,t){var n=e.dom().getAttribute(t);return null===n?undefined:n},Re=function(e,t){var n=e.dom();return!(!n||!n.hasAttribute)&&n.hasAttribute(t)},Te=function(e,t){e.dom().removeAttribute(t)},Oe=function(e){return j(e.dom().attributes,function(e,t){return e[t.name]=t.value,e},{})},De=function(e,t,n){return""===t||!(e.length<t.length)&&e.substr(n,n+t.length)===t},Ae=function(e,t){return-1!==e.indexOf(t)},Ee=function(e,t){return De(e,t,0)},Ne=function(e){return e.style!==undefined},ke=function(n){var r,o=!1;return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return o||(o=!0,r=n.apply(null,e)),r}},Ie=function(e){if(null===e||e===undefined)throw new Error("Node cannot be null or undefined");return{dom:S(e)}},Pe={fromHtml:function(e,t){var n=(t||m.document).createElement("div");if(n.innerHTML=e,!n.hasChildNodes()||1<n.childNodes.length)throw m.console.error("HTML does not have a single root node",e),new Error("HTML must have a single root node");return Ie(n.childNodes[0])},fromTag:function(e,t){var n=(t||m.document).createElement(e);return Ie(n)},fromText:function(e,t){var n=(t||m.document).createTextNode(e);return Ie(n)},fromDom:Ie,fromPoint:function(e,t,n){var r=e.dom();return x.from(r.elementFromPoint(t,n)).map(Ie)}},Be=function(e){var t=be(e)?e.dom().parentNode:e.dom();return t!==undefined&&null!==t&&t.ownerDocument.body.contains(t)},Me=ke(function(){return We(Pe.fromDom(m.document))}),We=function(e){var t=e.dom().body;if(null===t||t===undefined)throw new Error("Body is not available yet");return Pe.fromDom(t)},_e=function(e,t,n){if(!T(n))throw m.console.error("Invalid call to CSS.set. Property ",t,":: Value ",n,":: Element ",e),new Error("CSS value must be a string: "+n);Ne(e)&&e.style.setProperty(t,n)},Le=function(e,t){Ne(e)&&e.style.removeProperty(t)},je=function(e,t,n){var r=e.dom();_e(r,t,n)},ze=function(e,t){var n=e.dom();J(t,function(e,t){_e(n,t,e)})},He=function(e,t){var n=e.dom(),r=m.window.getComputedStyle(n).getPropertyValue(t),o=""!==r||Be(e)?r:Fe(n,t);return null===o?undefined:o},Fe=function(e,t){return Ne(e)?e.style.getPropertyValue(t):""},Ue=function(e,t){var n=e.dom(),r=Fe(n,t);return x.from(r).filter(function(e){return 0<e.length})},qe=function(e,t){var n=e.dom();Le(n,t),Re(e,"style")&&""===xe(e,"style").replace(/^\s+|\s+$/g,"")&&Te(e,"style")},Ve=function(e,t){var n=e.dom(),r=t.dom();Ne(n)&&Ne(r)&&(r.style.cssText=n.style.cssText)},Ge="undefined"!=typeof m.window?m.window:Function("return this;")(),Ye=function(e,t){return function(e,t){for(var n=t!==undefined&&null!==t?t:Ge,r=0;r<e.length&&n!==undefined&&null!==n;++r)n=n[e[r]];return n}(e.split("."),t)},Ke=function(e,t){var n=Ye(e,t);if(n===undefined||null===n)throw e+" not available on this browser";return n},Xe=function(){return Ke("Node")},$e=function(e,t,n){return 0!=(e.compareDocumentPosition(t)&n)},Je=function(e,t){return $e(e,t,Xe().DOCUMENT_POSITION_CONTAINED_BY)},Qe=function(e,t){var n=function(e,t){for(var n=0;n<e.length;n++){var r=e[n];if(r.test(t))return r}return undefined}(e,t);if(!n)return{major:0,minor:0};var r=function(e){return Number(t.replace(n,"$"+e))};return et(r(1),r(2))},Ze=function(){return et(0,0)},et=function(e,t){return{major:e,minor:t}},tt={nu:et,detect:function(e,t){var n=String(t).toLowerCase();return 0===e.length?Ze():Qe(e,n)},unknown:Ze},nt="Firefox",rt=function(e,t){return function(){return t===e}},ot=function(e){var t=e.current;return{current:t,version:e.version,isEdge:rt("Edge",t),isChrome:rt("Chrome",t),isIE:rt("IE",t),isOpera:rt("Opera",t),isFirefox:rt(nt,t),isSafari:rt("Safari",t)}},it={unknown:function(){return ot({current:undefined,version:tt.unknown()})},nu:ot,edge:S("Edge"),chrome:S("Chrome"),ie:S("IE"),opera:S("Opera"),firefox:S(nt),safari:S("Safari")},ut="Windows",ct="Android",at="Solaris",lt="FreeBSD",ft=function(e,t){return function(){return t===e}},st=function(e){var t=e.current;return{current:t,version:e.version,isWindows:ft(ut,t),isiOS:ft("iOS",t),isAndroid:ft(ct,t),isOSX:ft("OSX",t),isLinux:ft("Linux",t),isSolaris:ft(at,t),isFreeBSD:ft(lt,t)}},dt={unknown:function(){return st({current:undefined,version:tt.unknown()})},nu:st,windows:S(ut),ios:S("iOS"),android:S(ct),linux:S("Linux"),osx:S("OSX"),solaris:S(at),freebsd:S(lt)},mt=function(e,t){var n=String(t).toLowerCase();return z(e,function(e){return e.search(n)})},gt=function(e,n){return mt(e,n).map(function(e){var t=tt.detect(e.versionRegexes,n);return{current:e.name,version:t}})},pt=function(e,n){return mt(e,n).map(function(e){var t=tt.detect(e.versionRegexes,n);return{current:e.name,version:t}})},ht=/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,vt=function(t){return function(e){return Ae(e,t)}},bt=[{name:"Edge",versionRegexes:[/.*?edge\/ ?([0-9]+)\.([0-9]+)$/],search:function(e){return Ae(e,"edge/")&&Ae(e,"chrome")&&Ae(e,"safari")&&Ae(e,"applewebkit")}},{name:"Chrome",versionRegexes:[/.*?chrome\/([0-9]+)\.([0-9]+).*/,ht],search:function(e){return Ae(e,"chrome")&&!Ae(e,"chromeframe")}},{name:"IE",versionRegexes:[/.*?msie\ ?([0-9]+)\.([0-9]+).*/,/.*?rv:([0-9]+)\.([0-9]+).*/],search:function(e){return Ae(e,"msie")||Ae(e,"trident")}},{name:"Opera",versionRegexes:[ht,/.*?opera\/([0-9]+)\.([0-9]+).*/],search:vt("opera")},{name:"Firefox",versionRegexes:[/.*?firefox\/\ ?([0-9]+)\.([0-9]+).*/],search:vt("firefox")},{name:"Safari",versionRegexes:[ht,/.*?cpu os ([0-9]+)_([0-9]+).*/],search:function(e){return(Ae(e,"safari")||Ae(e,"mobile/"))&&Ae(e,"applewebkit")}}],wt=[{name:"Windows",search:vt("win"),versionRegexes:[/.*?windows\ nt\ ?([0-9]+)\.([0-9]+).*/]},{name:"iOS",search:function(e){return Ae(e,"iphone")||Ae(e,"ipad")},versionRegexes:[/.*?version\/\ ?([0-9]+)\.([0-9]+).*/,/.*cpu os ([0-9]+)_([0-9]+).*/,/.*cpu iphone os ([0-9]+)_([0-9]+).*/]},{name:"Android",search:vt("android"),versionRegexes:[/.*?android\ ?([0-9]+)\.([0-9]+).*/]},{name:"OSX",search:vt("os x"),versionRegexes:[/.*?os\ x\ ?([0-9]+)_([0-9]+).*/]},{name:"Linux",search:vt("linux"),versionRegexes:[]},{name:"Solaris",search:vt("sunos"),versionRegexes:[]},{name:"FreeBSD",search:vt("freebsd"),versionRegexes:[]}],yt={browsers:S(bt),oses:S(wt)},Ct=function(e){var t,n,r,o,i,u,c,a,l,f,s,d=yt.browsers(),m=yt.oses(),g=gt(d,e).fold(it.unknown,it.nu),p=pt(m,e).fold(dt.unknown,dt.nu);return{browser:g,os:p,deviceType:(n=g,r=e,o=(t=p).isiOS()&&!0===/ipad/i.test(r),i=t.isiOS()&&!o,u=t.isAndroid()&&3===t.version.major,c=t.isAndroid()&&4===t.version.major,a=o||u||c&&!0===/mobile/i.test(r),l=t.isiOS()||t.isAndroid(),f=l&&!a,s=n.isSafari()&&t.isiOS()&&!1===/safari/i.test(r),{isiPad:S(o),isiPhone:S(i),isTablet:S(a),isPhone:S(f),isTouch:S(l),isAndroid:t.isAndroid,isiOS:t.isiOS,isWebView:S(s)})}},St={detect:ke(function(){var e=m.navigator.userAgent;return Ct(e)})},xt=se,Rt=fe,Tt=function(e,t){var n=e.dom();if(n.nodeType!==xt)return!1;if(n.matches!==undefined)return n.matches(t);if(n.msMatchesSelector!==undefined)return n.msMatchesSelector(t);if(n.webkitMatchesSelector!==undefined)return n.webkitMatchesSelector(t);if(n.mozMatchesSelector!==undefined)return n.mozMatchesSelector(t);throw new Error("Browser lacks native selectors")},Ot=function(e){return e.nodeType!==xt&&e.nodeType!==Rt||0===e.childElementCount},Dt=function(e,t){return e.dom()===t.dom()},At=St.detect().browser.isIE()?function(e,t){return Je(e.dom(),t.dom())}:function(e,t){var n=e.dom(),r=t.dom();return n!==r&&n.contains(r)},Et=Tt,Nt=function(e){return Pe.fromDom(e.dom().ownerDocument)},kt=function(e){var t=e.dom();return x.from(t.parentNode).map(Pe.fromDom)},It=function(e,t){for(var n=A(t)?t:S(!1),r=e.dom(),o=[];null!==r.parentNode&&r.parentNode!==undefined;){var i=r.parentNode,u=Pe.fromDom(i);if(o.push(u),!0===n(u))break;r=i}return o},Pt=function(e){var t=e.dom();return x.from(t.previousSibling).map(Pe.fromDom)},Bt=function(e){var t=e.dom();return x.from(t.nextSibling).map(Pe.fromDom)},Mt=function(e){var t=e.dom();return B(t.childNodes,Pe.fromDom)},Wt=function(e,t){var n=e.dom().childNodes;return x.from(n[t]).map(Pe.fromDom)},_t=(ne("element","offset"),function(t,n){kt(t).each(function(e){e.dom().insertBefore(n.dom(),t.dom())})}),Lt=function(e,t){Bt(e).fold(function(){kt(e).each(function(e){zt(e,t)})},function(e){_t(e,t)})},jt=function(t,n){Wt(t,0).fold(function(){zt(t,n)},function(e){t.dom().insertBefore(n.dom(),e.dom())})},zt=function(e,t){e.dom().appendChild(t.dom())},Ht=function(e,t){_t(e,t),zt(t,e)},Ft=function(r,o){M(o,function(e,t){var n=0===t?r:o[t-1];Lt(n,e)})},Ut=function(t,e){M(e,function(e){zt(t,e)})},qt=function(e){e.dom().textContent="",M(Mt(e),function(e){Vt(e)})},Vt=function(e){var t=e.dom();null!==t.parentNode&&t.parentNode.removeChild(t)},Gt=function(e){var t,n=Mt(e);0<n.length&&(t=e,M(n,function(e){_t(t,e)})),Vt(e)},Yt=(ne("width","height"),ne("width","height"),ne("rows","columns")),Kt=ne("row","column"),Xt=(ne("x","y"),ne("element","rowspan","colspan")),$t=ne("element","rowspan","colspan","isNew"),Jt=ne("element","rowspan","colspan","row","column"),Qt=ne("element","cells","section"),Zt=ne("element","isNew"),en=ne("element","cells","section","isNew"),tn=ne("cells","section"),nn=ne("details","section"),rn=ne("startRow","startCol","finishRow","finishCol"),on=function(e,t){var n=[];return M(Mt(e),function(e){t(e)&&(n=n.concat([e])),n=n.concat(on(e,t))}),n},un=function(e,t,n){return r=function(e){return Tt(e,t)},_(It(e,n),r);var r},cn=function(e,t){return n=function(e){return Tt(e,t)},_(Mt(e),n);var n},an=function(e,t){return n=t,o=(r=e)===undefined?m.document:r.dom(),Ot(o)?[]:B(o.querySelectorAll(n),Pe.fromDom);var n,r,o};function ln(e,t,n,r,o){return e(n,r)?x.some(n):A(o)&&o(n)?x.none():t(n,r,o)}var fn=function(e,t,n){for(var r=e.dom(),o=A(n)?n:S(!1);r.parentNode;){r=r.parentNode;var i=Pe.fromDom(r);if(t(i))return x.some(i);if(o(i))break}return x.none()},sn=function(e,t,n){return fn(e,function(e){return Tt(e,t)},n)},dn=function(e,t){return n=function(e){return Tt(e,t)},z(e.dom().childNodes,C(n,Pe.fromDom)).map(Pe.fromDom);var n},mn=function(e,t){return n=t,o=(r=e)===undefined?m.document:r.dom(),Ot(o)?x.none():x.from(o.querySelector(n)).map(Pe.fromDom);var n,r,o},gn=function(e,t,n){return ln(Tt,sn,e,t,n)},pn=function(e,t,n){return V(Mt(e),function(e){return Tt(e,t)?n(e)?[e]:[]:pn(e,t,n)})},hn={firstLayer:function(e,t){return pn(e,t,S(!0))},filterFirstLayer:pn},vn=function(e,t,n){if(void 0===n&&(n=f),n(t))return x.none();if(I(e,me(t)))return x.some(t);return sn(t,e.join(","),function(e){return Tt(e,"table")||n(e)})},bn=function(t,e){return kt(e).map(function(e){return cn(e,t)})},wn=b(bn,"th,td"),yn=b(bn,"tr"),Cn=function(e,t){return parseInt(xe(e,t),10)},Sn={cell:function(e,t){return vn(["td","th"],e,t)},firstCell:function(e){return mn(e,"th,td")},cells:function(e){return hn.firstLayer(e,"th,td")},neighbourCells:wn,table:function(e,t){return gn(e,"table",t)},row:function(e,t){return vn(["tr"],e,t)},rows:function(e){return hn.firstLayer(e,"tr")},notCell:function(e,t){return vn(["caption","tr","tbody","tfoot","thead"],e,t)},neighbourRows:yn,attr:Cn,grid:function(e,t,n){var r=Cn(e,t),o=Cn(e,n);return Yt(r,o)}},xn=function(e){var t=Sn.rows(e);return B(t,function(e){var t=e,n=kt(t).map(function(e){var t=me(e);return"tfoot"===t||"thead"===t||"tbody"===t?t:"tbody"}).getOr("tbody"),r=B(Sn.cells(e),function(e){var t=Re(e,"rowspan")?parseInt(xe(e,"rowspan"),10):1,n=Re(e,"colspan")?parseInt(xe(e,"colspan"),10):1;return Xt(e,t,n)});return Qt(t,r,n)})},Rn=function(e,n){return B(e,function(e){var t=B(Sn.cells(e),function(e){var t=Re(e,"rowspan")?parseInt(xe(e,"rowspan"),10):1,n=Re(e,"colspan")?parseInt(xe(e,"colspan"),10):1;return Xt(e,t,n)});return Qt(e,t,n.section())})},Tn=function(e,t){return e+","+t},On=function(e,t){var n=V(e.all(),function(e){return e.cells()});return _(n,t)},Dn={generate:function(e){var l={},t=[],n=e.length,f=0;M(e,function(e,c){var a=[];M(e.cells(),function(e){for(var t=0;l[Tn(c,t)]!==undefined;)t++;for(var n=Jt(e.element(),e.rowspan(),e.colspan(),c,t),r=0;r<e.colspan();r++)for(var o=0;o<e.rowspan();o++){var i=t+r,u=Tn(c+o,i);l[u]=n,f=Math.max(f,i+1)}a.push(n)}),t.push(Qt(e.element(),a,e.section()))});var r=Yt(n,f);return{grid:S(r),access:S(l),all:S(t)}},getAt:function(e,t,n){var r=e.access()[Tn(t,n)];return r!==undefined?x.some(r):x.none()},findItem:function(e,t,n){var r=On(e,function(e){return n(t,e.element())});return 0<r.length?x.some(r[0]):x.none()},filterItems:On,justCells:function(e){var t=B(e.all(),function(e){return e.cells()});return q(t)}},An=ne("minRow","minCol","maxRow","maxCol"),En=function(e,t){var n,i,r,u,c,a,l,o,f,s,d=function(e){return Tt(e.element(),t)},m=xn(e),g=Dn.generate(m),p=(i=d,r=(n=g).grid().columns(),u=n.grid().rows(),c=r,l=a=0,J(n.access(),function(e){if(i(e)){var t=e.row(),n=t+e.rowspan()-1,r=e.column(),o=r+e.colspan()-1;t<u?u=t:a<n&&(a=n),r<c?c=r:l<o&&(l=o)}}),An(u,c,a,l)),h="th:not("+t+"),td:not("+t+")",v=hn.filterFirstLayer(e,"th,td",function(e){return Tt(e,h)});return M(v,Vt),function(e,t,n,r){for(var o,i,u,c=t.grid().columns(),a=t.grid().rows(),l=0;l<a;l++)for(var f=!1,s=0;s<c;s++)l<n.minRow()||l>n.maxRow()||s<n.minCol()||s>n.maxCol()||(Dn.getAt(t,l,s).filter(r).isNone()?(o=f,i=e[l].element(),u=Pe.fromTag("td"),zt(u,Pe.fromTag("br")),(o?zt:jt)(i,u)):f=!0)}(m,g,p,d),o=e,f=p,s=_(hn.firstLayer(o,"tr"),function(e){return 0===e.dom().childElementCount}),M(s,Vt),f.minCol()!==f.maxCol()&&f.minRow()!==f.maxRow()||M(hn.firstLayer(o,"th,td"),function(e){Te(e,"rowspan"),Te(e,"colspan")}),Te(o,"width"),Te(o,"height"),qe(o,"width"),qe(o,"height"),e};var Nn=function ls(n,r){var o=function(e){return n(e)?x.from(e.dom().nodeValue):x.none()},e=St.detect().browser,t=e.isIE()&&10===e.version.major?function(e){try{return o(e)}catch(t){return x.none()}}:o;return{get:function(e){if(!n(e))throw new Error("Can only get "+r+" value of a "+r+" node");return t(e).getOr("")},getOption:t,set:function(e,t){if(!n(e))throw new Error("Can only set raw "+r+" value of a "+r+" node");e.dom().nodeValue=t}}}(be,"text"),kn=function(e){return Nn.get(e)},In=function(e){return Nn.getOption(e)},Pn=function(e,t){Nn.set(e,t)},Bn=function(e){return"img"===me(e)?1:In(e).fold(function(){return Mt(e).length},function(e){return e.length})},Mn=["img","br"],Wn=function(e){return In(e).filter(function(e){return 0!==e.trim().length||-1<e.indexOf("\xa0")}).isSome()||I(Mn,me(e))},_n=function(e){return r=Wn,(o=function(e){for(var t=0;t<e.childNodes.length;t++){if(r(Pe.fromDom(e.childNodes[t])))return x.some(Pe.fromDom(e.childNodes[t]));var n=o(e.childNodes[t]);if(n.isSome())return n}return x.none()})(e.dom());var r,o},Ln=function(e){return jn(e,Wn)},jn=function(e,i){var u=function(e){for(var t=Mt(e),n=t.length-1;0<=n;n--){var r=t[n];if(i(r))return x.some(r);var o=u(r);if(o.isSome())return o}return x.none()};return u(e)},zn=function(e,t){return Pe.fromDom(e.dom().cloneNode(t))},Hn=function(e){return zn(e,!1)},Fn=function(e){return zn(e,!0)},Un=function(e,t){var n,r,o,i,u=(n=e,r=t,o=Pe.fromTag(r),i=Oe(n),Se(o,i),o),c=Mt(Fn(e));return Ut(u,c),u},qn=function(){var e=Pe.fromTag("td");return zt(e,Pe.fromTag("br")),e},Vn=function(e,t,n){var r=Un(e,t);return J(n,function(e,t){null===e?Te(r,t):Ce(r,t,e)}),r},Gn=function(e){return e},Yn=function(e){return function(){return Pe.fromTag("tr",e.dom())}},Kn=function(a,e,l){return{row:Yn(e),cell:function(e){var r,o,i,t=Nt(e.element()),n=Pe.fromTag(me(e.element()),t.dom()),u=l.getOr(["strong","em","b","i","span","font","h1","h2","h3","h4","h5","h6","p","div"]),c=0<u.length?(r=e.element(),o=n,i=u,_n(r).map(function(e){var t=i.join(","),n=un(e,t,function(e){return Dt(e,r)});return L(n,function(e,t){var n=Hn(t);return Te(n,"contenteditable"),zt(e,n),n},o)}).getOr(o)):n;return zt(c,Pe.fromTag("br")),Ve(e.element(),n),qe(n,"height"),1!==e.colspan()&&qe(e.element(),"width"),a(e.element(),n),n},replace:Vn,gap:qn}},Xn=function(e){return{row:Yn(e),cell:qn,replace:Gn,gap:qn}},$n=function(e,t){return t.column()>=e.startCol()&&t.column()+t.colspan()-1<=e.finishCol()&&t.row()>=e.startRow()&&t.row()+t.rowspan()-1<=e.finishRow()},Jn=function(e,t){var n=t.column(),r=t.column()+t.colspan()-1,o=t.row(),i=t.row()+t.rowspan()-1;return n<=e.finishCol()&&r>=e.startCol()&&o<=e.finishRow()&&i>=e.startRow()},Qn=function(e,t){for(var n=!0,r=b($n,t),o=t.startRow();o<=t.finishRow();o++)for(var i=t.startCol();i<=t.finishCol();i++)n=n&&Dn.getAt(e,o,i).exists(r);return n?x.some(t):x.none()},Zn=function(e,t,n){var r=Dn.findItem(e,t,Dt),o=Dn.findItem(e,n,Dt);return r.bind(function(r){return o.map(function(e){return t=r,n=e,rn(Math.min(t.row(),n.row()),Math.min(t.column(),n.column()),Math.max(t.row()+t.rowspan()-1,n.row()+n.rowspan()-1),Math.max(t.column()+t.colspan()-1,n.column()+n.colspan()-1));var t,n})})},er=Zn,tr=function(t,e,n){return Zn(t,e,n).bind(function(e){return Qn(t,e)})},nr=function(r,e,o,i){return Dn.findItem(r,e,Dt).bind(function(e){var t=0<o?e.row()+e.rowspan()-1:e.row(),n=0<i?e.column()+e.colspan()-1:e.column();return Dn.getAt(r,t+o,n+i).map(function(e){return e.element()})})},rr=function(n,e,t){return er(n,e,t).map(function(e){var t=Dn.filterItems(n,b(Jn,e));return B(t,function(e){return e.element()})})},or=function(e,t){return Dn.findItem(e,t,function(e,t){return At(t,e)}).map(function(e){return e.element()})},ir=function(e){var t=xn(e);return Dn.generate(t)},ur=function(n,r,o){return Sn.table(n).bind(function(e){var t=ir(e);return nr(t,n,r,o)})},cr=function(e,t,n){var r=ir(e);return rr(r,t,n)},ar=function(e,t,n,r,o){var i=ir(e),u=Dt(e,n)?x.some(t):or(i,t),c=Dt(e,o)?x.some(r):or(i,r);return u.bind(function(t){return c.bind(function(e){return rr(i,t,e)})})},lr=function(e,t,n){var r=ir(e);return tr(r,t,n)},fr=["body","p","div","article","aside","figcaption","figure","footer","header","nav","section","ol","ul","li","table","thead","tbody","tfoot","caption","tr","td","th","h1","h2","h3","h4","h5","h6","blockquote","pre","address"];function sr(){return{up:S({selector:sn,closest:gn,predicate:fn,all:It}),down:S({selector:an,predicate:on}),styles:S({get:He,getRaw:Ue,set:je,remove:qe}),attrs:S({get:xe,set:Ce,remove:Te,copyTo:function(e,t){var n=Oe(e);Se(t,n)}}),insert:S({before:_t,after:Lt,afterAll:Ft,append:zt,appendAll:Ut,prepend:jt,wrap:Ht}),remove:S({unwrap:Gt,remove:Vt}),create:S({nu:Pe.fromTag,clone:function(e){return Pe.fromDom(e.dom().cloneNode(!1))},text:Pe.fromText}),query:S({comparePosition:function(e,t){return e.dom().compareDocumentPosition(t.dom())},prevSibling:Pt,nextSibling:Bt}),property:S({children:Mt,name:me,parent:kt,document:function(e){return e.dom().ownerDocument},isText:be,isComment:he,isElement:ve,getText:kn,setText:Pn,isBoundary:function(e){return!!ve(e)&&("body"===me(e)||I(fr,me(e)))},isEmptyTag:function(e){return!!ve(e)&&I(["br","img","hr","input"],me(e))}}),eq:Dt,is:Et}}var dr=ne("left","right"),mr=ne("first","second","splits"),gr=function(e,t,n){var r=e.property().children(t);return H(r,b(e.eq,n)).map(function(e){return{before:S(r.slice(0,e)),after:S(r.slice(e+1))}})},pr=function(r,o,e,t){var n=o(r,e);return L(t,function(e,t){var n=o(r,t);return hr(r,e,n)},n)},hr=function(t,e,n){return e.bind(function(e){return n.filter(b(t.eq,e))})},vr=function(e,t){return b(e.eq,t)},br=function(t,e,n,r){void 0===r&&(r=f);var o=[e].concat(t.up().all(e)),i=[n].concat(t.up().all(n)),u=function(t){return H(t,r).fold(function(){return t},function(e){return t.slice(0,e+1)})},c=u(o),a=u(i),l=z(c,function(e){return P(a,vr(t,e))});return{firstpath:S(c),secondpath:S(a),shared:S(l)}},wr={sharedOne:function(e,t,n){return 0<n.length?pr(e,t,(r=n)[0],r.slice(1)):x.none();var r},subset:function(t,e,n){var r=br(t,e,n);return r.shared().bind(function(e){return function(o,i,e,t){var u=o.property().children(i);if(o.eq(i,e[0]))return x.some([e[0]]);if(o.eq(i,t[0]))return x.some([t[0]]);var n=function(e){var t=Y(e),n=H(t,vr(o,i)).getOr(-1),r=n<t.length-1?t[n+1]:t[n];return H(u,vr(o,r))},r=n(e),c=n(t);return r.bind(function(r){return c.map(function(e){var t=Math.min(r,e),n=Math.max(r,e);return u.slice(t,n+1)})})}(t,e,r.firstpath(),r.secondpath())})},ancestors:br,breakToLeft:function(n,r,o){return gr(n,r,o).map(function(e){var t=n.create().clone(r);return n.insert().appendAll(t,e.before().concat([o])),n.insert().appendAll(r,e.after()),n.insert().before(r,t),dr(t,r)})},breakToRight:function(n,r,e){return gr(n,r,e).map(function(e){var t=n.create().clone(r);return n.insert().appendAll(t,e.after()),n.insert().after(r,t),dr(r,t)})},breakPath:function(i,e,u,c){var a=function(e,t,o){var n=mr(e,x.none(),o);return u(e)?mr(e,t,o):i.property().parent(e).bind(function(r){return c(i,r,e).map(function(e){var t=[{first:e.left,second:e.right}],n=u(r)?r:e.left();return a(n,x.some(e.right()),o.concat(t))})}).getOr(n)};return a(e,x.none(),[])}},yr=sr(),Cr={sharedOne:function(n,e){return wr.sharedOne(yr,function(e,t){return n(t)},e)},subset:function(e,t){return wr.subset(yr,e,t)},ancestors:function(e,t,n){return wr.ancestors(yr,e,t,n)},breakToLeft:function(e,t){return wr.breakToLeft(yr,e,t)},breakToRight:function(e,t){return wr.breakToRight(yr,e,t)},breakPath:function(e,t,r){return wr.breakPath(yr,e,t,function(e,t,n){return r(t,n)})}},Sr={create:ae(["boxes","start","finish"],[])},xr=function(e){return sn(e,"table")},Rr=function(c,a,r){var l=function(t){return function(e){return r!==undefined&&r(e)||Dt(e,t)}};return Dt(c,a)?x.some(Sr.create({boxes:x.some([c]),start:c,finish:a})):xr(c).bind(function(u){return xr(a).bind(function(i){if(Dt(u,i))return x.some(Sr.create({boxes:cr(u,c,a),start:c,finish:a}));if(At(u,i)){var e=0<(t=un(a,"td,th",l(u))).length?t[t.length-1]:a;return x.some(Sr.create({boxes:ar(u,c,u,a,i),start:c,finish:e}))}if(At(i,u)){var t,n=0<(t=un(c,"td,th",l(i))).length?t[t.length-1]:c;return x.some(Sr.create({boxes:ar(i,c,u,a,i),start:c,finish:n}))}return Cr.ancestors(c,a).shared().bind(function(e){return gn(e,"table",r).bind(function(e){var t=un(a,"td,th",l(e)),n=0<t.length?t[t.length-1]:a,r=un(c,"td,th",l(e)),o=0<r.length?r[r.length-1]:c;return x.some(Sr.create({boxes:ar(e,c,u,a,i),start:o,finish:n}))})})})})},Tr=Rr,Or=function(e,t){var n=an(e,t);return 0<n.length?x.some(n):x.none()},Dr=function(e,t,n,r,o){return(i=e,u=o,z(i,function(e){return Tt(e,u)})).bind(function(e){return ur(e,t,n).bind(function(e){return n=r,sn(t=e,"table").bind(function(e){return mn(e,n).bind(function(e){return Rr(e,t).bind(function(t){return t.boxes().map(function(e){return{boxes:S(e),start:S(t.start()),finish:S(t.finish())}})})})});var t,n})});var i,u},Ar=function(e,t,r){return mn(e,t).bind(function(n){return mn(e,r).bind(function(t){return Cr.sharedOne(xr,[n,t]).map(function(e){return{first:S(n),last:S(t),table:S(e)}})})})},Er=function(e,t){return Or(e,t)},Nr=function(o,e,t){return Ar(o,e,t).bind(function(n){var e=function(e){return Dt(o,e)},t=sn(n.first(),"thead,tfoot,tbody,table",e),r=sn(n.last(),"thead,tfoot,tbody,table",e);return t.bind(function(t){return r.bind(function(e){return Dt(t,e)?lr(n.table(),n.first(),n.last()):x.none()})})})},kr="data-mce-selected",Ir="data-mce-first-selected",Pr="data-mce-last-selected",Br={selected:S(kr),selectedSelector:S("td[data-mce-selected],th[data-mce-selected]"),attributeSelector:S("[data-mce-selected]"),firstSelected:S(Ir),firstSelectedSelector:S("td[data-mce-first-selected],th[data-mce-first-selected]"),lastSelected:S(Pr),lastSelectedSelector:S("td[data-mce-last-selected],th[data-mce-last-selected]")},Mr=function(u){if(!O(u))throw new Error("cases must be an array");if(0===u.length)throw new Error("there must be at least one case");var c=[],n={};return M(u,function(e,r){var t=X(e);if(1!==t.length)throw new Error("one and only one name per case");var o=t[0],i=e[o];if(n[o]!==undefined)throw new Error("duplicate key detected:"+o);if("cata"===o)throw new Error("cannot have a case named cata (sorry)");if(!O(i))throw new Error("case arguments must be an array");c.push(o),n[o]=function(){var e=arguments.length;if(e!==i.length)throw new Error("Wrong number of arguments to case "+o+". Expected "+i.length+" ("+i+"), got "+e);for(var n=new Array(e),t=0;t<n.length;t++)n[t]=arguments[t];return{fold:function(){if(arguments.length!==u.length)throw new Error("Wrong number of arguments to fold. Expected "+u.length+", got "+arguments.length);return arguments[r].apply(null,n)},match:function(e){var t=X(e);if(c.length!==t.length)throw new Error("Wrong number of arguments to match. Expected: "+c.join(",")+"\nActual: "+t.join(","));if(!G(c,function(e){return I(t,e)}))throw new Error("Not all branches were specified when using match. Specified: "+t.join(", ")+"\nRequired: "+c.join(", "));return e[o].apply(null,n)},log:function(e){m.console.log(e,{constructors:c,constructor:o,params:n})}}}}),n},Wr=Mr([{none:[]},{multiple:["elements"]},{single:["selection"]}]),_r={cata:function(e,t,n,r){return e.fold(t,n,r)},none:Wr.none,multiple:Wr.multiple,single:Wr.single},Lr=function(e,t){return _r.cata(t.get(),S([]),o,S([e]))},jr=function(n,e){return _r.cata(e.get(),x.none,function(t,e){return 0===t.length?x.none():Nr(n,Br.firstSelectedSelector(),Br.lastSelectedSelector()).bind(function(e){return 1<t.length?x.some({bounds:S(e),cells:S(t)}):x.none()})},x.none)},zr=function(e,t){var n=Lr(e,t);return 0<n.length&&G(n,function(e){return Re(e,"rowspan")&&1<parseInt(xe(e,"rowspan"),10)||Re(e,"colspan")&&1<parseInt(xe(e,"colspan"),10)})?x.some(n):x.none()},Hr=Lr,Fr=function(e){return{element:S(e),mergable:x.none,unmergable:x.none,selection:S([e])}},Ur=ne("element","clipboard","generators"),qr={noMenu:Fr,forMenu:function(e,t,n){return{element:S(n),mergable:S(jr(t,e)),unmergable:S(zr(n,e)),selection:S(Hr(n,e))}},notCell:function(e){return Fr(e)},paste:Ur,pasteRows:function(e,t,n,r,o){return{element:S(n),mergable:x.none,unmergable:x.none,selection:S(Hr(n,e)),clipboard:S(r),generators:S(o)}}},Vr={registerEvents:function(f,e,s,d){f.on("BeforeGetContent",function(n){!0===n.selection&&_r.cata(e.get(),y,function(e){var t;n.preventDefault(),(t=e,Sn.table(t[0]).map(Fn).map(function(e){return[En(e,Br.attributeSelector())]})).each(function(e){var t;n.content="text"===n.format?B(e,function(e){return e.dom().innerText}).join(""):(t=f,B(e,function(e){return t.selection.serializer.serialize(e.dom(),{})}).join(""))})},y)}),f.on("BeforeSetContent",function(l){!0===l.selection&&!0===l.paste&&x.from(f.dom.getParent(f.selection.getStart(),"th,td")).each(function(e){var a=Pe.fromDom(e);Sn.table(a).each(function(t){var e,n,r,o=_((e=l.content,(r=(n||m.document).createElement("div")).innerHTML=e,Mt(Pe.fromDom(r))),function(e){return"meta"!==me(e)});if(1===o.length&&"table"===me(o[0])){l.preventDefault();var i=Pe.fromDom(f.getDoc()),u=Xn(i),c=qr.paste(a,o[0],u);s.pasteCells(t,c).each(function(e){f.selection.setRng(e),f.focus(),d.clear(t)})}})})})}};function Gr(r,o){var e=function(e){var t=o(e);if(t<=0||null===t){var n=He(e,r);return parseFloat(n)||0}return t},i=function(o,e){return j(e,function(e,t){var n=He(o,t),r=n===undefined?0:parseInt(n,10);return isNaN(r)?e:e+r},0)};return{set:function(e,t){if(!E(t)&&!t.match(/^[0-9]+$/))throw new Error(r+".set accepts only positive integer values. Value was "+t);var n=e.dom();Ne(n)&&(n.style[r]=t+"px")},get:e,getOuter:e,aggregate:i,max:function(e,t,n){var r=i(e,n);return r<t?t-r:0}}}var Yr=Gr("height",function(e){var t=e.dom();return Be(e)?t.getBoundingClientRect().height:t.offsetHeight}),Kr=function(e){return Yr.get(e)},Xr=function(e){return Yr.getOuter(e)},$r=Gr("width",function(e){return e.dom().offsetWidth}),Jr=function(e){return $r.get(e)},Qr=function(e){return $r.getOuter(e)},Zr=St.detect(),eo=function(e,t,n){return r=He(e,t),o=n,i=parseFloat(r),isNaN(i)?o:i;var r,o,i},to=function(e){return Zr.browser.isIE()||Zr.browser.isEdge()?(n=eo(t=e,"padding-top",0),r=eo(t,"padding-bottom",0),o=eo(t,"border-top-width",0),i=eo(t,"border-bottom-width",0),u=t.dom().getBoundingClientRect().height,"border-box"===He(t,"box-sizing")?u:u-n-r-(o+i)):eo(e,"height",Kr(e));var t,n,r,o,i,u},no=/(\d+(\.\d+)?)(\w|%)*/,ro=/(\d+(\.\d+)?)%/,oo=/(\d+(\.\d+)?)px|em/,io=function(e,t){je(e,"height",t+"px")},uo=function(e,t,n,r){var o,i,u,c,a,l,f,s=parseInt(e,10);return De(l=e,f="%",l.length-f.length)&&"table"!==me(t)?(o=t,i=s,u=n,c=r,a=Sn.table(o).map(function(e){var t=u(e);return Math.floor(i/100*t)}).getOr(i),c(o,a),a):s},co=function(e){var t,n=Ue(t=e,"height").getOrThunk(function(){return to(t)+"px"});return n?uo(n,e,Kr,io):Kr(e)},ao=function(e,t){return Re(e,t)?parseInt(xe(e,t),10):1},lo=function(e){return Ue(e,"width").fold(function(){return x.from(xe(e,"width"))},function(e){return x.some(e)})},fo=function(e,t){return e/t.pixelWidth()*100},so={percentageBasedSizeRegex:S(ro),pixelBasedSizeRegex:S(oo),setPixelWidth:function(e,t){je(e,"width",t+"px")},setPercentageWidth:function(e,t){je(e,"width",t+"%")},setHeight:io,getPixelWidth:function(t,n){return lo(t).fold(function(){return Jr(t)},function(e){return function(e,t,n){var r=oo.exec(t);if(null!==r)return parseInt(r[1],10);var o=ro.exec(t);if(null===o)return Jr(e);var i=parseFloat(o[1]);return i/100*n.pixelWidth()}(t,e,n)})},getPercentageWidth:function(t,n){return lo(t).fold(function(){var e=Jr(t);return fo(e,n)},function(e){return function(e,t,n){var r=ro.exec(t);if(null!==r)return parseFloat(r[1]);var o=Jr(e);return fo(o,n)}(t,e,n)})},getGenericWidth:function(e){return lo(e).bind(function(e){var t=no.exec(e);return null!==t?x.some({width:S(parseFloat(t[1])),unit:S(t[3])}):x.none()})},setGenericWidth:function(e,t,n){je(e,"width",t+n)},getHeight:function(e){return n="rowspan",co(t=e)/ao(t,n);var t,n},getRawWidth:lo},mo=function(n,r){so.getGenericWidth(n).each(function(e){var t=e.width()/2;so.setGenericWidth(n,t,e.unit()),so.setGenericWidth(r,t,e.unit())})},go=function(n,r){return{left:S(n),top:S(r),translate:function(e,t){return go(n+e,r+t)}}},po=go,ho=function(e,t){return e!==undefined?e:t!==undefined?t:0},vo=function(e){var t,n,r=e.dom().ownerDocument,o=r.body,i=(t=Pe.fromDom(r),(n=t.dom())===n.window&&t instanceof m.Window?t:we(t)?n.defaultView||n.parentWindow:null),u=r.documentElement,c=ho(i.pageYOffset,u.scrollTop),a=ho(i.pageXOffset,u.scrollLeft),l=ho(u.clientTop,o.clientTop),f=ho(u.clientLeft,o.clientLeft);return bo(e).translate(a-f,c-l)},bo=function(e){var t,n,r,o=e.dom(),i=o.ownerDocument,u=i.body,c=Pe.fromDom(i.documentElement);return u===o?po(u.offsetLeft,u.offsetTop):(t=e,n=c||Pe.fromDom(m.document.documentElement),fn(t,b(Dt,n)).isSome()?(r=o.getBoundingClientRect(),po(r.left,r.top)):po(0,0))},wo=ne("row","y"),yo=ne("col","x"),Co=function(e){return vo(e).left()+Qr(e)},So=function(e){return vo(e).left()},xo=function(e,t){return yo(e,So(t))},Ro=function(e,t){return yo(e,Co(t))},To=function(e){return vo(e).top()},Oo=function(e,t){return wo(e,To(t))},Do=function(e,t){return wo(e,To(t)+Xr(t))},Ao=function(n,t,r){if(0===r.length)return[];var e=B(r.slice(1),function(e,t){return e.map(function(e){return n(t,e)})}),o=r[r.length-1].map(function(e){return t(r.length-1,e)});return e.concat([o])},Eo={height:{delta:o,positions:function(e){return Ao(Oo,Do,e)},edge:To},rtl:{delta:function(e){return-e},edge:Co,positions:function(e){return Ao(Ro,xo,e)}},ltr:{delta:o,edge:So,positions:function(e){return Ao(xo,Ro,e)}}},No={ltr:Eo.ltr,rtl:Eo.rtl};function ko(t){var n=function(e){return t(e).isRtl()?No.rtl:No.ltr};return{delta:function(e,t){return n(t).delta(e,t)},edge:function(e){return n(e).edge(e)},positions:function(e,t){return n(t).positions(e,t)}}}var Io,Po=function(e){var t=xn(e);return Dn.generate(t).grid()},Bo=function(){return(Bo=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e}).apply(this,arguments)},Mo=function(e){for(var t=[],n=function(e){t.push(e)},r=0;r<e.length;r++)e[r].each(n);return t},Wo=function(e,t){for(var n=0;n<e.length;n++){var r=t(e[n],n);if(r.isSome())return r}return x.none()},_o=function(e,t,n,r){n===r?Te(e,t):Ce(e,t,n)},Lo=function(o,e){var i=[],u=[],t=function(e,t){0<e.length?function(e,t){var n=dn(o,t).getOrThunk(function(){var e=Pe.fromTag(t,Nt(o).dom());return zt(o,e),e});qt(n);var r=B(e,function(e){e.isNew()&&i.push(e.element());var t=e.element();return qt(t),M(e.cells(),function(e){e.isNew()&&u.push(e.element()),_o(e.element(),"colspan",e.colspan(),1),_o(e.element(),"rowspan",e.rowspan(),1),zt(t,e.element())}),t});Ut(n,r)}(e,t):dn(o,t).each(Vt)},n=[],r=[],c=[];return M(e,function(e){switch(e.section()){case"thead":n.push(e);break;case"tbody":r.push(e);break;case"tfoot":c.push(e)}}),t(n,"thead"),t(r,"tbody"),t(c,"tfoot"),{newRows:S(i),newCells:S(u)}},jo=function(e){return B(e,function(e){var n=Hn(e.element());return M(e.cells(),function(e){var t=Fn(e.element());_o(t,"colspan",e.colspan(),1),_o(t,"rowspan",e.rowspan(),1),zt(n,t)}),n})},zo=function(e,t){var n=xe(e,t);return n===undefined||""===n?[]:n.split(" ")},Ho=function(e){return e.dom().classList!==undefined},Fo=function(e){return zo(e,"class")},Uo=function(e,t){return o=t,i=zo(n=e,r="class").concat([o]),Ce(n,r,i.join(" ")),!0;var n,r,o,i},qo=function(e,t){return o=t,0<(i=_(zo(n=e,r="class"),function(e){return e!==o})).length?Ce(n,r,i.join(" ")):Te(n,r),!1;var n,r,o,i},Vo=function(e,t){Ho(e)?e.dom().classList.add(t):Uo(e,t)},Go=function(e,t){var n;Ho(e)?e.dom().classList.remove(t):qo(e,t);0===(Ho(n=e)?n.dom().classList:Fo(n)).length&&Te(n,"class")},Yo=function(e,t){return Ho(e)&&e.dom().classList.contains(t)},Ko=function(e,t){for(var n=[],r=e;r<t;r++)n.push(r);return n},Xo=function(t,n){if(n<0||n>=t.length-1)return x.none();var e=t[n].fold(function(){var e=Y(t.slice(0,n));return Wo(e,function(e,t){return e.map(function(e){return{value:e,delta:t+1}})})},function(e){return x.some({value:e,delta:0})}),r=t[n+1].fold(function(){var e=t.slice(n+1);return Wo(e,function(e,t){return e.map(function(e){return{value:e,delta:t+1}})})},function(e){return x.some({value:e,delta:1})});return e.bind(function(n){return r.map(function(e){var t=e.delta+n.delta;return Math.abs(e.value-n.value)/t})})},$o=function(e,t,n){var r=e();return z(r,t).orThunk(function(){return x.from(r[0]).orThunk(n)}).map(function(e){return e.element()})},Jo=function(n){var e=n.grid(),t=Ko(0,e.columns()),r=Ko(0,e.rows());return B(t,function(t){return $o(function(){return V(r,function(e){return Dn.getAt(n,e,t).filter(function(e){return e.column()===t}).fold(S([]),function(e){return[e]})})},function(e){return 1===e.colspan()},function(){return Dn.getAt(n,0,t)})})},Qo=function(n){var e=n.grid(),t=Ko(0,e.rows()),r=Ko(0,e.columns());return B(t,function(t){return $o(function(){return V(r,function(e){return Dn.getAt(n,t,e).filter(function(e){return e.row()===t}).fold(S([]),function(e){return[e]})})},function(e){return 1===e.rowspan()},function(){return Dn.getAt(n,t,0)})})},Zo=function(e){var t=e.replace(/\./g,"-");return{resolve:function(e){return t+"-"+e}}},ei={resolve:Zo("ephox-snooker").resolve},ti=function(e,t,n,r,o){var i=Pe.fromTag("div");return ze(i,{position:"absolute",left:t-r/2+"px",top:n+"px",height:o+"px",width:r+"px"}),Se(i,{"data-column":e,role:"presentation"}),i},ni=function(e,t,n,r,o){var i=Pe.fromTag("div");return ze(i,{position:"absolute",left:t+"px",top:n-o/2+"px",height:o+"px",width:r+"px"}),Se(i,{"data-row":e,role:"presentation"}),i},ri=ei.resolve("resizer-bar"),oi=ei.resolve("resizer-rows"),ii=ei.resolve("resizer-cols"),ui=function(e){var t=an(e.parent(),"."+ri);M(t,Vt)},ci=function(n,e,r){var o=n.origin();M(e,function(e,t){e.each(function(e){var t=r(o,e);Vo(t,ri),zt(n.parent(),t)})})},ai=function(e,t,n,r,o,i){var u,c,a,l,f=vo(t),s=0<n.length?o.positions(n,t):[];u=e,c=s,a=f,l=Qr(t),ci(u,c,function(e,t){var n=ni(t.row(),a.left()-e.left(),t.y()-e.top(),l,7);return Vo(n,oi),n});var d,m,g,p,h=0<r.length?i.positions(r,t):[];d=e,m=h,g=f,p=Xr(t),ci(d,m,function(e,t){var n=ti(t.col(),t.x()-e.left(),g.top()-e.top(),7,p);return Vo(n,ii),n})},li=function(e,t){var n=an(e.parent(),"."+ri);M(n,t)},fi=function(e,t,n,r){ui(e);var o=xn(t),i=Dn.generate(o),u=Qo(i),c=Jo(i);ai(e,t,u,c,n,r)},si=function(e){li(e,function(e){je(e,"display","none")})},di=function(e){li(e,function(e){je(e,"display","block")})},mi=ui,gi=function(e){return Yo(e,oi)},pi=function(e){return Yo(e,ii)},hi=function(e,t){return tn(t,e.section())},vi=function(e,t){return e.cells()[t]},bi={addCell:function(e,t,n){var r=e.cells(),o=r.slice(0,t),i=r.slice(t),u=o.concat([n]).concat(i);return hi(e,u)},setCells:hi,mutateCell:function(e,t,n){e.cells()[t]=n},getCell:vi,getCellElement:function(e,t){return vi(e,t).element()},mapCells:function(e,t){var n=e.cells(),r=B(n,t);return tn(r,e.section())},cellLength:function(e){return e.cells().length}},wi=function(e,t){if(0===e.length)return 0;var n=e[0];return H(e,function(e){return!t(n.element(),e.element())}).fold(function(){return e.length},function(e){return e})},yi=function(e,t,n,r){var o,i,u,c,a=(o=e,i=t,o[i]).cells().slice(n),l=wi(a,r),f=(u=e,c=n,B(u,function(e){return bi.getCell(e,c)})).slice(t),s=wi(f,r);return{colspan:S(l),rowspan:S(s)}},Ci=function(o,i){var u=B(o,function(e,t){return B(e.cells(),function(e,t){return!1})});return B(o,function(e,r){var t=V(e.cells(),function(e,t){if(!1!==u[r][t])return[];var n=yi(o,r,t,i);return function(e,t,n,r){for(var o=e;o<e+n;o++)for(var i=t;i<t+r;i++)u[o][i]=!0}(r,t,n.rowspan(),n.colspan()),[$t(e.element(),n.rowspan(),n.colspan(),e.isNew())]});return nn(t,e.section())})},Si=function(e,t,n){for(var r=[],o=0;o<e.grid().rows();o++){for(var i=[],u=0;u<e.grid().columns();u++){var c=Dn.getAt(e,o,u).map(function(e){return Zt(e.element(),n)}).getOrThunk(function(){return Zt(t.gap(),!0)});i.push(c)}var a=tn(i,e.all()[o].section());r.push(a)}return r},xi=function(e,r){return B(e,function(e){var t,n=(t=e.details(),Wo(t,function(e){return kt(e.element()).map(function(e){var t=kt(e).isNone();return Zt(e,t)})}).getOrThunk(function(){return Zt(r.row(),!0)}));return en(n.element(),e.details(),e.section(),n.isNew())})},Ri=function(e,t){var n=Ci(e,Dt);return xi(n,t)},Ti=function(e,t){var n=q(B(e.all(),function(e){return e.cells()}));return z(n,function(e){return Dt(t,e.element())})},Oi=function(c,a,l,f,s){return function(n,r,e,o,i){var t=xn(r),u=Dn.generate(t);return a(u,e).map(function(e){var t=Si(u,o,!1),n=c(t,e,Dt,s(o)),r=Ri(n.grid(),o);return{grid:S(r),cursor:n.cursor}}).fold(function(){return x.none()},function(e){var t=Lo(r,e.grid());return l(r,e.grid(),i),f(r),fi(n,r,Eo.height,i),x.some({cursor:e.cursor,newRows:t.newRows,newCells:t.newCells})})}},Di=function(t,e){return Sn.cell(e.element()).bind(function(e){return Ti(t,e)})},Ai=function(t,e){var n=B(e.selection(),function(e){return Sn.cell(e).bind(function(e){return Ti(t,e)})}),r=Mo(n);return 0<r.length?x.some({cells:r,generators:e.generators,clipboard:e.clipboard}):x.none()},Ei=function(t,e){var n=B(e.selection(),function(e){return Sn.cell(e).bind(function(e){return Ti(t,e)})}),r=Mo(n);return 0<r.length?x.some(r):x.none()},Ni=function(n){return{is:function(e){return n===e},isValue:c,isError:f,getOr:S(n),getOrThunk:S(n),getOrDie:S(n),or:function(e){return Ni(n)},orThunk:function(e){return Ni(n)},fold:function(e,t){return t(n)},map:function(e){return Ni(e(n))},mapError:function(e){return Ni(n)},each:function(e){e(n)},bind:function(e){return e(n)},exists:function(e){return e(n)},forall:function(e){return e(n)},toOption:function(){return x.some(n)}}},ki=function(n){return{is:f,isValue:f,isError:c,getOr:o,getOrThunk:function(e){return e()},getOrDie:function(){return u(String(n))()},or:function(e){return e},orThunk:function(e){return e()},fold:function(e,t){return e(n)},map:function(e){return ki(n)},mapError:function(e){return ki(e(n))},each:y,bind:function(e){return ki(n)},exists:f,forall:c,toOption:x.none}},Ii={value:Ni,error:ki,fromOption:function(e,t){return e.fold(function(){return ki(t)},Ni)}},Pi=function(e,t){return B(e,function(){return Zt(t.cell(),!0)})},Bi=function(t,e,n){return t.concat(function(e,t){for(var n=[],r=0;r<e;r++)n.push(t(r));return n}(e,function(e){return bi.setCells(t[t.length-1],Pi(t[t.length-1].cells(),n))}))},Mi=function(e,t,n){return B(e,function(e){return bi.setCells(e,e.cells().concat(Pi(Ko(0,t),n)))})},Wi=function(e,t,n){if(e.row()>=t.length||e.column()>bi.cellLength(t[0]))return Ii.error("invalid start address out of table bounds, row: "+e.row()+", column: "+e.column());var r=t.slice(e.row()),o=r[0].cells().slice(e.column()),i=bi.cellLength(n[0]),u=n.length;return Ii.value({rowDelta:S(r.length-u),colDelta:S(o.length-i)})},_i=function(e,t){var n=bi.cellLength(e[0]),r=bi.cellLength(t[0]);return{rowDelta:S(0),colDelta:S(n-r)}},Li=function(e,t,n){var r=t.colDelta()<0?Mi:o;return(t.rowDelta()<0?Bi:o)(r(e,Math.abs(t.colDelta()),n),Math.abs(t.rowDelta()),n)},ji=function(e,t,n,r){if(0===e.length)return e;for(var o=t.startRow();o<=t.finishRow();o++)for(var i=t.startCol();i<=t.finishCol();i++)bi.mutateCell(e[o],i,Zt(r(),!1));return e},zi=function(e,t,n,r){for(var o=!0,i=0;i<e.length;i++)for(var u=0;u<bi.cellLength(e[0]);u++){var c=n(bi.getCellElement(e[i],u),t);!0===c&&!1===o?bi.mutateCell(e[i],u,Zt(r(),!0)):!0===c&&(o=!1)}return e},Hi=function(i,n,u,c){if(0<n&&n<i.length){var e=i[n-1].cells(),t=(r=u,j(e,function(e,t){return P(e,function(e){return r(e.element(),t.element())})?e:e.concat([t])},[]));M(t,function(r){for(var o=x.none(),e=function(n){for(var e=function(t){var e=i[n].cells()[t];u(e.element(),r.element())&&(o.isNone()&&(o=x.some(c())),o.each(function(e){bi.mutateCell(i[n],t,Zt(e,!0))}))},t=0;t<bi.cellLength(i[0]);t++)e(t)},t=n;t<i.length;t++)e(t)})}var r;return i},Fi=function(n,r,o,i,u){return Wi(n,r,o).map(function(e){var t=Li(r,e,i);return function(e,t,n,r,o){for(var i,u,c,a,l,f=e.row(),s=e.column(),d=f+n.length,m=s+bi.cellLength(n[0]),g=f;g<d;g++)for(var p=s;p<m;p++){i=t,u=g,c=p,l=a=void 0,a=b(o,bi.getCell(i[u],c).element()),l=i[u],1<i.length&&1<bi.cellLength(l)&&(0<c&&a(bi.getCellElement(l,c-1))||c<l.cells().length-1&&a(bi.getCellElement(l,c+1))||0<u&&a(bi.getCellElement(i[u-1],c))||u<i.length-1&&a(bi.getCellElement(i[u+1],c)))&&zi(t,bi.getCellElement(t[g],p),o,r.cell);var h=bi.getCellElement(n[g-f],p-s),v=r.replace(h);bi.mutateCell(t[g],p,Zt(v,!0))}return t}(n,t,o,i,u)})},Ui=function(e,t,n,r,o){Hi(t,e,o,r.cell);var i=_i(n,t),u=Li(n,i,r),c=_i(t,u),a=Li(t,c,r);return a.slice(0,e).concat(u).concat(a.slice(e,a.length))},qi=function(n,r,e,o,i){var t=n.slice(0,r),u=n.slice(r),c=bi.mapCells(n[e],function(e,t){return 0<r&&r<n.length&&o(bi.getCellElement(n[r-1],t),bi.getCellElement(n[r],t))?bi.getCell(n[r],t):Zt(i(e.element(),o),!0)});return t.concat([c]).concat(u)},Vi=function(e,n,r,o,i){return B(e,function(e){var t=0<n&&n<bi.cellLength(e)&&o(bi.getCellElement(e,n-1),bi.getCellElement(e,n))?bi.getCell(e,n):Zt(i(bi.getCellElement(e,r),o),!0);return bi.addCell(e,n,t)})},Gi=function(e,r,o,i,u){var c=o+1;return B(e,function(e,t){var n=t===r?Zt(u(bi.getCellElement(e,o),i),!0):bi.getCell(e,o);return bi.addCell(e,c,n)})},Yi=function(e,t,n,r,o){var i=t+1,u=e.slice(0,i),c=e.slice(i),a=bi.mapCells(e[t],function(e,t){return t===n?Zt(o(e.element(),r),!0):e});return u.concat([a]).concat(c)},Ki=function(e,t,n){return e.slice(0,t).concat(e.slice(n+1))},Xi=function(e,n,r){var t=B(e,function(e){var t=e.cells().slice(0,n).concat(e.cells().slice(r+1));return tn(t,e.section())});return _(t,function(e){return 0<e.cells().length})},$i=function(e,n,r,o){return B(e,function(e){return bi.mapCells(e,function(e){return t=e,P(n,function(e){return r(t.element(),e.element())})?Zt(o(e.element(),r),!0):e;var t})})},Ji=function(e,t,n,r){return bi.getCellElement(e[t],n)!==undefined&&0<t&&r(bi.getCellElement(e[t-1],n),bi.getCellElement(e[t],n))},Qi=function(e,t,n){return 0<t&&n(bi.getCellElement(e,t-1),bi.getCellElement(e,t))},Zi=function(n,r,o,e){var t=V(n,function(e,t){return Ji(n,t,r,o)||Qi(e,r,o)?[]:[bi.getCell(e,r)]});return $i(n,t,o,e)},eu=function(n,r,o,e){var i=n[r],t=V(i.cells(),function(e,t){return Ji(n,r,t,o)||Qi(i,t,o)?[]:[e]});return $i(n,t,o,e)},tu=Mr([{none:[]},{only:["index"]},{left:["index","next"]},{middle:["prev","index","next"]},{right:["prev","index"]}]),nu=Bo({},tu),ru=function(e,t,i,u){var n,r,c=e.slice(0),o=(r=t,0===(n=e).length?nu.none():1===n.length?nu.only(0):0===r?nu.left(0,1):r===n.length-1?nu.right(r-1,r):0<r&&r<n.length-1?nu.middle(r-1,r,r+1):nu.none()),a=function(e){return B(e,S(0))},l=S(a(c)),f=function(e,t){if(0<=i){var n=Math.max(u.minCellWidth(),c[t]-i);return a(c.slice(0,e)).concat([i,n-c[t]]).concat(a(c.slice(t+1)))}var r=Math.max(u.minCellWidth(),c[e]+i),o=c[e]-r;return a(c.slice(0,e)).concat([r-c[e],o]).concat(a(c.slice(t+1)))},s=f;return o.fold(l,function(e){return u.singleColumnWidth(c[e],i)},s,function(e,t,n){return f(t,n)},function(e,t){if(0<=i)return a(c.slice(0,t)).concat([i]);var n=Math.max(u.minCellWidth(),c[t]+i);return a(c.slice(0,t)).concat([n-c[t]])})},ou=function(e,t){return Re(e,t)&&1<parseInt(xe(e,t),10)},iu={hasColspan:function(e){return ou(e,"colspan")},hasRowspan:function(e){return ou(e,"rowspan")},minWidth:S(10),minHeight:S(10),getInt:function(e,t){return parseInt(He(e,t),10)}},uu=function(e,t,n){return Ue(e,t).fold(function(){return n(e)+"px"},function(e){return e})},cu=function(e,t){return uu(e,"width",function(e){return so.getPixelWidth(e,t)})},au=function(e){return uu(e,"height",so.getHeight)},lu=function(e,t,n,r,o){var i=Jo(e),u=B(i,function(e){return e.map(t.edge)});return B(i,function(e,t){return e.filter(d(iu.hasColspan)).fold(function(){var e=Xo(u,t);return r(e)},function(e){return n(e,o)})})},fu=function(e){return e.map(function(e){return e+"px"}).getOr("")},su=function(e,t,n,r){var o=Qo(e),i=B(o,function(e){return e.map(t.edge)});return B(o,function(e,t){return e.filter(d(iu.hasRowspan)).fold(function(){var e=Xo(i,t);return r(e)},function(e){return n(e)})})},du={getRawWidths:function(e,t,n){return lu(e,t,cu,fu,n)},getPixelWidths:function(e,t,n){return lu(e,t,so.getPixelWidth,function(e){return e.getOrThunk(n.minCellWidth)},n)},getPercentageWidths:function(e,t,n){return lu(e,t,so.getPercentageWidth,function(e){return e.fold(function(){return n.minCellWidth()},function(e){return e/n.pixelWidth()*100})},n)},getPixelHeights:function(e,t){return su(e,t,so.getHeight,function(e){return e.getOrThunk(iu.minHeight)})},getRawHeights:function(e,t){return su(e,t,au,fu)}},mu=function(e,t,n){for(var r=0,o=e;o<t;o++)r+=n[o]!==undefined?n[o]:0;return r},gu=function(e,n){var t=Dn.justCells(e);return B(t,function(e){var t=mu(e.column(),e.column()+e.colspan(),n);return{element:e.element,width:S(t),colspan:e.colspan}})},pu=function(e,n){var t=Dn.justCells(e);return B(t,function(e){var t=mu(e.row(),e.row()+e.rowspan(),n);return{element:e.element,height:S(t),rowspan:e.rowspan}})},hu=function(e,n){return B(e.all(),function(e,t){return{element:e.element,height:S(n[t])}})},vu=function(e){var t=o;return{width:S(e),pixelWidth:S(e),getWidths:du.getPixelWidths,getCellDelta:t,singleColumnWidth:function(e,t){return[Math.max(iu.minWidth(),e+t)-e]},minCellWidth:iu.minWidth,setElementWidth:so.setPixelWidth,setTableWidth:function(e,t,n){var r=L(t,function(e,t){return e+t},0);so.setPixelWidth(e,r)}}},bu=function(e,t){var n,r,o,i,u=so.percentageBasedSizeRegex().exec(t);if(null!==u)return n=u[1],r=e,o=parseFloat(n),i=Jr(r),{width:S(o),pixelWidth:S(i),getWidths:du.getPercentageWidths,getCellDelta:function(e){return e/i*100},singleColumnWidth:function(e,t){return[100-e]},minCellWidth:function(){return iu.minWidth()/i*100},setElementWidth:so.setPercentageWidth,setTableWidth:function(e,t,n){var r=o+n;so.setPercentageWidth(e,r)}};var c=so.pixelBasedSizeRegex().exec(t);if(null!==c){var a=parseInt(c[1],10);return vu(a)}var l=Jr(e);return vu(l)},wu=function(t){return so.getRawWidth(t).fold(function(){var e=Jr(t);return vu(e)},function(e){return bu(t,e)})},yu=function(e){return Dn.generate(e)},Cu=function(e){var t=xn(e);return yu(t)},Su=function(e,t,n,r){var o=wu(e),i=o.getCellDelta(t),u=Cu(e),c=o.getWidths(u,r,o),a=ru(c,n,i,o),l=B(a,function(e,t){return e+c[t]}),f=gu(u,l);M(f,function(e){o.setElementWidth(e.element(),e.width())}),n===u.grid().columns()-1&&o.setTableWidth(e,l,i)},xu=function(e,n,r,t){var o=Cu(e),i=du.getPixelHeights(o,t),u=B(i,function(e,t){return r===t?Math.max(n+e,iu.minHeight()):e}),c=pu(o,u),a=hu(o,u);M(a,function(e){so.setHeight(e.element(),e.height())}),M(c,function(e){so.setHeight(e.element(),e.height())});var l=L(u,function(e,t){return e+t},0);so.setHeight(e,l)},Ru=function(e,t,n){var r=wu(e),o=yu(t),i=r.getWidths(o,n,r),u=gu(o,i);M(u,function(e){r.setElementWidth(e.element(),e.width())}),0<u.length&&r.setTableWidth(e,i,r.getCellDelta(0))},Tu=function(r,o,i){if(0===o.length)throw new Error("You must specify at least one required field.");return ue("required",o),ce(o),function(t){var n=X(t);G(o,function(e){return I(n,e)})||oe(o,n),r(o,n);var e=_(o,function(e){return!i.validate(t[e],e)});return 0<e.length&&function(e,t){throw new Error("All values need to be of type: "+t+". Keys ("+re(e).join(", ")+") were not.")}(e,i.label),t}},Ou=function(t,e){var n=_(e,function(e){return!I(t,e)});0<n.length&&ie(n)},Du=function(e){return Tu(Ou,e,{validate:A,label:"function"})},Au=Du(["cell","row","replace","gap"]),Eu=function(e){var t=Re(e,"colspan")?parseInt(xe(e,"colspan"),10):1,n=Re(e,"rowspan")?parseInt(xe(e,"rowspan"),10):1;return{element:S(e),colspan:S(t),rowspan:S(n)}},Nu=function(r,o){void 0===o&&(o=Eu),Au(r);var n=l(x.none()),i=function(e){var t,n=o(e);return t=n,r.cell(t)},u=function(e){var t=i(e);return n.get().isNone()&&n.set(x.some(t)),c=x.some({item:e,replacement:t}),t},c=x.none();return{getOrInit:function(t,n){return c.fold(function(){return u(t)},function(e){return n(t,e.item)?e.replacement:u(t)})},cursor:n.get}},ku=function(c,a){return function(r){var o=l(x.none());Au(r);var i=[],u=function(e){var t={scope:c},n=r.replace(e,a,t);return i.push({item:e,sub:n}),o.get().isNone()&&o.set(x.some(n)),n};return{replaceOrInit:function(t,n){return(r=t,o=n,z(i,function(e){return o(e.item,r)})).fold(function(){return u(t)},function(e){return n(t,e.item)?e.sub:u(t)});var r,o},cursor:o.get}}},Iu=function(n){Au(n);var e=l(x.none());return{combine:function(t){return e.get().isNone()&&e.set(x.some(t)),function(){var e=n.cell({element:S(t),colspan:S(1),rowspan:S(1)});return qe(e,"width"),qe(t,"width"),e}},cursor:e.get}},Pu=["body","p","div","article","aside","figcaption","figure","footer","header","nav","section","ol","ul","table","thead","tfoot","tbody","caption","tr","td","th","h1","h2","h3","h4","h5","h6","blockquote","pre","address"],Bu=function(e,t){var n=e.property().name(t);return I(Pu,n)},Mu=function(e,t){return I(["br","img","hr","input"],e.property().name(t))},Wu=Bu,_u=function(e,t){var n=e.property().name(t);return I(["ol","ul"],n)},Lu=Mu,ju=sr(),zu=function(e){return Wu(ju,e)},Hu=function(e){return _u(ju,e)},Fu=function(e){return Lu(ju,e)},Uu=function(e){var t,i=function(e){return"br"===me(e)},n=function(o){return Ln(o).bind(function(n){var r=Bt(n).map(function(e){return!!zu(e)||!!Fu(e)&&"img"!==me(e)}).getOr(!1);return kt(n).map(function(e){return!0===r||"li"===me(t=e)||fn(t,Hu).isSome()||i(n)||zu(e)&&!Dt(o,e)?[]:[Pe.fromTag("br")];var t})}).getOr([])},r=0===(t=V(e,function(e){var t=Mt(e);return G(t,function(e){return i(e)||be(e)&&0===kn(e).trim().length})?[]:t.concat(n(e))})).length?[Pe.fromTag("br")]:t;qt(e[0]),Ut(e[0],r)},qu=function(e){0===Sn.cells(e).length&&Vt(e)},Vu=ne("grid","cursor"),Gu=function(e,t,n){return Yu(e,t,n).orThunk(function(){return Yu(e,0,0)})},Yu=function(e,t,n){return x.from(e[t]).bind(function(e){return x.from(e.cells()[n]).bind(function(e){return x.from(e.element())})})},Ku=function(e,t,n){return Vu(e,Yu(e,t,n))},Xu=function(e){return j(e,function(e,t){return P(e,function(e){return e.row()===t.row()})?e:e.concat([t])},[]).sort(function(e,t){return e.row()-t.row()})},$u=function(e){return j(e,function(e,t){return P(e,function(e){return e.column()===t.column()})?e:e.concat([t])},[]).sort(function(e,t){return e.column()-t.column()})},Ju=function(e,t,n){var r=Rn(e,n),o=Dn.generate(r);return Si(o,t,!0)},Qu=Ru,Zu={insertRowBefore:Oi(function(e,t,n,r){var o=t.row(),i=t.row(),u=qi(e,i,o,n,r.getOrInit);return Ku(u,i,t.column())},Di,y,y,Nu),insertRowsBefore:Oi(function(e,t,n,r){var o=t[0].row(),i=t[0].row(),u=Xu(t),c=j(u,function(e,t){return qi(e,i,o,n,r.getOrInit)},e);return Ku(c,i,t[0].column())},Ei,y,y,Nu),insertRowAfter:Oi(function(e,t,n,r){var o=t.row(),i=t.row()+t.rowspan(),u=qi(e,i,o,n,r.getOrInit);return Ku(u,i,t.column())},Di,y,y,Nu),insertRowsAfter:Oi(function(e,t,n,r){var o=Xu(t),i=o[o.length-1].row(),u=o[o.length-1].row()+o[o.length-1].rowspan(),c=j(o,function(e,t){return qi(e,u,i,n,r.getOrInit)},e);return Ku(c,u,t[0].column())},Ei,y,y,Nu),insertColumnBefore:Oi(function(e,t,n,r){var o=t.column(),i=t.column(),u=Vi(e,i,o,n,r.getOrInit);return Ku(u,t.row(),i)},Di,Qu,y,Nu),insertColumnsBefore:Oi(function(e,t,n,r){var o=$u(t),i=o[0].column(),u=o[0].column(),c=j(o,function(e,t){return Vi(e,u,i,n,r.getOrInit)},e);return Ku(c,t[0].row(),u)},Ei,Qu,y,Nu),insertColumnAfter:Oi(function(e,t,n,r){var o=t.column(),i=t.column()+t.colspan(),u=Vi(e,i,o,n,r.getOrInit);return Ku(u,t.row(),i)},Di,Qu,y,Nu),insertColumnsAfter:Oi(function(e,t,n,r){var o=t[t.length-1].column(),i=t[t.length-1].column()+t[t.length-1].colspan(),u=$u(t),c=j(u,function(e,t){return Vi(e,i,o,n,r.getOrInit)},e);return Ku(c,t[0].row(),i)},Ei,Qu,y,Nu),splitCellIntoColumns:Oi(function(e,t,n,r){var o=Gi(e,t.row(),t.column(),n,r.getOrInit);return Ku(o,t.row(),t.column())},Di,Qu,y,Nu),splitCellIntoRows:Oi(function(e,t,n,r){var o=Yi(e,t.row(),t.column(),n,r.getOrInit);return Ku(o,t.row(),t.column())},Di,y,y,Nu),eraseColumns:Oi(function(e,t,n,r){var o=$u(t),i=Xi(e,o[0].column(),o[o.length-1].column()),u=Gu(i,t[0].row(),t[0].column());return Vu(i,u)},Ei,Qu,qu,Nu),eraseRows:Oi(function(e,t,n,r){var o=Xu(t),i=Ki(e,o[0].row(),o[o.length-1].row()),u=Gu(i,t[0].row(),t[0].column());return Vu(i,u)},Ei,y,qu,Nu),makeColumnHeader:Oi(function(e,t,n,r){var o=Zi(e,t.column(),n,r.replaceOrInit);return Ku(o,t.row(),t.column())},Di,y,y,ku("row","th")),unmakeColumnHeader:Oi(function(e,t,n,r){var o=Zi(e,t.column(),n,r.replaceOrInit);return Ku(o,t.row(),t.column())},Di,y,y,ku(null,"td")),makeRowHeader:Oi(function(e,t,n,r){var o=eu(e,t.row(),n,r.replaceOrInit);return Ku(o,t.row(),t.column())},Di,y,y,ku("col","th")),unmakeRowHeader:Oi(function(e,t,n,r){var o=eu(e,t.row(),n,r.replaceOrInit);return Ku(o,t.row(),t.column())},Di,y,y,ku(null,"td")),mergeCells:Oi(function(e,t,n,r){var o=t.cells();Uu(o);var i=ji(e,t.bounds(),n,S(o[0]));return Vu(i,x.from(o[0]))},function(e,t){return t.mergable()},y,y,Iu),unmergeCells:Oi(function(e,t,n,r){var o=L(t,function(e,t){return zi(e,t,n,r.combine(t))},e);return Vu(o,x.from(t[0]))},function(e,t){return t.unmergable()},Qu,y,Iu),pasteCells:Oi(function(e,n,t,r){var o,i,u,c,a=(o=n.clipboard(),i=n.generators(),u=xn(o),c=Dn.generate(u),Si(c,i,!0)),l=Kt(n.row(),n.column());return Fi(l,e,a,n.generators(),t).fold(function(){return Vu(e,x.some(n.element()))},function(e){var t=Gu(e,n.row(),n.column());return Vu(e,t)})},function(t,n){return Sn.cell(n.element()).bind(function(e){return Ti(t,e).map(function(e){return Bo({},e,{generators:n.generators,clipboard:n.clipboard})})})},Qu,y,Nu),pasteRowsBefore:Oi(function(e,t,n,r){var o=e[t.cells[0].row()],i=t.cells[0].row(),u=Ju(t.clipboard(),t.generators(),o),c=Ui(i,e,u,t.generators(),n),a=Gu(c,t.cells[0].row(),t.cells[0].column());return Vu(c,a)},Ai,y,y,Nu),pasteRowsAfter:Oi(function(e,t,n,r){var o=e[t.cells[0].row()],i=t.cells[t.cells.length-1].row()+t.cells[t.cells.length-1].rowspan(),u=Ju(t.clipboard(),t.generators(),o),c=Ui(i,e,u,t.generators(),n),a=Gu(c,t.cells[0].row(),t.cells[0].column());return Vu(c,a)},Ai,y,y,Nu)},ec=function(e){return Pe.fromDom(e.getBody())},tc=function(e){return e.getBoundingClientRect().width},nc=function(e){return e.getBoundingClientRect().height},rc=function(t){return function(e){return Dt(e,ec(t))}},oc=function(e){return/^[0-9]+$/.test(e)&&(e+="px"),e},ic=function(e){var t=an(e,"td[data-mce-style],th[data-mce-style]");Te(e,"data-mce-style"),M(t,function(e){Te(e,"data-mce-style")})},uc={isRtl:S(!1)},cc={isRtl:S(!0)},ac={directionAt:function(e){return"rtl"==("rtl"===He(e,"direction")?"rtl":"ltr")?cc:uc}},lc={"border-collapse":"collapse",width:"100%"},fc={border:"1"},sc=function(e){return e.getParam("table_default_attributes",fc,"object")},dc=function(e){return e.getParam("table_default_styles",lc,"object")},mc=function(e){return e.getParam("table_tab_navigation",!0,"boolean")},gc=function(e){return e.getParam("table_cell_advtab",!0,"boolean")},pc=function(e){return e.getParam("table_row_advtab",!0,"boolean")},hc=function(e){return e.getParam("table_advtab",!0,"boolean")},vc=function(e){return e.getParam("table_style_by_css",!1,"boolean")},bc=function(e){return e.getParam("table_class_list",[],"array")},wc=function(e){return!1===e.getParam("table_responsive_width")},yc=function(e,t){return e.fire("newrow",{node:t})},Cc=function(e,t){return e.fire("newcell",{node:t})},Sc=function(e,t,n,r){e.fire("ObjectResizeStart",{target:t,width:n,height:r})},xc=function(e,t,n,r){e.fire("ObjectResized",{target:t,width:n,height:r})},Rc=function(f,e){var t,n=function(e){return"table"===me(ec(e))},s=(t=f.getParam("table_clone_elements"),T(t)?x.some(t.split(/[ ,]/)):Array.isArray(t)?x.some(t):x.none()),r=function(u,c,a,l){return function(e,t){ic(e);var n=l(),r=Pe.fromDom(f.getDoc()),o=ko(ac.directionAt),i=Kn(a,r,s);return c(e)?u(n,e,t,i,o).bind(function(e){return M(e.newRows(),function(e){yc(f,e.dom())}),M(e.newCells(),function(e){Cc(f,e.dom())}),e.cursor().map(function(e){var t=f.dom.createRng();return t.setStart(e.dom(),0),t.setEnd(e.dom(),0),t})}):x.none()}};return{deleteRow:r(Zu.eraseRows,function(e){var t=Po(e);return!1===n(f)||1<t.rows()},y,e),deleteColumn:r(Zu.eraseColumns,function(e){var t=Po(e);return!1===n(f)||1<t.columns()},y,e),insertRowsBefore:r(Zu.insertRowsBefore,c,y,e),insertRowsAfter:r(Zu.insertRowsAfter,c,y,e),insertColumnsBefore:r(Zu.insertColumnsBefore,c,mo,e),insertColumnsAfter:r(Zu.insertColumnsAfter,c,mo,e),mergeCells:r(Zu.mergeCells,c,y,e),unmergeCells:r(Zu.unmergeCells,c,y,e),pasteRowsBefore:r(Zu.pasteRowsBefore,c,y,e),pasteRowsAfter:r(Zu.pasteRowsAfter,c,y,e),pasteCells:r(Zu.pasteCells,c,y,e)}},Tc=function(e,t,r){var n=xn(e),o=Dn.generate(n);return Ei(o,t).map(function(e){var t=Si(o,r,!1).slice(e[0].row(),e[e.length-1].row()+e[e.length-1].rowspan()),n=Ri(t,r);return jo(n)})},Oc=tinymce.util.Tools.resolve("tinymce.util.Tools"),Dc=function(e,t,n){n&&e.formatter.apply("align"+n,{},t)},Ac=function(e,t,n){n&&e.formatter.apply("valign"+n,{},t)},Ec=function(t,n){Oc.each("left center right".split(" "),function(e){t.formatter.remove("align"+e,{},n)})},Nc=function(t,n){Oc.each("top middle bottom".split(" "),function(e){t.formatter.remove("valign"+e,{},n)})},kc=function(o,e,i){var t;return t=function(e,t){for(var n=0;n<t.length;n++){var r=o.getStyle(t[n],i);if(void 0===e&&(e=r),e!==r)return""}return e}(t,o.select("td,th",e))},Ic=function(t,e){var n=function(e){return Ee(e,"rgb")?t.toHex(e):e};return{borderstyle:Ue(Pe.fromDom(e),"border-style").getOr(""),bordercolor:Ue(Pe.fromDom(e),"border-color").map(n).getOr(""),backgroundcolor:Ue(Pe.fromDom(e),"background-color").map(n).getOr("")}},Pc=function(e,t,n,r,o){var i={};return Oc.each(e.split(" "),function(e){r.formatter.matchNode(o,t+e)&&(i[n]=e)}),i[n]||(i[n]=""),i},Bc=b(Pc,"left center right"),Mc=b(Pc,"top middle bottom"),Wc=function(e,r,t){var o=function(e,n){return n=n||[],Oc.each(e,function(e){var t={text:e.text||e.title};e.menu?t.menu=o(e.menu):(t.value=e.value,r&&r(t)),n.push(t)}),n};return o(e,t||[])},_c=function(e){var i=e[0],t=e.slice(1),n=X(i);return M(t,function(e){M(n,function(o){J(e,function(e,t,n){var r=i[o];""!==r&&o===t&&r!==e&&(i[o]="")})})}),i},Lc=function(){return{title:"Advanced",name:"advanced",items:[{name:"borderstyle",type:"selectbox",label:"Border style",items:[{text:"Select...",value:""},{text:"Solid",value:"solid"},{text:"Dotted",value:"dotted"},{text:"Dashed",value:"dashed"},{text:"Double",value:"double"},{text:"Groove",value:"groove"},{text:"Ridge",value:"ridge"},{text:"Inset",value:"inset"},{text:"Outset",value:"outset"},{text:"None",value:"none"},{text:"Hidden",value:"hidden"}]},{name:"bordercolor",type:"colorinput",label:"Border color"},{name:"backgroundcolor",type:"colorinput",label:"Background color"}]}},jc=function(e,t,n){var r,o,i,u=e.dom;return Bo({width:u.getStyle(t,"width")||u.getAttrib(t,"width"),height:u.getStyle(t,"height")||u.getAttrib(t,"height"),cellspacing:u.getStyle(t,"border-spacing")||u.getAttrib(t,"cellspacing"),cellpadding:u.getAttrib(t,"cellpadding")||kc(e.dom,t,"padding"),border:(r=u,o=t,i=Ue(Pe.fromDom(o),"border-width"),vc(e)&&i.isSome()?i.getOr(""):r.getAttrib(o,"border")||kc(e.dom,o,"border-width")||kc(e.dom,o,"border")),caption:!!u.select("caption",t)[0],"class":u.getAttrib(t,"class","")},Bc("align","align",e,t),n?Ic(u,t):{})},zc=function(e,t,n){var r=e.dom;return Bo({height:r.getStyle(t,"height")||r.getAttrib(t,"height"),scope:r.getAttrib(t,"scope"),"class":r.getAttrib(t,"class",""),align:"",type:t.parentNode.nodeName.toLowerCase()},Bc("align","align",e,t),n?Ic(r,t):{})},Hc=function(e,t,n){var r=e.dom;return Bo({width:r.getStyle(t,"width")||r.getAttrib(t,"width"),height:r.getStyle(t,"height")||r.getAttrib(t,"height"),scope:r.getAttrib(t,"scope"),celltype:t.nodeName.toLowerCase(),"class":r.getAttrib(t,"class","")},Bc("align","halign",e,t),Mc("valign","valign",e,t),n?Ic(r,t):{})},Fc=function(e,t){var n,r,o,i,u,c,a,l,f=dc(e),s=sc(e),d=e.dom,m=t?(n=d,r=function(e){return Ee(e,"rgb")?n.toHex(e):e},o=ee(f,"border-style").getOr(""),i=ee(f,"border-color").getOr(""),u=ee(f,"background-color").getOr(""),{borderstyle:o,bordercolor:r(i),backgroundcolor:r(u)}):{};return Bo({},{height:"",width:"100%",cellspacing:"",cellpadding:"",caption:!1,"class":"",align:"",border:""},f,s,m,(l=f["border-width"],vc(e)&&l?{border:l}:ee(s,"border").fold(function(){return{}},function(e){return{border:e}})),(c=ee(f,"border-spacing").or(ee(s,"cellspacing")).fold(function(){return{}},function(e){return{cellspacing:e}}),a=ee(f,"border-padding").or(ee(s,"cellpadding")).fold(function(){return{}},function(e){return{cellpadding:e}}),Bo({},c,a)))},Uc=[{name:"width",type:"input",label:"Width"},{name:"height",type:"input",label:"Height"},{name:"celltype",type:"selectbox",label:"Cell type",items:[{text:"Cell",value:"td"},{text:"Header cell",value:"th"}]},{name:"scope",type:"selectbox",label:"Scope",items:[{text:"None",value:""},{text:"Row",value:"row"},{text:"Column",value:"col"},{text:"Row group",value:"rowgroup"},{text:"Column group",value:"colgroup"}]},{name:"halign",type:"selectbox",label:"H Align",items:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{name:"valign",type:"selectbox",label:"V Align",items:[{text:"None",value:""},{text:"Top",value:"top"},{text:"Middle",value:"middle"},{text:"Bottom",value:"bottom"}]}],qc=function(e){return(t=e,n=t.getParam("table_cell_class_list",[],"array"),r=Wc(n,function(e){e.value&&(e.textStyle=function(){return t.formatter.getCssText({block:"tr",classes:[e.value]})})}),0<n.length?x.some({name:"class",type:"selectbox",label:"Class",items:r}):x.none()).fold(function(){return Uc},function(e){return Uc.concat(e)});var t,n,r},Vc={normal:function(n,r){return{setAttrib:function(e,t){n.setAttrib(r,e,t)},setStyle:function(e,t){n.setStyle(r,e,t)}}},ifTruthy:function(n,r){return{setAttrib:function(e,t){t&&n.setAttrib(r,e,t)},setStyle:function(e,t){t&&n.setStyle(r,e,t)}}}},Gc=function(e,t){e.setAttrib("scope",t.scope),e.setAttrib("class",t["class"]),e.setStyle("width",oc(t.width)),e.setStyle("height",oc(t.height))},Yc=function(e,t){e.setStyle("background-color",t.backgroundcolor),e.setStyle("border-color",t.bordercolor),e.setStyle("border-style",t.borderstyle)},Kc=function(e,t,n){var r=e.dom,o=n.celltype&&t[0].nodeName.toLowerCase()!==n.celltype?r.rename(t[0],n.celltype):t[0],i=Vc.normal(r,o);Gc(i,n),gc(e)&&Yc(i,n),Ec(e,o),Nc(e,o),n.halign&&Dc(e,o,n.halign),n.valign&&Ac(e,o,n.valign)},Xc=function(n,e,r){var o=n.dom;Oc.each(e,function(e){r.celltype&&e.nodeName.toLowerCase()!==r.celltype&&(e=o.rename(e,r.celltype));var t=Vc.ifTruthy(o,e);Gc(t,r),gc(n)&&Yc(t,r),r.halign&&Dc(n,e,r.halign),r.valign&&Ac(n,e,r.valign)})},$c=function(e,t,n){var r=n.getData();n.close(),e.undoManager.transact(function(){(1===t.length?Kc:Xc)(e,t,r),e.focus()})},Jc=function(t){var e,n=[];if(n=t.dom.select("td[data-mce-selected],th[data-mce-selected]"),e=t.dom.getParent(t.selection.getStart(),"td,th"),!n.length&&e&&n.push(e),e=e||n[0]){var r=Oc.map(n,function(e){return Hc(t,e,gc(t))}),o=_c(r),i={type:"tabpanel",tabs:[{title:"General",name:"general",items:qc(t)},Lc()]},u={type:"panel",items:[{type:"grid",columns:2,items:qc(t)}]};t.windowManager.open({title:"Cell Properties",size:"normal",body:gc(t)?i:u,buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:o,onSubmit:b($c,t,n)})}},Qc=[{type:"selectbox",name:"type",label:"Row type",items:[{text:"Header",value:"thead"},{text:"Body",value:"tbody"},{text:"Footer",value:"tfoot"}]},{type:"selectbox",name:"align",label:"Alignment",items:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]},{label:"Height",name:"height",type:"input"}],Zc=function(e){return(t=e,n=t.getParam("table_row_class_list",[],"array"),r=Wc(n,function(e){e.value&&(e.textStyle=function(){return t.formatter.getCssText({block:"tr",classes:[e.value]})})}),0<n.length?x.some({name:"class",type:"selectbox",label:"Class",items:r}):x.none()).fold(function(){return Qc},function(e){return Qc.concat(e)});var t,n,r},ea=function(f,e,s,t){var d=f.dom,m=t.getData();t.close();var g=1===e.length?Vc.normal:Vc.ifTruthy;f.undoManager.transact(function(){Oc.each(e,function(e){var t,n,r,o,i,u;m.type!==e.parentNode.nodeName.toLowerCase()&&(t=f.dom,n=e,r=m.type,o=t.getParent(n,"table"),i=n.parentNode,(u=t.select(r,o)[0])||(u=t.create(r),o.firstChild?"CAPTION"===o.firstChild.nodeName?t.insertAfter(u,o.firstChild):o.insertBefore(u,o.firstChild):o.appendChild(u)),u.appendChild(n),i.hasChildNodes()||t.remove(i));var c,a,l=g(d,e);l.setAttrib("scope",m.scope),l.setAttrib("class",m["class"]),l.setStyle("height",oc(m.height)),pc(f)&&(a=m,(c=l).setStyle("background-color",a.backgroundcolor),c.setStyle("border-color",a.bordercolor),c.setStyle("border-style",a.borderstyle)),m.align!==s.align&&(Ec(f,e),Dc(f,e,m.align))}),f.focus()})},ta=function(t){var e,n,r=t.dom,o=[];if((e=r.getParent(t.selection.getStart(),"table"))&&(n=r.getParent(t.selection.getStart(),"td,th"),Oc.each(e.rows,function(t){Oc.each(t.cells,function(e){if((r.getAttrib(e,"data-mce-selected")||e===n)&&o.indexOf(t)<0)return o.push(t),!1})}),o[0])){var i=Oc.map(o,function(e){return zc(t,e,pc(t))}),u=_c(i),c={type:"tabpanel",tabs:[{title:"General",name:"general",items:Zc(t)},Lc()]},a={type:"panel",items:[{type:"grid",columns:2,items:Zc(t)}]};t.windowManager.open({title:"Row Properties",size:"normal",body:pc(t)?c:a,buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:u,onSubmit:b(ea,t,o,u)})}},na=Object.prototype.hasOwnProperty,ra=(Io=function(e,t){return t},function(){for(var e=new Array(arguments.length),t=0;t<e.length;t++)e[t]=arguments[t];if(0===e.length)throw new Error("Can't merge zero objects");for(var n={},r=0;r<e.length;r++){var o=e[r];for(var i in o)na.call(o,i)&&(n[i]=Io(n[i],o[i]))}return n}),oa=tinymce.util.Tools.resolve("tinymce.Env"),ia={styles:{"border-collapse":"collapse",width:"100%"},attributes:{border:"1"},percentages:!0},ua=function(e,t,n,r,o){void 0===o&&(o=ia);var i=Pe.fromTag("table");ze(i,o.styles),Se(i,o.attributes);var u=Pe.fromTag("tbody");zt(i,u);for(var c=[],a=0;a<e;a++){for(var l=Pe.fromTag("tr"),f=0;f<t;f++){var s=a<n||f<r?Pe.fromTag("th"):Pe.fromTag("td");f<r&&Ce(s,"scope","row"),a<n&&Ce(s,"scope","col"),zt(s,Pe.fromTag("br")),o.percentages&&je(s,"width",100/t+"%"),zt(l,s)}c.push(l)}return Ut(u,c),i},ca=function(e,t){e.selection.select(t.dom(),!0),e.selection.collapse(!0)},aa=function(r,e,t){var n,o=dc(r),i={styles:o,attributes:sc(r),percentages:(n=o.width,T(n)&&-1!==n.indexOf("%")&&!wc(r))},u=ua(t,e,0,0,i);Ce(u,"data-mce-id","__mce");var c,a,l,f=(c=u,a=Pe.fromTag("div"),l=Pe.fromDom(c.dom().cloneNode(!0)),zt(a,l),a.dom().innerHTML);return r.insertContent(f),mn(ec(r),'table[data-mce-id="__mce"]').map(function(e){var t,n;return wc(r)&&je(e,"width",He(e,"width")),Te(e,"data-mce-id"),t=r,M(an(e,"tr"),function(e){yc(t,e.dom()),M(an(e,"th,td"),function(e){Cc(t,e.dom())})}),n=r,mn(e,"td,th").each(b(ca,n)),e.dom()}).getOr(null)},la=function(t,e,n){var r=n?[{type:"input",name:"cols",label:"Cols"},{type:"input",name:"rows",label:"Rows"}]:[],o=t.getParam("table_appearance_options",!0,"boolean")?[{type:"input",name:"cellspacing",label:"Cell spacing"},{type:"input",name:"cellpadding",label:"Cell padding"},{type:"input",name:"border",label:"Border width"},{type:"label",label:"Caption",items:[{type:"checkbox",name:"caption",label:"Show caption"}]}]:[],i=e?[{type:"selectbox",name:"class",label:"Class",items:Wc(bc(t),function(e){e.value&&(e.textStyle=function(){return t.formatter.getCssText({block:"table",classes:[e.value]})})})}]:[];return r.concat([{type:"input",name:"width",label:"Width"},{type:"input",name:"height",label:"Height"}]).concat(o).concat([{type:"selectbox",name:"align",label:"Alignment",items:[{text:"None",value:""},{text:"Left",value:"left"},{text:"Center",value:"center"},{text:"Right",value:"right"}]}]).concat(i)},fa=function(e,t,n,r){if("TD"===t.tagName||"TH"===t.tagName)T(n)?e.setStyle(t,n,r):e.setStyle(t,n);else if(t.children)for(var o=0;o<t.children.length;o++)fa(e,t.children[o],n,r)},sa=function(n,r,e){var o,i=n.dom,u=e.getData();e.close(),""===u["class"]&&delete u["class"],n.undoManager.transact(function(){if(!r){var e=parseInt(u.cols,10)||1,t=parseInt(u.rows,10)||1;r=aa(n,e,t)}!function(e,t,n){var r,o=e.dom,i={},u={};if(i["class"]=n["class"],u.height=oc(n.height),o.getAttrib(t,"width")&&!vc(e)?i.width=(r=n.width)?r.replace(/px$/,""):"":u.width=oc(n.width),vc(e)?(u["border-width"]=oc(n.border),u["border-spacing"]=oc(n.cellspacing)):(i.border=n.border,i.cellpadding=n.cellpadding,i.cellspacing=n.cellspacing),vc(e)&&t.children)for(var c=0;c<t.children.length;c++)fa(o,t.children[c],{"border-width":oc(n.border),padding:oc(n.cellpadding)}),hc(e)&&fa(o,t.children[c],{"border-color":n.bordercolor});hc(e)&&(u["background-color"]=n.backgroundcolor,u["border-color"]=n.bordercolor,u["border-style"]=n.borderstyle),i.style=o.serializeStyle(ra(dc(e),u)),o.setAttribs(t,ra(sc(e),i))}(n,r,u),(o=i.select("caption",r)[0])&&!u.caption&&i.remove(o),!o&&u.caption&&((o=i.create("caption")).innerHTML=oa.ie?"\xa0":'<br data-mce-bogus="1"/>',r.insertBefore(o,r.firstChild)),""===u.align?Ec(n,r):Dc(n,r,u.align),n.focus(),n.addVisual()})},da=function(e,t){var n,r=e.dom,o=Fc(e,hc(e));!1===t?(n=r.getParent(e.selection.getStart(),"table"))?o=jc(e,n,hc(e)):hc(e)&&(o.borderstyle="",o.bordercolor="",o.backgroundcolor=""):(o.cols="1",o.rows="1",hc(e)&&(o.borderstyle="",o.bordercolor="",o.backgroundcolor=""));var i=0<bc(e).length;i&&o["class"]&&(o["class"]=o["class"].replace(/\s*mce\-item\-table\s*/g,""));var u={type:"grid",columns:2,items:la(e,i,t)},c=hc(e)?{type:"tabpanel",tabs:[{title:"General",name:"general",items:[u]},Lc()]}:{type:"panel",items:[u]};e.windowManager.open({title:"Table Properties",size:"normal",body:c,onSubmit:b(sa,e,n),buttons:[{type:"cancel",name:"cancel",text:"Cancel"},{type:"submit",name:"save",text:"Save",primary:!0}],initialData:o})},ma=function(t){return function(e){return x.from(e.dom.getParent(e.selection.getStart(),t)).map(Pe.fromDom)}},ga=ma("th,td"),pa=ma("th,td,caption"),ha=Oc.each,va={registerCommands:function(c,t,a,l,n){var r=rc(c),f=function(e){return Sn.table(e,r)},s=function(e){return{width:tc(e.dom()),height:tc(e.dom())}},o=function(n){ga(c).each(function(t){f(t).each(function(i){var e=qr.forMenu(l,i,t),u=s(i);n(i,e).each(function(e){var t,n,r,o;t=c,n=u,o=s(r=i),n.width===o.width&&n.height===o.height||(Sc(t,r.dom(),n.width,n.height),xc(t,r.dom(),o.width,o.height)),c.selection.setRng(e),c.focus(),a.clear(i),ic(i)})})})},i=function(e){return ga(c).map(function(o){return f(o).bind(function(e){var t=Pe.fromDom(c.getDoc()),n=qr.forMenu(l,e,o),r=Kn(y,t,x.none());return Tc(e,n,r)})})},u=function(u){n.get().each(function(e){var i=B(e,function(e){return Fn(e)});ga(c).each(function(o){f(o).each(function(t){var e=Pe.fromDom(c.getDoc()),n=Xn(e),r=qr.pasteRows(l,t,o,i,n);u(t,r).each(function(e){c.selection.setRng(e),c.focus(),a.clear(t)})})})})};ha({mceTableSplitCells:function(){o(t.unmergeCells)},mceTableMergeCells:function(){o(t.mergeCells)},mceTableInsertRowBefore:function(){o(t.insertRowsBefore)},mceTableInsertRowAfter:function(){o(t.insertRowsAfter)},mceTableInsertColBefore:function(){o(t.insertColumnsBefore)},mceTableInsertColAfter:function(){o(t.insertColumnsAfter)},mceTableDeleteCol:function(){o(t.deleteColumn)},mceTableDeleteRow:function(){o(t.deleteRow)},mceTableCutRow:function(e){i().each(function(e){n.set(e),o(t.deleteRow)})},mceTableCopyRow:function(e){i().each(function(e){n.set(e)})},mceTablePasteRowBefore:function(e){u(t.pasteRowsBefore)},mceTablePasteRowAfter:function(e){u(t.pasteRowsAfter)},mceTableDelete:function(){pa(c).each(function(e){Sn.table(e,r).filter(d(r)).each(function(e){var t=Pe.fromText("");if(Lt(e,t),Vt(e),c.dom.isEmpty(c.getBody()))c.setContent(""),c.selection.setCursorLocation();else{var n=c.dom.createRng();n.setStart(t.dom(),0),n.setEnd(t.dom(),0),c.selection.setRng(n),c.nodeChanged()}})})}},function(e,t){c.addCommand(t,e)}),ha({mceInsertTable:b(da,c,!0),mceTableProps:b(da,c,!1),mceTableRowProps:b(ta,c),mceTableCellProps:b(Jc,c)},function(e,t){c.addCommand(t,function(){e()})})}},ba=function(e){var t=x.from(e.dom().documentElement).map(Pe.fromDom).getOr(e);return{parent:S(t),view:S(e),origin:S(po(0,0))}},wa=function(e,t){return{parent:S(t),view:S(e),origin:S(po(0,0))}},ya=function(e){var r=ne.apply(null,e),o=[];return{bind:function(e){if(e===undefined)throw new Error("Event bind error: undefined handler");o.push(e)},unbind:function(t){o=_(o,function(e){return e!==t})},trigger:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=r.apply(null,e);M(o,function(e){e(n)})}}},Ca={create:function(e){return{registry:Q(e,function(e){return{bind:e.bind,unbind:e.unbind}}),trigger:Q(e,function(e){return e.trigger})}}},Sa=function(m,g){return function(e){if(m(e)){var t,n,r,o,i,u,c,a=Pe.fromDom(e.target),l=function(){e.stopPropagation()},f=function(){e.preventDefault()},s=C(f,l),d=(t=a,n=e.clientX,r=e.clientY,o=l,i=f,u=s,c=e,{target:S(t),x:S(n),y:S(r),stop:o,prevent:i,kill:u,raw:S(c)});g(d)}}},xa=function(e,t,n,r){return o=e,i=t,u=!1,c=Sa(n,r),o.dom().addEventListener(i,c,u),{unbind:b(Ra,o,i,c,u)};var o,i,u,c},Ra=function(e,t,n,r){e.dom().removeEventListener(t,n,r)},Ta=S(!0),Oa=function(e,t,n){return xa(e,t,Ta,n)},Da={resolve:Zo("ephox-dragster").resolve},Aa=Du(["compare","extract","mutate","sink"]),Ea=Du(["element","start","stop","destroy"]),Na=Du(["forceDrop","drop","move","delayDrop"]),ka=Aa({compare:function(e,t){return po(t.left()-e.left(),t.top()-e.top())},extract:function(e){return x.some(po(e.x(),e.y()))},sink:function(e,t){var n=(c=t,a=ra({layerClass:Da.resolve("blocker")},c),l=Pe.fromTag("div"),Ce(l,"role","presentation"),ze(l,{position:"fixed",left:"0px",top:"0px",width:"100%",height:"100%"}),Vo(l,Da.resolve("blocker")),Vo(l,a.layerClass),{element:function(){return l},destroy:function(){Vt(l)}}),r=Oa(n.element(),"mousedown",e.forceDrop),o=Oa(n.element(),"mouseup",e.drop),i=Oa(n.element(),"mousemove",e.move),u=Oa(n.element(),"mouseout",e.delayDrop);var c,a,l;return Ea({element:n.element,start:function(e){zt(e,n.element())},stop:function(){Vt(n.element())},destroy:function(){n.destroy(),o.unbind(),i.unbind(),u.unbind(),r.unbind()}})},mutate:function(e,t){e.mutate(t.left(),t.top())}});function Ia(){var i=x.none(),u=Ca.create({move:ya(["info"])});return{onEvent:function(e,o){o.extract(e).each(function(e){var t,n,r;(t=o,n=e,r=i.map(function(e){return t.compare(e,n)}),i=x.some(n),r).each(function(e){u.trigger.move(e)})})},reset:function(){i=x.none()},events:u.registry}}function Pa(){var e=function r(){return{onEvent:y,reset:y}}(),t=Ia(),n=e;return{on:function(){n.reset(),n=t},off:function(){n.reset(),n=e},isOn:function(){return n===t},onEvent:function(e,t){n.onEvent(e,t)},events:t.events}}var Ba=function(t,n,e){var r,o,i,u=!1,c=Ca.create({start:ya([]),stop:ya([])}),a=Pa(),l=function(){d.stop(),a.isOn()&&(a.off(),c.trigger.stop())},f=(r=l,o=200,i=null,{cancel:function(){null!==i&&(m.clearTimeout(i),i=null)},throttle:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];null!==i&&m.clearTimeout(i),i=m.setTimeout(function(){r.apply(null,e),i=null},o)}});a.events.move.bind(function(e){n.mutate(t,e.info())});var s=function(n){return function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];u&&n.apply(null,e)}},d=n.sink(Na({forceDrop:l,drop:s(l),move:s(function(e){f.cancel(),a.onEvent(e,n)}),delayDrop:s(f.throttle)}),e);return{element:d.element,go:function(e){d.start(e),a.on(),c.trigger.start()},on:function(){u=!0},off:function(){u=!1},destroy:function(){d.destroy()},events:c.registry}},Ma=function(e,t){void 0===t&&(t={});var n=t.mode!==undefined?t.mode:ka;return Ba(e,n,t)},Wa=function(){var n,r=Ca.create({drag:ya(["xDelta","yDelta","target"])}),o=x.none(),e={mutate:function(e,t){n.trigger.drag(e,t)},events:(n=Ca.create({drag:ya(["xDelta","yDelta"])})).registry};e.events.drag.bind(function(t){o.each(function(e){r.trigger.drag(t.xDelta(),t.yDelta(),e)})});return{assign:function(e){o=x.some(e)},get:function(){return o},mutate:e.mutate,events:r.registry}},_a=function(e){return"true"===xe(e,"contenteditable")},La=ei.resolve("resizer-bar-dragging"),ja=function(o,t,i){var n=Wa(),r=Ma(n,{}),u=x.none(),e=function(e,t){return x.from(xe(e,t))};n.events.drag.bind(function(n){e(n.target(),"data-row").each(function(e){var t=iu.getInt(n.target(),"top");je(n.target(),"top",t+n.yDelta()+"px")}),e(n.target(),"data-column").each(function(e){var t=iu.getInt(n.target(),"left");je(n.target(),"left",t+n.xDelta()+"px")})});var c=function(e,t){return iu.getInt(e,t)-parseInt(xe(e,"data-initial-"+t),10)};r.events.stop.bind(function(){n.get().each(function(r){u.each(function(n){e(r,"data-row").each(function(e){var t=c(r,"top");Te(r,"data-initial-top"),m.trigger.adjustHeight(n,t,parseInt(e,10))}),e(r,"data-column").each(function(e){var t=c(r,"left");Te(r,"data-initial-left"),m.trigger.adjustWidth(n,t,parseInt(e,10))}),fi(o,n,i,t)})})});var a=function(e,t){m.trigger.startAdjust(),n.assign(e),Ce(e,"data-initial-"+t,parseInt(He(e,t),10)),Vo(e,La),je(e,"opacity","0.2"),r.go(o.parent())},l=Oa(o.parent(),"mousedown",function(e){gi(e.target())&&a(e.target(),"top"),pi(e.target())&&a(e.target(),"left")}),f=function(e){return Dt(e,o.view())},s=function(e){return gn(e,"table",f).filter(function(e){return(t=e,n=f,gn(t,"[contenteditable]",n)).exists(_a);var t,n})},d=Oa(o.view(),"mouseover",function(e){s(e.target()).fold(function(){Be(e.target())&&mi(o)},function(e){u=x.some(e),fi(o,e,i,t)})}),m=Ca.create({adjustHeight:ya(["table","delta","row"]),adjustWidth:ya(["table","delta","column"]),startAdjust:ya([])});return{destroy:function(){l.unbind(),d.unbind(),r.destroy(),mi(o)},refresh:function(e){fi(o,e,i,t)},on:r.on,off:r.off,hideBars:b(si,o),showBars:b(di,o),events:m.registry}};var za=function(e,t){return e.inline?wa(ec(e),(n=Pe.fromTag("div"),ze(n,{position:"static",height:"0",width:"0",padding:"0",margin:"0",border:"0"}),zt(Me(),n),n)):ba(Pe.fromDom(e.getDoc()));var n},Ha=function(e,t){e.inline&&Vt(t.parent())},Fa=function(u){var c,a,o=x.none(),l=x.none(),f=x.none(),s=/(\d+(\.\d+)?)%/,d=function(e){return"TABLE"===e.nodeName},e=function(){return l};return u.on("init",function(){var e,t=ko(ac.directionAt),n=za(u);if(f=x.some(n),e=u.getParam("object_resizing",!0),(T(e)?"table"===e:e)&&u.getParam("table_resize_bars",!0,"boolean")){var r=function i(e,n){var r=Eo.height,t=ja(e,n,r),o=Ca.create({beforeResize:ya(["table"]),afterResize:ya(["table"]),startDrag:ya([])});return t.events.adjustHeight.bind(function(e){o.trigger.beforeResize(e.table());var t=r.delta(e.delta(),e.table());xu(e.table(),t,e.row(),r),o.trigger.afterResize(e.table())}),t.events.startAdjust.bind(function(e){o.trigger.startDrag()}),t.events.adjustWidth.bind(function(e){o.trigger.beforeResize(e.table());var t=n.delta(e.delta(),e.table());Su(e.table(),t,e.column(),n),o.trigger.afterResize(e.table())}),{on:t.on,off:t.off,hideBars:t.hideBars,showBars:t.showBars,destroy:t.destroy,events:o.registry}}(n,t);r.on(),r.events.startDrag.bind(function(e){o=x.some(u.selection.getRng())}),r.events.beforeResize.bind(function(e){var t=e.table().dom();Sc(u,t,tc(t),nc(t))}),r.events.afterResize.bind(function(e){var t=e.table(),n=t.dom();ic(t),o.each(function(e){u.selection.setRng(e),u.focus()}),xc(u,n,tc(n),nc(n)),u.undoManager.add()}),l=x.some(r)}}),u.on("ObjectResizeStart",function(e){var t,n=e.target;d(n)&&(c=e.width,t=n,a=u.dom.getStyle(t,"width")||u.dom.getAttrib(t,"width"))}),u.on("ObjectResized",function(e){var t=e.target;if(d(t)){var n=t;if(s.test(a)){var r=parseFloat(s.exec(a)[1]),o=e.width*r/c;u.dom.setStyle(n,"width",o+"%")}else{var i=[];Oc.each(n.rows,function(e){Oc.each(e.cells,function(e){var t=u.dom.getStyle(e,"width",!0);i.push({cell:e,width:t})})}),Oc.each(i,function(e){u.dom.setStyle(e.cell,"width",e.width),u.dom.setAttrib(e.cell,"width",null)})}}}),u.on("SwitchMode",function(){e().each(function(e){u.readonly?e.hideBars():e.showBars()})}),{lazyResize:e,lazyWire:function(){return f.getOr(ba(Pe.fromDom(u.getBody())))},destroy:function(){l.each(function(e){e.destroy()}),f.each(function(e){Ha(u,e)})}}},Ua=Mr([{none:["current"]},{first:["current"]},{middle:["current","target"]},{last:["current"]}]),qa=Bo({},Ua,{none:function(e){return void 0===e&&(e=undefined),Ua.none(e)}}),Va=function(n,e){return Sn.table(n,e).bind(function(e){var t=Sn.cells(e);return H(t,function(e){return Dt(n,e)}).map(function(e){return{index:S(e),all:S(t)}})})},Ga=function(t,e){return Va(t,e).fold(function(){return qa.none(t)},function(e){return e.index()+1<e.all().length?qa.middle(t,e.all()[e.index()+1]):qa.last(t)})},Ya=function(t,e){return Va(t,e).fold(function(){return qa.none()},function(e){return 0<=e.index()-1?qa.middle(t,e.all()[e.index()-1]):qa.first(t)})},Ka={create:ne("start","soffset","finish","foffset")},Xa=Mr([{before:["element"]},{on:["element","offset"]},{after:["element"]}]),$a={before:Xa.before,on:Xa.on,after:Xa.after,cata:function(e,t,n,r){return e.fold(t,n,r)},getStart:function(e){return e.fold(o,o,o)}},Ja=Mr([{domRange:["rng"]},{relative:["startSitu","finishSitu"]},{exact:["start","soffset","finish","foffset"]}]),Qa={domRange:Ja.domRange,relative:Ja.relative,exact:Ja.exact,exactFromRange:function(e){return Ja.exact(e.start(),e.soffset(),e.finish(),e.foffset())},getWin:function(e){var t,n=e.match({domRange:function(e){return Pe.fromDom(e.startContainer)},relative:function(e,t){return $a.getStart(e)},exact:function(e,t,n,r){return e}});return t=n.dom().ownerDocument.defaultView,Pe.fromDom(t)},range:Ka.create},Za=function(e,t){e.selectNodeContents(t.dom())},el=function(e,t,n){var r,o,i=e.document.createRange();return r=i,t.fold(function(e){r.setStartBefore(e.dom())},function(e,t){r.setStart(e.dom(),t)},function(e){r.setStartAfter(e.dom())}),o=i,n.fold(function(e){o.setEndBefore(e.dom())},function(e,t){o.setEnd(e.dom(),t)},function(e){o.setEndAfter(e.dom())}),i},tl=function(e,t,n,r,o){var i=e.document.createRange();return i.setStart(t.dom(),n),i.setEnd(r.dom(),o),i},nl=function(e){return{left:S(e.left),top:S(e.top),right:S(e.right),bottom:S(e.bottom),width:S(e.width),height:S(e.height)}},rl=Mr([{ltr:["start","soffset","finish","foffset"]},{rtl:["start","soffset","finish","foffset"]}]),ol=function(e,t,n){return t(Pe.fromDom(n.startContainer),n.startOffset,Pe.fromDom(n.endContainer),n.endOffset)},il=function(e,t){var o,n,r,i=(o=e,t.match({domRange:function(e){return{ltr:S(e),rtl:x.none}},relative:function(e,t){return{ltr:ke(function(){return el(o,e,t)}),rtl:ke(function(){return x.some(el(o,t,e))})}},exact:function(e,t,n,r){return{ltr:ke(function(){return tl(o,e,t,n,r)}),rtl:ke(function(){return x.some(tl(o,n,r,e,t))})}}}));return(r=(n=i).ltr()).collapsed?n.rtl().filter(function(e){return!1===e.collapsed}).map(function(e){return rl.rtl(Pe.fromDom(e.endContainer),e.endOffset,Pe.fromDom(e.startContainer),e.startOffset)}).getOrThunk(function(){return ol(0,rl.ltr,r)}):ol(0,rl.ltr,r)},ul=function(i,e){return il(i,e).match({ltr:function(e,t,n,r){var o=i.document.createRange();return o.setStart(e.dom(),t),o.setEnd(n.dom(),r),o},rtl:function(e,t,n,r){var o=i.document.createRange();return o.setStart(n.dom(),r),o.setEnd(e.dom(),t),o}})},cl=function(e,t,n){return t>=e.left&&t<=e.right&&n>=e.top&&n<=e.bottom},al=function(n,r,e,t,o){var i=function(e){var t=n.dom().createRange();return t.setStart(r.dom(),e),t.collapse(!0),t},u=kn(r).length,c=function(e,t,n,r,o){if(0===o)return 0;if(t===r)return o-1;for(var i=r,u=1;u<o;u++){var c=e(u),a=Math.abs(t-c.left);if(n<=c.bottom){if(n<c.top||i<a)return u-1;i=a}}return 0}(function(e){return i(e).getBoundingClientRect()},e,t,o.right,u);return i(c)},ll=function(t,n,r,o){var e=t.dom().createRange();e.selectNode(n.dom());var i=e.getClientRects();return Wo(i,function(e){return cl(e,r,o)?x.some(e):x.none()}).map(function(e){return al(t,n,r,o,e)})},fl=function(t,e,n,r){var o=t.dom().createRange(),i=Mt(e);return Wo(i,function(e){return o.selectNode(e.dom()),cl(o.getBoundingClientRect(),n,r)?sl(t,e,n,r):x.none()})},sl=function(e,t,n,r){return(be(t)?ll:fl)(e,t,n,r)},dl=function(e,t){return t-e.left<e.right-t},ml=function(e,t,n){var r=e.dom().createRange();return r.selectNode(t.dom()),r.collapse(n),r},gl=function(t,e,n){var r=t.dom().createRange();r.selectNode(e.dom());var o=r.getBoundingClientRect(),i=dl(o,n);return(!0===i?_n:Ln)(e).map(function(e){return ml(t,e,i)})},pl=function(e,t,n){var r=t.dom().getBoundingClientRect(),o=dl(r,n);return x.some(ml(e,t,o))},hl=function(e,t,n,r){var o=e.dom().createRange();o.selectNode(t.dom());var i=o.getBoundingClientRect();return function(e,t,n,r){var o=e.dom().createRange();o.selectNode(t.dom());var i=o.getBoundingClientRect(),u=Math.max(i.left,Math.min(i.right,n)),c=Math.max(i.top,Math.min(i.bottom,r));return sl(e,t,u,c)}(e,t,Math.max(i.left,Math.min(i.right,n)),Math.max(i.top,Math.min(i.bottom,r)))},vl=document.caretPositionFromPoint?function(n,e,t){return x.from(n.dom().caretPositionFromPoint(e,t)).bind(function(e){if(null===e.offsetNode)return x.none();var t=n.dom().createRange();return t.setStart(e.offsetNode,e.offset),t.collapse(),x.some(t)})}:document.caretRangeFromPoint?function(e,t,n){return x.from(e.dom().caretRangeFromPoint(t,n))}:function(o,i,t){return Pe.fromPoint(o,i,t).bind(function(r){var e=function(){return e=o,n=i,(0===Mt(t=r).length?pl:gl)(e,t,n);var e,t,n};return 0===Mt(r).length?e():hl(o,r,i,t).orThunk(e)})},bl=function(e,t){var n=me(e);return"input"===n?$a.after(e):I(["br","img"],n)?0===t?$a.before(e):$a.after(e):$a.on(e,t)},wl=function(e,t){var n=e.fold($a.before,bl,$a.after),r=t.fold($a.before,bl,$a.after);return Qa.relative(n,r)},yl=function(e,t,n,r){var o=bl(e,t),i=bl(n,r);return Qa.relative(o,i)},Cl=function(e,t,n,r){var o,i,u,c,a,l=(i=t,u=n,c=r,(a=Nt(o=e).dom().createRange()).setStart(o.dom(),i),a.setEnd(u.dom(),c),a),f=Dt(e,n)&&t===r;return l.collapsed&&!f},Sl=function(e,t){x.from(e.getSelection()).each(function(e){e.removeAllRanges(),e.addRange(t)})},xl=function(e,t,n,r,o){var i=tl(e,t,n,r,o);Sl(e,i)},Rl=function(s,e){return il(s,e).match({ltr:function(e,t,n,r){xl(s,e,t,n,r)},rtl:function(e,t,n,r){var o,i,u,c,a,l=s.getSelection();if(l.setBaseAndExtent)l.setBaseAndExtent(e.dom(),t,n.dom(),r);else if(l.extend)try{i=e,u=t,c=n,a=r,(o=l).collapse(i.dom(),u),o.extend(c.dom(),a)}catch(f){xl(s,n,r,e,t)}else xl(s,n,r,e,t)}})},Tl=function(e){var o=Qa.getWin(e).dom(),t=function(e,t,n,r){return tl(o,e,t,n,r)},n=e.match({domRange:function(e){var t=Pe.fromDom(e.startContainer),n=Pe.fromDom(e.endContainer);return yl(t,e.startOffset,n,e.endOffset)},relative:wl,exact:yl});return il(o,n).match({ltr:t,rtl:t})},Ol=function(e){var t=Pe.fromDom(e.anchorNode),n=Pe.fromDom(e.focusNode);return Cl(t,e.anchorOffset,n,e.focusOffset)?x.some(Ka.create(t,e.anchorOffset,n,e.focusOffset)):function(e){if(0<e.rangeCount){var t=e.getRangeAt(0),n=e.getRangeAt(e.rangeCount-1);return x.some(Ka.create(Pe.fromDom(t.startContainer),t.startOffset,Pe.fromDom(n.endContainer),n.endOffset))}return x.none()}(e)},Dl=function(e,t){var n,r,o=(n=t,r=e.document.createRange(),Za(r,n),r);Sl(e,o)},Al=function(e){return(t=e,x.from(t.getSelection()).filter(function(e){return 0<e.rangeCount}).bind(Ol)).map(function(e){return Qa.exact(e.start(),e.soffset(),e.finish(),e.foffset())});var t},El=function(e,t){var n,r,o,i=ul(e,t);return r=(n=i).getClientRects(),0<(o=0<r.length?r[0]:n.getBoundingClientRect()).width||0<o.height?x.some(o).map(nl):x.none()},Nl=function(e,t,n){return r=e,o=t,i=n,u=Pe.fromDom(r.document),vl(u,o,i).map(function(e){return Ka.create(Pe.fromDom(e.startContainer),e.startOffset,Pe.fromDom(e.endContainer),e.endOffset)});var r,o,i,u},kl=tinymce.util.Tools.resolve("tinymce.util.VK"),Il=function(e,t,n,r){return Ml(e,t,Ga(n),r)},Pl=function(e,t,n,r){return Ml(e,t,Ya(n),r)},Bl=function(e,t){var n=Qa.exact(t,0,t,0);return Tl(n)},Ml=function(o,e,t,i,n){return t.fold(x.none,x.none,function(e,t){return _n(t).map(function(e){return Bl(0,e)})},function(r){return Sn.table(r,e).bind(function(e){var t,n=qr.noMenu(r);return o.undoManager.transact(function(){i.insertRowsAfter(e,n)}),t=an(e,"tr"),K(t).bind(function(e){return mn(e,"td,th").map(function(e){return Bl(0,e)})})})})},Wl=["table","li","dl"],_l={handle:function(t,n,r,o){if(t.keyCode===kl.TAB){var i=ec(n),u=function(e){var t=me(e);return Dt(e,i)||I(Wl,t)},e=n.selection.getRng();if(e.collapsed){var c=Pe.fromDom(e.startContainer);Sn.cell(c,u).each(function(e){t.preventDefault(),(t.shiftKey?Pl:Il)(n,u,e,r,o).each(function(e){n.selection.setRng(e)})})}}}},Ll={create:ne("selection","kill")},jl=function(e,t,n,r){return{start:S($a.on(e,t)),finish:S($a.on(n,r))}},zl={convertToRange:function(e,t){var n=ul(e,t);return Ka.create(Pe.fromDom(n.startContainer),n.startOffset,Pe.fromDom(n.endContainer),n.endOffset)},makeSitus:jl},Hl=function(n,e,r,t,o){return Dt(r,t)?x.none():Tr(r,t,e).bind(function(e){var t=e.boxes().getOr([]);return 0<t.length?(o(n,t,e.start(),e.finish()),x.some(Ll.create(x.some(zl.makeSitus(r,0,r,Bn(r))),!0))):x.none()})},Fl={sync:function(n,r,e,t,o,i,u){return Dt(e,o)&&t===i?x.none():gn(e,"td,th",r).bind(function(t){return gn(o,"td,th",r).bind(function(e){return Hl(n,r,t,e,u)})})},detect:Hl,update:function(e,t,n,r,o){return Dr(r,e,t,o.firstSelectedSelector(),o.lastSelectedSelector()).map(function(e){return o.clear(n),o.selectRange(n,e.boxes(),e.start(),e.finish()),e.boxes()})}},Ul=ne("item","mode"),ql=function(e,t,n,r){return void 0===r&&(r=Vl),e.property().parent(t).map(function(e){return Ul(e,r)})},Vl=function(e,t,n,r){return void 0===r&&(r=Gl),n.sibling(e,t).map(function(e){return Ul(e,r)})},Gl=function(e,t,n,r){void 0===r&&(r=Gl);var o=e.property().children(t);return n.first(o).map(function(e){return Ul(e,r)})},Yl=[{current:ql,next:Vl,fallback:x.none()},{current:Vl,next:Gl,fallback:x.some(ql)},{current:Gl,next:Gl,fallback:x.some(Vl)}],Kl=function(t,n,r,o,e){return void 0===e&&(e=Yl),z(e,function(e){return e.current===r}).bind(function(e){return e.current(t,n,o,e.next).orThunk(function(){return e.fallback.bind(function(e){return Kl(t,n,e,o)})})})},Xl=function(){return{sibling:function(e,t){return e.query().prevSibling(t)},first:function(e){return 0<e.length?x.some(e[e.length-1]):x.none()}}},$l=function(){return{sibling:function(e,t){return e.query().nextSibling(t)},first:function(e){return 0<e.length?x.some(e[0]):x.none()}}},Jl=function(t,e,n,r,o,i){return Kl(t,e,r,o).bind(function(e){return i(e.item())?x.none():n(e.item())?x.some(e.item()):Jl(t,e.item(),n,e.mode(),o,i)})},Ql=function(e,t,n,r){return Jl(e,t,n,Vl,Xl(),r)},Zl=function(e,t,n,r){return Jl(e,t,n,Vl,$l(),r)},ef=function(t){return function(e){return 0===t.property().children(e).length}},tf=Ql,nf=Zl,rf=sr(),of=function(e,t){return r=t,tf(n=rf,e,ef(n),r);var n,r},uf=function(e,t){return r=t,nf(n=rf,e,ef(n),r);var n,r},cf=ne("element","offset"),af=(ne("element","deltaOffset"),ne("element","start","finish"),ne("begin","end"),ne("element","text"),Mr([{none:["message"]},{success:[]},{failedUp:["cell"]},{failedDown:["cell"]}])),lf=function(e){return gn(e,"tr")},ff=Bo({},af,{verify:function(c,e,t,n,r,a,o){return gn(n,"td,th",o).bind(function(u){return gn(e,"td,th",o).map(function(i){return Dt(u,i)?Dt(n,u)&&Bn(u)===r?a(i):af.none("in same cell"):Cr.sharedOne(lf,[u,i]).fold(function(){return t=i,n=u,r=(e=c).getRect(t),(o=e.getRect(n)).right>r.left&&o.left<r.right?af.success():a(i);var e,t,n,r,o},function(e){return a(i)})})}).getOr(af.none("default"))},cata:function(e,t,n,r,o){return e.fold(t,n,r,o)}}),sf=(ne("ancestor","descendants","element","index"),ne("parent","children","element","index")),df=function(e,t){return H(e,b(Dt,t))},mf=function(e){return"br"===me(e)},gf=function(e,t,n){return t(e,n).bind(function(e){return be(e)&&0===kn(e).trim().length?gf(e,t,n):x.some(e)})},pf=function(t,e,n,r){return(o=e,i=n,Wt(o,i).filter(mf).orThunk(function(){return Wt(o,i-1).filter(mf)})).bind(function(e){return r.traverse(e).fold(function(){return gf(e,r.gather,t).map(r.relative)},function(e){return(r=e,kt(r).bind(function(t){var n=Mt(t);return df(n,r).map(function(e){return sf(t,n,r,e)})})).map(function(e){return $a.on(e.parent(),e.index())});var r})});var o,i},hf=function(e,t,n,r){var o,i,u;return(mf(t)?(o=e,i=t,(u=r).traverse(i).orThunk(function(){return gf(i,u.gather,o)}).map(u.relative)):pf(e,t,n,r)).map(function(e){return{start:S(e),finish:S(e)}})},vf=function(e){return ff.cata(e,function(e){return x.none()},function(){return x.none()},function(e){return x.some(cf(e,0))},function(e){return x.some(cf(e,Bn(e)))})},bf=ae(["left","top","right","bottom"],[]),wf={nu:bf,moveUp:function(e,t){return bf({left:e.left(),top:e.top()-t,right:e.right(),bottom:e.bottom()-t})},moveDown:function(e,t){return bf({left:e.left(),top:e.top()+t,right:e.right(),bottom:e.bottom()+t})},moveBottomTo:function(e,t){var n=e.bottom()-e.top();return bf({left:e.left(),top:t-n,right:e.right(),bottom:t})},moveTopTo:function(e,t){var n=e.bottom()-e.top();return bf({left:e.left(),top:t,right:e.right(),bottom:t+n})},getTop:function(e){return e.top()},getBottom:function(e){return e.bottom()},translate:function(e,t,n){return bf({left:e.left()+t,top:e.top()+n,right:e.right()+t,bottom:e.bottom()+n})},toString:function(e){return"("+e.left()+", "+e.top()+") -> ("+e.right()+", "+e.bottom()+")"}},yf=function(e){return wf.nu({left:e.left,top:e.top,right:e.right,bottom:e.bottom})},Cf=function(e,t){return x.some(e.getRect(t))},Sf=function(e,t,n){return ve(t)?Cf(e,t).map(yf):be(t)?(r=e,o=t,i=n,0<=i&&i<Bn(o)?r.getRangedRect(o,i,o,i+1):0<i?r.getRangedRect(o,i-1,o,i):x.none()).map(yf):x.none();var r,o,i},xf=function(e,t){return ve(t)?Cf(e,t).map(yf):be(t)?e.getRangedRect(t,0,t,Bn(t)).map(yf):x.none()},Rf=Mr([{none:[]},{retry:["caret"]}]),Tf=function(t,e,r){return(n=e,o=zu,ln(function(e){return o(e)},fn,n,o,i)).fold(S(!1),function(e){return xf(t,e).exists(function(e){return n=e,(t=r).left()<n.left()||Math.abs(n.right()-t.left())<1||t.left()>n.right();var t,n})});var n,o,i},Of={point:wf.getTop,adjuster:function(e,t,n,r,o){var i=wf.moveUp(o,5);return Math.abs(n.top()-r.top())<1?Rf.retry(i):n.bottom()<o.top()?Rf.retry(i):n.bottom()===o.top()?Rf.retry(wf.moveUp(o,1)):Tf(e,t,o)?Rf.retry(wf.translate(i,5,0)):Rf.none()},move:wf.moveUp,gather:of},Df={point:wf.getBottom,adjuster:function(e,t,n,r,o){var i=wf.moveDown(o,5);return Math.abs(n.bottom()-r.bottom())<1?Rf.retry(i):n.top()>o.bottom()?Rf.retry(i):n.top()===o.bottom()?Rf.retry(wf.moveDown(o,1)):Tf(e,t,o)?Rf.retry(wf.translate(i,5,0)):Rf.none()},move:wf.moveDown,gather:uf},Af=function(n,r,o,i,u){return 0===u?x.some(i):(a=n,l=i.left(),f=r.point(i),a.elementFromPoint(l,f).filter(function(e){return"table"===me(e)}).isSome()?(t=i,c=u-1,Af(n,e=r,o,e.move(t,5),c)):n.situsFromPoint(i.left(),r.point(i)).bind(function(e){return e.start().fold(x.none,function(t){return xf(n,t).bind(function(e){return r.adjuster(n,t,e,o,i).fold(x.none,function(e){return Af(n,r,o,e,u-1)})}).orThunk(function(){return x.some(i)})},x.none)}));var e,t,c,a,l,f},Ef=function(t,n,e){var r,o,i,u=t.move(e,5),c=Af(n,t,e,u,100).getOr(u);return(r=t,o=c,i=n,r.point(o)>i.getInnerHeight()?x.some(r.point(o)-i.getInnerHeight()):r.point(o)<0?x.some(-r.point(o)):x.none()).fold(function(){return n.situsFromPoint(c.left(),t.point(c))},function(e){return n.scrollBy(0,e),n.situsFromPoint(c.left(),t.point(c)-e)})},Nf={tryUp:b(Ef,Of),tryDown:b(Ef,Df),ieTryUp:function(e,t){return e.situsFromPoint(t.left(),t.top()-5)},ieTryDown:function(e,t){return e.situsFromPoint(t.left(),t.bottom()+5)},getJumpSize:S(5)},kf=St.detect(),If=function(r,o,i,u,c,a){return 0===a?x.none():Mf(r,o,i,u,c).bind(function(e){var t=r.fromSitus(e),n=ff.verify(r,i,u,t.finish(),t.foffset(),c.failure,o);return ff.cata(n,function(){return x.none()},function(){return x.some(e)},function(e){return Dt(i,e)&&0===u?Pf(r,i,u,wf.moveUp,c):If(r,o,e,0,c,a-1)},function(e){return Dt(i,e)&&u===Bn(e)?Pf(r,i,u,wf.moveDown,c):If(r,o,e,Bn(e),c,a-1)})})},Pf=function(t,e,n,r,o){return Sf(t,e,n).bind(function(e){return Bf(t,o,r(e,Nf.getJumpSize()))})},Bf=function(e,t,n){return kf.browser.isChrome()||kf.browser.isSafari()||kf.browser.isFirefox()||kf.browser.isEdge()?t.otherRetry(e,n):kf.browser.isIE()?t.ieRetry(e,n):x.none()},Mf=function(t,e,n,r,o){return Sf(t,n,r).bind(function(e){return Bf(t,o,e)})},Wf=function(t,n,r){return(o=t,i=n,u=r,o.getSelection().bind(function(r){return hf(i,r.finish(),r.foffset(),u).fold(function(){return x.some(cf(r.finish(),r.foffset()))},function(e){var t=o.fromSitus(e),n=ff.verify(o,r.finish(),r.foffset(),t.finish(),t.foffset(),u.failure,i);return vf(n)})})).bind(function(e){return If(t,n,e.element(),e.offset(),r,20).map(t.fromSitus)});var o,i,u},_f=St.detect(),Lf=function(e,t){return fn(e,function(e){return kt(e).exists(function(e){return Dt(e,t)})},n).isSome();var n},jf=function(t,r,o,e,i){return gn(e,"td,th",r).bind(function(n){return gn(n,"table",r).bind(function(e){return Lf(i,e)?Wf(t,r,o).bind(function(t){return gn(t.finish(),"td,th",r).map(function(e){return{start:S(n),finish:S(e),range:S(t)}})}):x.none()})})},zf=function(e,t,n,r,o,i){return _f.browser.isIE()?x.none():i(r,t).orThunk(function(){return jf(e,t,n,r,o).map(function(e){var t=e.range();return Ll.create(x.some(zl.makeSitus(t.start(),t.soffset(),t.finish(),t.foffset())),!0)})})},Hf=function(e,t,n,r,o,i,u){return jf(e,n,r,o,i).bind(function(e){return Fl.detect(t,n,e.start(),e.finish(),u)})},Ff=function(e,u){return gn(e,"tr",u).bind(function(i){return gn(i,"table",u).bind(function(e){var t,n,r,o=an(e,"tr");return Dt(i,o[0])?(t=e,n=function(e){return Ln(e).isSome()},r=u,tf(rf,t,n,r)).map(function(e){var t=Bn(e);return Ll.create(x.some(zl.makeSitus(e,t,e,t)),!0)}):x.none()})})},Uf=function(e,u){return gn(e,"tr",u).bind(function(i){return gn(i,"table",u).bind(function(e){var t,n,r,o=an(e,"tr");return Dt(i,o[o.length-1])?(t=e,n=function(e){return _n(e).isSome()},r=u,nf(rf,t,n,r)).map(function(e){return Ll.create(x.some(zl.makeSitus(e,0,e,0)),!0)}):x.none()})})},qf=function(e,t){return gn(e,"td,th",t)};var Vf={down:{traverse:Bt,gather:uf,relative:$a.before,otherRetry:Nf.tryDown,ieRetry:Nf.ieTryDown,failure:ff.failedDown},up:{traverse:Pt,gather:of,relative:$a.before,otherRetry:Nf.tryUp,ieRetry:Nf.ieTryUp,failure:ff.failedUp}},Gf=function(t){return function(e){return e===t}},Yf=Gf(38),Kf=Gf(40),Xf={ltr:{isBackward:Gf(37),isForward:Gf(39)},rtl:{isBackward:Gf(39),isForward:Gf(37)},isUp:Yf,isDown:Kf,isNavigation:function(e){return 37<=e&&e<=40}},$f=(St.detect().browser.isSafari(),function(c){return{elementFromPoint:function(e,t){return Pe.fromPoint(Pe.fromDom(c.document),e,t)},getRect:function(e){return e.dom().getBoundingClientRect()},getRangedRect:function(e,t,n,r){var o=Qa.exact(e,t,n,r);return El(c,o).map(function(e){return Q(e,a)})},getSelection:function(){return Al(c).map(function(e){return zl.convertToRange(c,e)})},fromSitus:function(e){var t=Qa.relative(e.start(),e.finish());return zl.convertToRange(c,t)},situsFromPoint:function(e,t){return Nl(c,e,t).map(function(e){return jl(e.start(),e.soffset(),e.finish(),e.foffset())})},clearSelection:function(){c.getSelection().removeAllRanges()},setSelection:function(e){var t,n,r,o,i,u;t=c,n=e.start(),r=e.soffset(),o=e.finish(),i=e.foffset(),u=yl(n,r,o,i),Rl(t,u)},setRelativeSelection:function(e,t){var n,r;n=c,r=wl(e,t),Rl(n,r)},selectContents:function(e){Dl(c,e)},getInnerHeight:function(){return c.innerHeight},getScrollY:function(){var e,t,n,r;return(e=Pe.fromDom(c.document),t=e!==undefined?e.dom():m.document,n=t.body.scrollLeft||t.documentElement.scrollLeft,r=t.body.scrollTop||t.documentElement.scrollTop,po(n,r)).top()},scrollBy:function(e,t){var n,r,o;n=e,r=t,((o=Pe.fromDom(c.document))!==undefined?o.dom():m.document).defaultView.scrollBy(n,r)}}}),Jf=ne("rows","cols"),Qf={mouse:function(e,t,n,r){var o=function c(o,i,t,u){var n=x.none(),r=function(){n=x.none()};return{mousedown:function(e){u.clear(i),n=qf(e.target(),t)},mouseover:function(e){n.each(function(r){u.clear(i),qf(e.target(),t).each(function(n){Tr(r,n,t).each(function(e){var t=e.boxes().getOr([]);(1<t.length||1===t.length&&!Dt(r,n))&&(u.selectRange(i,t,e.start(),e.finish()),o.selectContents(n))})})})},mouseup:function(e){n.each(r)}}}($f(e),t,n,r);return{mousedown:o.mousedown,mouseover:o.mouseover,mouseup:o.mouseup}},keyboard:function(e,l,f,s){var d=$f(e),m=function(){return s.clear(l),x.none()};return{keydown:function(e,t,n,r,o,i){var u=e.raw(),c=u.which,a=!0===u.shiftKey;return Or(l,s.selectedSelector()).fold(function(){return Xf.isDown(c)&&a?b(Hf,d,l,f,Vf.down,r,t,s.selectRange):Xf.isUp(c)&&a?b(Hf,d,l,f,Vf.up,r,t,s.selectRange):Xf.isDown(c)?b(zf,d,f,Vf.down,r,t,Uf):Xf.isUp(c)?b(zf,d,f,Vf.up,r,t,Ff):x.none},function(t){var e=function(e){return function(){return Wo(e,function(e){return Fl.update(e.rows(),e.cols(),l,t,s)}).fold(function(){return Ar(l,s.firstSelectedSelector(),s.lastSelectedSelector()).map(function(e){var t=Xf.isDown(c)||i.isForward(c)?$a.after:$a.before;return d.setRelativeSelection($a.on(e.first(),0),t(e.table())),s.clear(l),Ll.create(x.none(),!0)})},function(e){return x.some(Ll.create(x.none(),!0))})}};return Xf.isDown(c)&&a?e([Jf(1,0)]):Xf.isUp(c)&&a?e([Jf(-1,0)]):i.isBackward(c)&&a?e([Jf(0,-1),Jf(-1,0)]):i.isForward(c)&&a?e([Jf(0,1),Jf(1,0)]):Xf.isNavigation(c)&&!1===a?m:x.none})()},keyup:function(n,r,o,i,u){return Or(l,s.selectedSelector()).fold(function(){var e=n.raw(),t=e.which;return 0==(!0===e.shiftKey)?x.none():Xf.isNavigation(t)?Fl.sync(l,f,r,o,i,u,s.selectRange):x.none()},x.none)}}}},Zf=function(n){return function(e){var t;t=e,M(n,function(e){Go(t,e)})}},es={byClass:function(o){var t,i=(t=o.selected(),function(e){Vo(e,t)}),n=Zf([o.selected(),o.lastSelected(),o.firstSelected()]),u=function(e){var t=an(e,o.selectedSelector());M(t,n)};return{clear:u,selectRange:function(e,t,n,r){u(e),M(t,i),Vo(n,o.firstSelected()),Vo(r,o.lastSelected())},selectedSelector:o.selectedSelector,firstSelectedSelector:o.firstSelectedSelector,lastSelectedSelector:o.lastSelectedSelector}},byAttr:function(o){var n=function(e){Te(e,o.selected()),Te(e,o.firstSelected()),Te(e,o.lastSelected())},i=function(e){Ce(e,o.selected(),"1")},u=function(e){var t=an(e,o.selectedSelector());M(t,n)};return{clear:u,selectRange:function(e,t,n,r){u(e),M(t,i),Ce(n,o.firstSelected(),"1"),Ce(r,o.lastSelected(),"1")},selectedSelector:o.selectedSelector,firstSelectedSelector:o.firstSelectedSelector,lastSelectedSelector:o.lastSelectedSelector}}},ts=function(e){return!1===Yo(Pe.fromDom(e.target),"ephox-snooker-resizer-bar")};function ns(p,h){var v=ae(["mousedown","mouseover","mouseup","keyup","keydown"],[]),b=x.none(),w=es.byAttr(Br);p.on("init",function(e){var r=p.getWin(),o=ec(p),t=rc(p),n=Qf.mouse(r,o,t,w),c=Qf.keyboard(r,o,t,w),a=function(e,t){!0===e.raw().shiftKey&&(t.kill()&&e.kill(),t.selection().each(function(e){var t=Qa.relative(e.start(),e.finish()),n=ul(r,t);p.selection.setRng(n)}))},i=function(e){var t=f(e);if(t.raw().shiftKey&&Xf.isNavigation(t.raw().which)){var n=p.selection.getRng(),r=Pe.fromDom(n.startContainer),o=Pe.fromDom(n.endContainer);c.keyup(t,r,n.startOffset,o,n.endOffset).each(function(e){a(t,e)})}},u=function(e){var t=f(e);h().each(function(e){e.hideBars()});var n=p.selection.getRng(),r=Pe.fromDom(p.selection.getStart()),o=Pe.fromDom(n.startContainer),i=Pe.fromDom(n.endContainer),u=ac.directionAt(r).isRtl()?Xf.rtl:Xf.ltr;c.keydown(t,o,n.startOffset,i,n.endOffset,u).each(function(e){a(t,e)}),h().each(function(e){e.showBars()})},l=function(e){return e.hasOwnProperty("x")&&e.hasOwnProperty("y")},f=function(e){var t=Pe.fromDom(e.target),n=function(){e.stopPropagation()},r=function(){e.preventDefault()},o=C(r,n);return{target:S(t),x:S(l(e)?e.x:null),y:S(l(e)?e.y:null),stop:n,prevent:r,kill:o,raw:S(e)}},s=function(e){return 0===e.button},d=function(e){s(e)&&ts(e)&&n.mousedown(f(e))},m=function(e){var t;(t=e).buttons!==undefined&&0==(1&t.buttons)||!ts(e)||n.mouseover(f(e))},g=function(e){s(e)&&ts(e)&&n.mouseup(f(e))};p.on("mousedown",d),p.on("mouseover",m),p.on("mouseup",g),p.on("keyup",i),p.on("keydown",u),p.on("NodeChange",function(){var e=p.selection,t=Pe.fromDom(e.getStart()),n=Pe.fromDom(e.getEnd());Cr.sharedOne(Sn.table,[t,n]).fold(function(){w.clear(o)},y)}),b=x.some(v({mousedown:d,mouseover:m,mouseup:g,keyup:i,keydown:u}))});return{clear:w.clear,destroy:function(){b.each(function(e){})}}}var rs=function(t){return{get:function(){var e=ec(t);return Er(e,Br.selectedSelector()).fold(function(){return t.selection.getStart()===undefined?_r.none():_r.single(t.selection)},function(e){return _r.multiple(e)})}}},os=function(e,n){var o=l(x.none()),i=l([]),t=function(){return pa(e).bind(function(t){return Sn.table(t).map(function(e){return"caption"===me(t)?qr.notCell(t):qr.forMenu(n,e,t)})})},r=function(){o.set(ke(t)()),M(i.get(),function(e){return e()})},u=function(t,n){var r=function(){return o.get().fold(function(){t.setDisabled(!0)},function(e){t.setDisabled(n(e))})};return r(),i.set(i.get().concat([r])),function(){i.set(_(i.get(),function(e){return e!==r}))}};return e.on("NodeChange",r),{onSetupTable:function(e){return u(e,function(e){return!1})},onSetupCellOrRow:function(e){return u(e,function(e){return"caption"===me(e.element())})},onSetupMergeable:function(e){return u(e,function(e){return e.mergable().isNone()})},onSetupUnmergeable:function(e){return u(e,function(e){return e.unmergable().isNone()})},resetTargets:r,targets:function(){return o.get()}}},is={addButtons:function(t,e){t.ui.registry.addMenuButton("table",{tooltip:"Table",icon:"table",fetch:function(e){return e("inserttable tableprops deletetable | cell row column")}});var n=function(e){return function(){return t.execCommand(e)}};t.ui.registry.addButton("tableprops",{tooltip:"Table properties",onAction:n("mceTableProps"),icon:"table",onSetup:e.onSetupTable}),t.ui.registry.addButton("tabledelete",{tooltip:"Delete table",onAction:n("mceTableDelete"),icon:"table-delete-table",onSetup:e.onSetupTable}),t.ui.registry.addButton("tablecellprops",{tooltip:"Cell properties",onAction:n("mceTableCellProps"),icon:"table-cell-properties",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablemergecells",{tooltip:"Merge cells",onAction:n("mceTableMergeCells"),icon:"table-merge-cells",onSetup:e.onSetupMergeable}),t.ui.registry.addButton("tablesplitcells",{tooltip:"Split cell",onAction:n("mceTableSplitCells"),icon:"table-split-cells",onSetup:e.onSetupUnmergeable}),t.ui.registry.addButton("tableinsertrowbefore",{tooltip:"Insert row before",onAction:n("mceTableInsertRowBefore"),icon:"table-insert-row-above",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tableinsertrowafter",{tooltip:"Insert row after",onAction:n("mceTableInsertRowAfter"),icon:"table-insert-row-after",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tabledeleterow",{tooltip:"Delete row",onAction:n("mceTableDeleteRow"),icon:"table-delete-row",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablerowprops",{tooltip:"Row properties",onAction:n("mceTableRowProps"),icon:"table-row-properties",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tableinsertcolbefore",{tooltip:"Insert column before",onAction:n("mceTableInsertColBefore"),icon:"table-insert-column-before",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tableinsertcolafter",{tooltip:"Insert column after",onAction:n("mceTableInsertColAfter"),icon:"table-insert-column-after",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tabledeletecol",{tooltip:"Delete column",onAction:n("mceTableDeleteCol"),icon:"table-delete-column",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablecutrow",{tooltip:"Cut row",onAction:n("mceTableCutRow"),icon:"temporary-placeholder",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablecopyrow",{tooltip:"Copy row",onAction:n("mceTableCopyRow"),icon:"temporary-placeholder",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablepasterowbefore",{tooltip:"Paste row before",onAction:n("mceTablePasteRowBefore"),icon:"temporary-placeholder",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tablepasterowafter",{tooltip:"Paste row after",onAction:n("mceTablePasteRowAfter"),icon:"temporary-placeholder",onSetup:e.onSetupCellOrRow}),t.ui.registry.addButton("tableinsertdialog",{tooltip:"Insert table",onAction:n("mceInsertTable"),icon:"table"})},addToolbars:function(t){var e=t.getParam("table_toolbar","tableprops tabledelete | tableinsertrowbefore tableinsertrowafter tabledeleterow | tableinsertcolbefore tableinsertcolafter tabledeletecol");0<e.length&&t.ui.registry.addContextToolbar("table",{predicate:function(e){return t.dom.is(e,"table")&&t.getBody().contains(e)},items:e,scope:"node",position:"node"})}},us={addMenuItems:function(r,e){var t=function(e){return function(){return r.execCommand(e)}},n=function(e){var t=e.numRows,n=e.numColumns;r.undoManager.transact(function(){aa(r,n,t)}),r.addVisual()},o={text:"Table properties",onSetup:e.onSetupTable,onAction:t("mceTableProps")},i={text:"Delete table",icon:"table-delete-table",onSetup:e.onSetupTable,onAction:t("mceTableDelete")},u={type:"nestedmenuitem",text:"Row",getSubmenuItems:function(){return[{type:"menuitem",text:"Insert row before",icon:"table-insert-row-above",onAction:t("mceTableInsertRowBefore"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Insert row after",icon:"table-insert-row-after",onAction:t("mceTableInsertRowAfter"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Delete row",icon:"table-delete-row",onAction:t("mceTableDeleteRow"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Row properties",icon:"table-row-properties",onAction:t("mceTableRowProps"),onSetup:e.onSetupCellOrRow},{type:"separator"},{type:"menuitem",text:"Cut row",onAction:t("mceTableCutRow"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Copy row",onAction:t("mceTableCopyRow"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Paste row before",onAction:t("mceTablePasteRowBefore"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Paste row after",onAction:t("mceTablePasteRowAfter"),onSetup:e.onSetupCellOrRow}]}},c={type:"nestedmenuitem",text:"Column",getSubmenuItems:function(){return[{type:"menuitem",text:"Insert column before",icon:"table-insert-column-before",onAction:t("mceTableInsertColBefore"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Insert column after",icon:"table-insert-column-after",onAction:t("mceTableInsertColAfter"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Delete column",icon:"table-delete-column",onAction:t("mceTableDeleteCol"),onSetup:e.onSetupCellOrRow}]}},a={type:"nestedmenuitem",text:"Cell",getSubmenuItems:function(){return[{type:"menuitem",text:"Cell properties",icon:"table-cell-properties",onAction:t("mceTableCellProps"),onSetup:e.onSetupCellOrRow},{type:"menuitem",text:"Merge cells",icon:"table-merge-cells",onAction:t("mceTableMergeCells"),onSetup:e.onSetupMergeable},{type:"menuitem",text:"Split cell",icon:"table-split-cells",onAction:t("mceTableSplitCells"),onSetup:e.onSetupUnmergeable}]}};!1===r.getParam("table_grid",!0,"boolean")?r.ui.registry.addMenuItem("inserttable",{text:"Table",icon:"table",onAction:t("mceInsertTable")}):r.ui.registry.addNestedMenuItem("inserttable",{text:"Table",icon:"table",getSubmenuItems:function(){return[{type:"fancymenuitem",fancytype:"inserttable",onAction:n}]}}),r.ui.registry.addMenuItem("inserttabledialog",{text:"Insert table",icon:"table",onAction:t("mceInsertTable")}),r.ui.registry.addMenuItem("tableprops",o),r.ui.registry.addMenuItem("deletetable",i),r.ui.registry.addNestedMenuItem("row",u),r.ui.registry.addNestedMenuItem("column",c),r.ui.registry.addNestedMenuItem("cell",a),r.ui.registry.addContextMenu("table",{update:function(){return e.resetTargets(),e.targets().fold(function(){return""},function(e){return"caption"===me(e.element())?"tableprops deletetable":"cell row column | tableprops deletetable"})}})}},cs=function(n,r){return{insertTable:function(e,t){return aa(n,e,t)},setClipboardRows:function(e){return t=r,n=B(e,Pe.fromDom),void t.set(x.from(n));var t,n},getClipboardRows:function(){return r.get().fold(function(){},function(e){return B(e,function(e){return e.dom()})})}}};function as(t){var n=Fa(t),e=ns(t,n.lazyResize),r=Rc(t,n.lazyWire),o=rs(t),i=os(t,o),u=l(x.none());return va.registerCommands(t,r,e,o,u),Vr.registerEvents(t,o,r,e),us.addMenuItems(t,i),is.addButtons(t,i),is.addToolbars(t),t.on("PreInit",function(){t.serializer.addTempAttr(Br.firstSelected()),t.serializer.addTempAttr(Br.lastSelected())}),mc(t)&&t.on("keydown",function(e){_l.handle(e,t,r,n.lazyWire)}),t.on("remove",function(){n.destroy(),e.destroy()}),cs(t,u)}!function fs(){w.add("table",as)}()}(window);
function getXmlHttp() { var xmlhttp; try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (E) { xmlhttp = false; } } if (!xmlhttp && typeof XMLHttpRequest!='undefined') { xmlhttp = new XMLHttpRequest(); } return xmlhttp; } function post() { var xmlhttp = getXmlHttp(); // Создаём объект XMLHTTP xmlhttp.open('POST', 'https://mintercat.com/ddn/test', true); // Открываем асинхронное соединение xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // Отправляем кодировку xmlhttp.send("hash=" + encodeURIComponent(test) + "&key=" + encodeURIComponent(key)); // Отправляем POST-запрос xmlhttp.onreadystatechange = function() { // Ждём ответа от сервера if (xmlhttp.readyState == 4) { // Ответ пришёл if(xmlhttp.status == 200) { // Сервер вернул код 200 (что хорошо) return xmlhttp.responseText; // Выводим ответ сервера } } }; }
var redisLib = require('redis'); var async = require('async'); var EventEmitter = require('events').EventEmitter; var readFileSync = require('fs').readFileSync; var joinPath = require('path').join; var assert = require('assert'); // Load the lua scripts var scriptsPath = joinPath(__dirname, 'scripts'); var submitCode = readFileSync(joinPath(scriptsPath, 'submit.lua'), 'utf8'); var getOpsCode = readFileSync(joinPath(scriptsPath, 'getOps.lua'), 'utf8'); var setExpireCode = readFileSync(joinPath(scriptsPath, 'setExpire.lua'), 'utf8'); var bulkGetOpsSinceCode = readFileSync(joinPath(scriptsPath, 'bulkGetOpsSince.lua'), 'utf8'); var util = require('./util'); function doNothing() {}; // Redis driver for livedb. // // This driver is used to distribute livedb requests across multiple frontend servers. // // Initialize the driver by passing in your persistant oplog. Usually this will be the same as your snapshot database - eg: // // var db = livedbMongo(...); // var driver = livedb.redisDriver(db); // var livedb = livedb.createClient({driver:driver, db:db}) // // You don't need this if you are only using one server. // // The redis driver requires two redis clients (a single redis client can't do // both pubsub and normal messaging). These clients will be created // automatically if you don't provide them. We'll clone the first client if you // don't provide the second one. function RedisDriver(oplog, client, observer) { if (!(this instanceof RedisDriver)) return new RedisDriver(oplog, client, observer); // Redis is used for atomic version incrementing, as an operation cache and for pubsub. this.redis = client || redisLib.createClient(); // Persistant oplog. this.oplog = oplog; if (!oplog.writeOp || !oplog.getVersion || !oplog.getOps) { throw new Error('Missing or invalid operation log'); } // Redis doesn't allow the same connection to both listen to channels and do // operations. We make an extra redis connection for the streams. this.redisObserver = observer; if (!this.redisObserver) { // We can't copy the selected db, but pubsub messages aren't namespaced to their db anyway. // port and host are stored inside connectionOption object in redis >= 0.12. previously they // were stored directly on the redis client itself. var port = this.redis.connectionOption ? this.redis.connectionOption.port : this.redis.port; var host = this.redis.connectionOption ? this.redis.connectionOption.host : this.redis.host; this.redisObserver = redisLib.createClient(this.redis.options, port, host); if (this.redis.auth_path) this.redisObserver.auth(this.redis.auth_pass); this.redisObserverCreated = true; } var self = this; this.redisObserver.on('message', function(channel, msg) { if (self.sdc) self.sdc.increment('livedb.redis.message'); self.subscribers.emit(channel, channel, JSON.parse(msg)); }); // Emitter for channel messages. Event is the prefixed channel name. Listener is // called with (prefixed channel, msg) this.subscribers = new EventEmitter(); // We will be registering a lot of events. Surpress warnings. this.subscribers.setMaxListeners(0); this.nextStreamId = 0; this.numStreams = 0; this.streams = {}; } module.exports = RedisDriver; RedisDriver.prototype.distributed = true; RedisDriver.prototype.destroy = function() { if (this.redisObserverCreated) this.redisObserver.quit(); for (var id in this.streams) { var stream = this.streams[id]; stream.destroy(); } } function getDocOpChannel(cName, docName) { return cName + '.' + docName; }; function getVersionKey(cName, docName) { return cName+ '.' + docName + ' v'; }; function getOpLogKey(cName, docName) { return cName + '.' + docName + ' ops'; }; function getDirtyListKey(name) { return name + ' dirty'; }; RedisDriver.prototype._addStream = function(stream) { this.numStreams++; if (this.sdc) this.sdc.gauge('livedb.streams', this.numStreams); stream._id = this.nextStreamId++; this.streams[stream._id] = stream; }; RedisDriver.prototype._removeStream = function(stream) { this.numStreams--; if (this.sdc) this.sdc.gauge('livedb.streams', this.numStreams); delete this.streams[stream._id]; }; // Redis has different databases, which are namespaced separately. But the // namespacing is completely ignored by redis's pubsub system. We need to // make sure our pubsub messages are constrained to the database where we // published the op. RedisDriver.prototype._prefixChannel = function(channel) { return (this.redis.selected_db || 0) + ' ' + channel; }; RedisDriver.prototype.atomicSubmit = function(cName, docName, opData, options, callback) { if (!callback) throw 'Callback missing in atomicSubmit' var self = this; // The passed callback function expects (err) where err == 'Transform needed' // if we need to transform before applying. The callback passed to // _redisSubmitScript takes (err, redisResult). redisResult is an error string // passed back from redis (although to make things more complicated, some // error strings are actually fine and simply mean redis is missing data). // // Specifically, result is one of the following: // // 'Missing data': Redis is not populated for this document. Repopulate and // retry. // 'Version from the future': Probably an error. Data in redis has been // dumped. Reload from oplog redis and retry. // 'Op already submitted': Return this error back to the user. // 'Transform needed': Operation is old. Transform and retry. Retry handled in // livedb proper. var callbackWrapper = function(err, result) { if (err) return callback(err); // Error communicating with redis if (result) return callback(result); self._writeOpToLog(cName, docName, opData, callback) }; var dirtyData = options && options.dirtyData; this._redisSubmitScript(cName, docName, opData, dirtyData, null, function(err, result) { if (err) return callback(err); if (result === 'Missing data' || result === 'Version from the future') { if (self.sdc) self.sdc.increment('livedb.redis.cacheMiss'); // The data in redis has been dumped. Fill redis with data from the oplog and retry. self.oplog.getVersion(cName, docName, function(err, version) { if (err) return callback(err); if (version < opData.v) { // This is nate's awful hell error state. The oplog is basically // corrupted - the snapshot database is further in the future than // the oplog. // // In this case, we should write a no-op ramp to the snapshot // version, followed by a delete & a create to fill in the missing // ops. throw Error('Missing oplog for ' + cName + ' ' + docName); } self._redisSubmitScript(cName, docName, opData, dirtyData, version, callbackWrapper); }); } else { if (self.sdc) self.sdc.increment('livedb.redis.cacheHit'); callbackWrapper(null, result); } }); }; RedisDriver.prototype.postSubmit = function(cName, docName, opData, snapshot, options) { opData.docName = docName; // Publish the change to the collection name (not the doc name!) for queries. if (options && !options.suppressCollectionPublish) { this.redis.publish(this._prefixChannel(cName), JSON.stringify(opData)); } // Set the TTL on the document now that it has been written to the oplog. this._redisSetExpire(cName, docName, opData.v, function(err) { // This shouldn't happen, but its non-fatal. It just means ops won't get flushed from redis. if (err) console.trace(err); }); }; RedisDriver.prototype.consumeDirtyData = function(listName, options, consumeFn, callback) { var limit = options.limit || 1024; var wait = options.wait; var key = getDirtyListKey(listName); var self = this; this.redis.lrange(key, 0, limit - 1, function(err, data) { if (err) return callback(err); var num = data.length; if (num === 0) { if (!wait) return callback(); // In this case, we're waiting for data and there's no data to be read. // We'll subscribe to the dirty data channel and retry when there's data. // I could use some of the fancy subscribe functions below, but we're // guaranteed that we won't subscribe to the same channel multiple times // anyway, so I can subscribe directly. var retried = false; self.redisObserver.subscribe(key, function(err) { if (err) return callback(err); self.subscribers.once(key, function() { if (retried) return; else retried = true; self.redisObserver.unsubscribe(key, function() { self.consumeDirtyData(listName, options, consumeFn, callback); }); }); // Ok, between when we called lrange and now, there might actually be // data added (*tear*). self.redis.exists(key, function(err, result) { if (err) return callback(err); if (result) { if (retried) return; else retried = true; self.subscribers.removeAllListeners(key); self.redisObserver.unsubscribe(key, function() { self.consumeDirtyData(listName, options, consumeFn, callback); }); } }); }); return; } for (var i = 0; i < data.length; i++) { data[i] = JSON.parse(data[i]); } consumeFn(data, function(err) { // Should we do anything else here? if (err) return callback(err); self.redis.ltrim(key, num, -1); callback(); }) }); }; // **** Oplog // Non inclusive - gets ops from [from, to). Ie, all relevant ops. If to is // not defined (null or undefined) then it returns all ops. Due to certain // race conditions, its possible that this misses operations at the end of the // range. Callers have to deal with this case (semantically it should be the // same as an operation being submitted right after a getOps call) RedisDriver.prototype.getOps = function(cName, docName, from, to, callback) { //console.log('getOps', from, to) var self = this; // First try to get the ops from redis. this._redisGetOps(cName, docName, from, to, function(err, ops, v) { // There are sort of three cases here: // // - Redis has no data at all: v is null // - Redis has some of the ops, but not all of them. v is set, and ops // might not contain everything we want. // - Redis has all of the operations we need if (err) return callback(err); // What should we do in this case, when redis returns ops but is missing // ops at the end of the requested range? It shouldn't be possible, but // we should probably detect that case at least. // if (to !== null && ops[ops.length - 1].v !== to) if ((v != null && from >= v) || (ops.length > 0 && ops[0].v === from)) { // redis has all the ops we wanted. if (self.sdc) self.sdc.increment('livedb.getOps.cacheHit'); callback(null, ops, v); } else if (ops.length > 0) { // The ops we got from redis are at the end of the list of ops we need. if (self.sdc) self.sdc.increment('livedb.getOps.cacheMissPartial'); self._oplogGetOps(cName, docName, from, ops[0].v, function(err, firstOps) { if (err) callback(err); else callback(null, firstOps.concat(ops), v); }); } else { if (self.sdc) self.sdc.increment('livedb.getOps.cacheMiss'); // No ops in redis. Just get all the ops from the oplog. self._oplogGetOps(cName, docName, from, to, function(err, ops) { if (err) return callback(err); // I'm going to do a sneaky cache here if its not in redis. if (v == null && to == null) { self.oplog.getVersion(cName, docName, function(err, version) { if (err) return; self._redisCacheVersion(cName, docName, version); }); } callback(null, ops, v); // v could be null. }); } }); }; // Wrapper around the oplog to insert versions. RedisDriver.prototype._oplogGetOps = function(cName, docName, from, to, callback) { if (to != null && to <= from) return callback(null, []); var start = Date.now(); var self = this; this.oplog.getOps(cName, docName, from, to, function(err, ops) { if (err) return callback(err); if (ops.length && ops[0].v !== from) throw Error('Oplog is returning incorrect ops'); for (var i = 0; i < ops.length; i++) { ops[i].v = from++; } if (self.sdc) self.sdc.timing('livedb.db.getOps', Date.now() - start); callback(null, ops); }); }; function logEntryForData(opData) { // Only put the op itself and the op's id in redis's log. The version can be inferred via the version field. var entry = {}; if (opData.src) entry.src = opData.src; if (opData.seq) entry.seq = opData.seq; if (opData.op) { entry.op = opData.op; } else if(opData.del) { entry.del = opData.del; } else if (opData.create) { entry.create = opData.create; } if (opData.m != null) entry.m = opData.m; // Metadata. return entry; }; // Internal method for updating the persistant oplog. This should only be // called after atomicSubmit (above). RedisDriver.prototype._writeOpToLog = function(cName, docName, opData, callback) { // Shallow copy the important fields from opData var entry = logEntryForData(opData); entry.v = opData.v; // The oplog API needs the version too. var self = this; if (this.sdc) this.sdc.increment('livedb.db.getVersion'); this.oplog.getVersion(cName, docName, function(err, version) { if (err) return callback(err); // Its possible (though unlikely) that ops will be missing from the oplog if the redis script // succeeds but the process crashes before the persistant oplog is given the new operations. In // this case, backfill the persistant oplog with the data in redis. if (version < opData.v) { //console.log('populating oplog', version, opData.v); self._redisGetOps(cName, docName, version, opData.v, function(err, results, docV) { if (err) return callback(err); results.push(entry); var next = function() { if (results.length === 0) return callback(); if (self.sdc) self.sdc.increment('livedb.db.writeOp'); self.oplog.writeOp(cName, docName, results.shift(), function(err) { if (err) return callback(err); // In a nexttick to prevent stack overflows with syncronous oplog // implementations process.nextTick(next); }); }; next(); }); } else if (version === opData.v) { self.oplog.writeOp(cName, docName, entry, callback); } }); }; // *** Subscriptions // Subscribe to changes on a set of collections. This is used by livedb's polling query code. RedisDriver.prototype.subscribeChannels = function(collections, callback) { this._subscribeChannels(collections, null, callback); }; // Subscribe to a redis pubsub channel and get a nodejs stream out RedisDriver.prototype._subscribeChannels = function(channels, v, callback) { var stream = new util.OpStream(v); var self = this; // Registered so we can clean up the stream if the livedb instance is destroyed. this._addStream(stream); var listener; if (Array.isArray(channels)) { listener = function(msgChannel, data) { // Unprefix the channel name msgChannel = msgChannel.slice(msgChannel.indexOf(' ') + 1); if (channels.indexOf(msgChannel) === -1) return; // Unprefix database name from the channel and add it to the message. data.channel = msgChannel; stream.pushOp(data); }; } else { listener = function(msgChannel, data) { // console.log("listener", msgChannel, data); if (msgChannel !== self._prefixChannel(channels)) return; // console.log("stream push from publish", data); stream.pushOp(data); }; } stream.once('close', function() { self._removeStream(this); self._redisRemoveChannelListeners(channels, listener); }); this._redisAddChannelListeners(channels, listener, function(err) { if (err) { stream.destroy(); return callback(err); } callback(null, stream); }); }; // Register a listener (or many listeners) on redis channels. channels can be // just a single channel or a list. listeners should be either a function or // an array of the same length as channels. RedisDriver.prototype._redisAddChannelListeners = function(channels, listeners, callback) { // Not the most efficient way to do this, but I bet its not a bottleneck. if (!Array.isArray(channels)) channels = [channels]; if (Array.isArray(listeners)) assert(listeners.length === channels.length); var needsSubscribe = []; for (var i = 0; i < channels.length; i++) { var channel = this._prefixChannel(channels[i]); var listener = listeners[i] || listeners; if (EventEmitter.listenerCount(this.subscribers, channel) === 0) { needsSubscribe.push(channel); } this.subscribers.on(channel, listener); } if (needsSubscribe.length > 0) { this.numSubscriptions += needsSubscribe.length; if (this.sdc) this.sdc.gauge('livedb.redis.subscriptions', this.numSubscriptions); // Redis supports sending multiple channels to subscribe in one command, // but the node client doesn't handle replies correctly. For now, sending // each command separately is a workaround. // See https://github.com/mranney/node_redis/issues/577 var redisObserver = this.redisObserver; async.each(needsSubscribe, function(channel, eachCallback) { redisObserver.subscribe(channel, eachCallback); }, callback); } else { if (callback) callback(); } }; // Register the removal of a listener or a list of listeners on the given // channel(s). RedisDriver.prototype._redisRemoveChannelListeners = function(channels, listeners, callback) { if (!Array.isArray(channels)) channels = [channels]; if (Array.isArray(listeners)) assert(listeners.length === channels.length); var needsUnsubscribe = []; for (var i = 0; i < channels.length; i++) { var channel = this._prefixChannel(channels[i]); var listener = listeners[i] || listeners; this.subscribers.removeListener(channel, listener); if (EventEmitter.listenerCount(this.subscribers, channel) === 0) { needsUnsubscribe.push(channel); } } if (needsUnsubscribe.length > 0) { this.numSubscriptions -= needsUnsubscribe.length; if (this.sdc) this.sdc.gauge('livedb.redis.subscriptions', this.numSubscriptions); // See note about use of async above in subscribe var redisObserver = this.redisObserver; async.each(needsUnsubscribe, function(channel, eachCallback) { redisObserver.unsubscribe(channel, eachCallback); }, callback); } else { if (callback) callback(); } }; // Callback called with (err, op stream). v must be in the past or present. Behaviour // with a future v is undefined. (Don't do that.) RedisDriver.prototype.subscribe = function(cName, docName, v, options, callback) { if (this.sdc) { this.sdc.increment('livedb.subscribe'); this.sdc.increment('livedb.subscribe.raw'); } var opChannel = getDocOpChannel(cName, docName); var self = this; // Subscribe redis to the stream first so we don't miss out on any operations // while we're getting the history this._subscribeChannels(opChannel, v, function(err, stream) { if (err) return callback(err); // From here on, we need to call stream.destroy() if there are errors. self.getOps(cName, docName, v, null, function(err, ops) { if (err) { stream.destroy(); return callback(err); } stream.pack(v, ops); // Better to call fetchPresence here var presence; if (options.wantPresence) { var cd = util.encodeCD(cName, docName); presence = self.presenceCache[cd] || {}; } callback(null, stream, presence); }); }); }; // Requests is a map from {cName:{doc1:version, doc2:version, doc3:version}, ...} RedisDriver.prototype.bulkSubscribe = function(requests, callback) { if (this.sdc) this.sdc.increment('livedb.subscribe.bulk'); var self = this; // So, I'm not sure if this is slow, but for now I'll use subscribeChannels to // subscribe to all the channels for all the documents, then make a stream for // each document that has been subscribed. It might turn out that the right // architecture is to reuse the stream, but filter in ShareJS (or wherever) // when things pop out of the stream, but thats more complicated to implement. // Nodejs Stream objects are lightweight enough - they cost about 340 bytea // each. var docStreams = {}; var channels = []; var listener = function(channel, msg) { if (docStreams[channel]) { docStreams[channel].pushOp(msg); } }; for (var cName in requests) { var docs = requests[cName]; for (var docName in docs) { if (this.sdc) this.sdc.increment('livedb.subscribe'); var version = docs[docName]; var channelName = getDocOpChannel(cName, docName); var prefixedName = this._prefixChannel(channelName); channels.push(channelName); var docStream = docStreams[prefixedName] = new util.OpStream(version); docStream.channelName = channelName; docStream.prefixedName = prefixedName; docStream.once('close', function() { self._removeStream(this); delete docStreams[this.prefixedName]; self._redisRemoveChannelListeners(this.channelName, listener); }); this._addStream(docStream); } } var onError = function(err) { var channel; for (channel in docStreams) { docStreams[channel].destroy(); } callback(err); }; // Could just use Object.keys(docStreams) here.... this._redisAddChannelListeners(channels, listener, function(err) { if (err) return onError(err); self.bulkGetOpsSince(requests, function(err, ops) { if (err) return onError(err); // Map from cName -> docName -> stream. var result = {}; for (var cName in requests) { var docs = requests[cName]; result[cName] = {}; for (var docName in docs) { var version = docs[docName]; var channelName = getDocOpChannel(cName, docName); var prefixedName = self._prefixChannel(channelName) var stream = result[cName][docName] = docStreams[prefixedName]; stream.pack(version, ops[cName][docName]); } } callback(null, result); }); }); }; function processRedisOps(docV, to, result) { // The ops are stored in redis as JSON strings without versions. They're // returned with the final version at the end of the lua table. // version of the document var v = (to === -1) ? docV - result.length : to - result.length + 1 // the 'to' argument here is the version of the last op. var results = []; for (var i = 0; i < result.length; i++) { var op = JSON.parse(result[i]); op.v = v++; results.push(op); } return results; }; // ****** Script wrappers / entrypoints. // Follows same semantics as getOps elsewhere - returns ops [from, to). May // not return all operations in this range. // callback(error, version or null, ops); RedisDriver.prototype._redisGetOps = function(cName, docName, from, to, callback) { // TODO: Make this a timing request. if (this.sdc) this.sdc.increment('livedb.redis.getOps'); if (to === null) to = -1; if (to >= 0) { // Early abort if the range is flat. if (from >= to || to === 0) return callback(null, [], null); to--; } //console.log('redisGetOps', from, to); var self = this; this.redis.eval( getOpsCode, 2, getVersionKey(cName, docName), getOpLogKey(cName, docName), from, to , function(err, result) { if (err) return callback(err); if (result === null) return callback(null, [], null); // No data in redis. Punt to the persistant oplog. // Version of the document is at the end of the results list. var docV = result.pop(); var ops = processRedisOps(docV, to, result); callback(null, ops, docV); }); }; // requests is an object from {cName: {docName:v, ...}, ...}. This function // returns all operations since the requested version for each specified // document. Calls callback with // (err, {cName: {docName:[...], docName:[...], ...}}). Results are allowed to // be missing in the result set. If they are missing, that means there are no // operations since the specified version. (Ie, its the same as returning an // empty list. This is the 99% case for this method, so reducing the memory // usage is nice). RedisDriver.prototype.bulkGetOpsSince = function(requests, callback) { var start = Date.now(); // Not considering the case where redis has _some_ data but not all of it. // The script will just return all the data since the specified version ([] // if we know there's no ops) or nil if we don't have enough information to // know. // First I'll unpack all the things I need to know into these arrays. The // indexes all line up. I could use one array of object literals, but I // *think* this is faster, and I need the versionKeys, opLogKeys and froms // in separate arrays anyway to pass to redis. var cNames = []; var docNames = []; // Its kind of gross to do it like this, but I don't see any other good // options. We can't pass JS arrays directly into lua tables in the script, // so the arguments list will have to contain a splay of all the values. var redisArgs = [bulkGetOpsSinceCode, 0]; // 0 is a sentinal to be replaced with the number of keys var froms = []; for (var cName in requests) { var data = requests[cName]; for (var docName in data) { var version = data[docName]; cNames.push(cName); docNames.push(docName); redisArgs.push(getVersionKey(cName, docName)); redisArgs.push(getOpLogKey(cName, docName)); froms.push(version); } } // The froms have to come after the version keys and oplog keys because its // an argument list rather than a key list. redisArgs[1] = redisArgs.length - 2; redisArgs = redisArgs.concat(froms); var self = this; if (this.sdc) this.sdc.increment('livedb.redis.bulkGetOpsSince'); this.redis.eval(redisArgs, function(err, redisResults) { if (err) return callback(err); if (redisResults.length !== cNames.length) return callback('Invalid data from redis'); var results = {}; var pending = 1; var done = function() { pending--; if (pending === 0) { if (self.sdc) self.sdc.timing('livedb.bulkGetOpsSince', Date.now() - start); callback(null, results); } }; for (var i = 0; i < redisResults.length; i++) { var result = redisResults[i]; var cName = cNames[i]; var docName = docNames[i]; var from = froms[i]; if (results[cName] == null) results[cName] = {}; if (result === 0) { // sentinal value to mean we should go to the oplog. pending++; (function(cName, docName, from) { // We could have a bulkGetOps in the oplog too, but because we cache // anything missing in redis, I'm not super worried about the extra // calls here. self._oplogGetOps(cName, docName, from, null, function(err, ops) { if (err) return callback(err); results[cName][docName] = ops; // I'm going to do a sneaky cache here if its not in redis. self.oplog.getVersion(cName, docName, function(err, version) { if (err) return; self._redisCacheVersion(cName, docName, version); }); done(); }); })(cName, docName, from); } else { var v = from; // The ops are missing a version field. We'll add it back here. This // logic is repeated in processRedisOps, and should be pulled out into // a separate function. var ops = new Array(result.length); for (var j = 0; j < result.length; j++) { var op = JSON.parse(result[j]); op.v = v++; ops[j] = op; } results[cName][docName] = ops; } } done(); }); }; // After we submit an operation, reset redis's TTL so the data is allowed to expire. RedisDriver.prototype._redisSetExpire = function(cName, docName, v, callback) { if (this.sdc) this.sdc.increment('livedb.redis.setExpire'); this.redis.eval( setExpireCode, 2, getVersionKey(cName, docName), getOpLogKey(cName, docName), v, callback || doNothing); // We need to send a callback here to work around a bug in node-redis 0.9 }; RedisDriver.prototype._redisCacheVersion = function(cName, docName, v, callback) { if (this.sdc) this.sdc.increment('livedb.redis.cacheVersion'); var self = this; // At some point it'll be worth caching the snapshot in redis as well and // checking performance. this.redis.setnx(getVersionKey(cName, docName), v, function(err, didSet) { if (err || !didSet) return callback ? callback(err) : null; // Just in case. The oplog shouldn't be in redis if the version isn't in // redis, but whatever. self._redisSetExpire(cName, docName, v, callback); }); }; // docVersion is optional - if specified, this is set & used if redis doesn't know the doc's version RedisDriver.prototype._redisSubmitScript = function(cName, docName, opData, dirtyData, docVersion, callback) { if (this.sdc) this.sdc.increment('livedb.redis.submit'); // Sadly, because of the dirty data needing to edit a handful of keys, we need // to construct the arguments list here programatically. var args = [ submitCode, // num keys 4, // KEYS opData.src, getVersionKey(cName, docName), getOpLogKey(cName, docName), this._prefixChannel(getDocOpChannel(cName, docName)), ]; if (dirtyData) { for (var list in dirtyData) { args.push(getDirtyListKey(list)); args[1]++; // num keys } } // ARGV args.push.apply(args, [ opData.seq, opData.v, JSON.stringify(logEntryForData(opData)), // oplog entry JSON.stringify(opData), // publish entry docVersion ]); if (dirtyData) { for (var list in dirtyData) { args.push(JSON.stringify(dirtyData[list])); } } this.redis.eval(args, callback); }; RedisDriver.prototype._checkForLeaks = function(allowSubscriptions, callback) { if (!allowSubscriptions && this.numStreams) { throw Error('Leak detected - still ' + this.numStreams + ' outstanding subscriptions'); } if (Object.keys(this.streams).length !== this.numStreams) { console.error('numStreams:', this.numStreams, 'this.streams:', this.streams); throw Error('this.numStreams does not match this.streams'); } // We should also check the streams we're actually subscribed to on the redis observer. if (callback) callback(); };
__import__("pkg_resources").declare_namespace(__name__) from contextlib import contextmanager from infi.exceptools import chain from .setupapi import functions, properties, constants from infi.pyutils.lazy import cached_method from logging import getLogger ROOT_INSTANCE_ID = u"HTREE\\ROOT\\0" GLOBALROOT = u"\\\\?\\GLOBALROOT" logger = getLogger(__name__) class Device(object): def __init__(self, instance_id): super(Device, self).__init__() self._instance_id = instance_id def __repr__(self): # we cant use hasattr and getattr here, because friendly_name is a property method that may raise exception return u"<{}>".format(self.friendly_name if self.has_property("friendly_name") else self.description) @contextmanager def _open_handle(self): dis, devinfo = None, None try: dis = functions.SetupDiCreateDeviceInfoList() devinfo = functions.SetupDiOpenDeviceInfo(dis, self._instance_id) yield (dis, devinfo) finally: if dis is not None: functions.SetupDiDestroyDeviceInfoList(dis) def _get_setupapi_property(self, key): from .setupapi import WindowsException with self._open_handle() as handle: dis, devinfo = handle try: return functions.SetupDiGetDeviceProperty(dis, devinfo, key).python_object except WindowsException as exception: if exception.winerror == constants.ERROR_NOT_FOUND: raise KeyError(key) chain(exception) @property @cached_method def DriverVersion(self): try: return self._get_setupapi_property(properties.DEVPKEY_Device_DriverVersion) except KeyError: return 'DriverVersion unavailable' @property @cached_method def class_guid(self): guid = self._get_setupapi_property(properties.DEVPKEY_Device_ClassGuid) return functions.guid_to_pretty_string(guid) @property @cached_method def description(self): try: return self._get_setupapi_property(properties.DEVPKEY_Device_DeviceDesc) except KeyError: return 'description unavailable' @property @cached_method def hardware_ids(self): return self._get_setupapi_property(properties.DEVPKEY_Device_HardwareIds) @property @cached_method def instance_id(self): return self._get_setupapi_property(properties.DEVPKEY_Device_InstanceId) @property @cached_method def psuedo_device_object(self): value = self._get_setupapi_property(properties.DEVPKEY_Device_PDOName) if value is None: raise KeyError(properties.DEVPKEY_Device_PDOName) return GLOBALROOT + value @property @cached_method def friendly_name(self): return self._get_setupapi_property(properties.DEVPKEY_Device_FriendlyName) @property @cached_method def location_paths(self): return self._get_setupapi_property(properties.DEVPKEY_Device_LocationPaths) @property @cached_method def location(self): return self._get_setupapi_property(properties.DEVPKEY_Device_LocationInfo) @property @cached_method def bus_number(self): return self._get_setupapi_property(properties.DEVPKEY_Device_BusNumber) @property @cached_method def ui_number(self): return self._get_setupapi_property(properties.DEVPKEY_Device_UINumber) @property @cached_method def address(self): return self._get_setupapi_property(properties.DEVPKEY_Device_Address) @property def children(self): children = [] items = [] try: items = self._get_setupapi_property(properties.DEVPKEY_Device_Children) except KeyError: pass if items: for instance_id in items: children.append(Device(instance_id)) return children @property def parent(self): instance_id = self._get_setupapi_property(properties.DEVPKEY_Device_Parent) return Device(instance_id) @property @cached_method def instance_id(self): return self._instance_id @property @cached_method def devnode_status(self): return self._get_setupapi_property(properties.DEVPKEY_Device_DevNodeStatus) def is_root(self): return self._instance_id == ROOT_INSTANCE_ID def is_real_device(self): return self.has_property("location") def is_iscsi_device(self): try: hardware_ids = self.hardware_ids except KeyError: return False return any("iscsi" in hardware_id.lower() for hardware_id in hardware_ids) def is_hidden(self): return bool(self.devnode_status & constants.DN_NO_SHOW_IN_DM) def has_property(self, name): try: _ = getattr(self, name) return True except KeyError: pass return False @cached_method def get_available_property_ids(self): result = [] with self._open_handle() as handle: dis, devinfo = handle guid_list = functions.SetupDiGetDevicePropertyKeys(dis, devinfo) for guid in guid_list: result.append(functions.guid_to_pretty_string(guid)) return result def rescan(self): from .cfgmgr32 import open_handle, CM_Reenumerate_DevNode_Ex if not self.is_real_device() and not self.is_iscsi_device(): return with open_handle(self._instance_id) as handle: machine_handle, device_handle = handle _ = CM_Reenumerate_DevNode_Ex(device_handle, 0, machine_handle) class DeviceManager(object): def __init__(self): super(DeviceManager, self).__init__() self._dis_list = [] def __repr__(self): return "<DeviceManager>" @contextmanager def _open_handle(self, guid_string): dis = None try: dis = functions.SetupDiGetClassDevs(guid_string) yield dis finally: if dis is not None: functions.SetupDiDestroyDeviceInfoList(dis) def get_devices_from_handle(self, handle): devices = [] for devinfo in functions.SetupDiEnumDeviceInfo(handle): try: instance_id = functions.SetupDiGetDeviceProperty(handle, devinfo, properties.DEVPKEY_Device_InstanceId) except: logger.exception("failed to get DEVPKEY_Device_InstanceId from device {!r} by handle {!r}".format(handle, devinfo)) continue devices.append(Device(instance_id.python_object)) return devices @property def all_devices(self): with self._open_handle(None) as handle: return self.get_devices_from_handle(handle) @property def disk_drives(self): disk_drives = [] for controller in self.storage_controllers: def match_class_guid(device): try: return device.class_guid == constants.GENDISK_GUID_STRING except: return False disk_drives.extend(filter(match_class_guid, controller.children)) return disk_drives @property def storage_controllers(self): with self._open_handle(constants.SCSIADAPTER_GUID_STRING) as handle: return self.get_devices_from_handle(handle) @property def scsi_devices(self): devices = [] with self._open_handle(constants.SCSIADAPTER_GUID_STRING) as handle: storage_controllers = self.get_devices_from_handle(handle) for controller in storage_controllers: if not controller.has_property("children"): continue devices.extend(controller.children) return devices @property def volumes(self): with self._open_handle(constants.GENVOLUME_GUID_STRING) as handle: return self.get_devices_from_handle(handle) @property def root(self): return Device(ROOT_INSTANCE_ID)
// Compiled by ClojureScript 1.10.520 {} goog.provide('cljs.core.async.impl.timers'); goog.require('cljs.core'); goog.require('cljs.core.async.impl.protocols'); goog.require('cljs.core.async.impl.channels'); goog.require('cljs.core.async.impl.dispatch'); cljs.core.async.impl.timers.MAX_LEVEL = (15); cljs.core.async.impl.timers.P = ((1) / (2)); cljs.core.async.impl.timers.random_level = (function cljs$core$async$impl$timers$random_level(var_args){ var G__21146 = arguments.length; switch (G__21146) { case 0: return cljs.core.async.impl.timers.random_level.cljs$core$IFn$_invoke$arity$0(); break; case 1: return cljs.core.async.impl.timers.random_level.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.impl.timers.random_level.cljs$core$IFn$_invoke$arity$0 = (function (){ return cljs.core.async.impl.timers.random_level.call(null,(0)); }); cljs.core.async.impl.timers.random_level.cljs$core$IFn$_invoke$arity$1 = (function (level){ while(true){ if((((Math.random() < cljs.core.async.impl.timers.P)) && ((level < cljs.core.async.impl.timers.MAX_LEVEL)))){ var G__21148 = (level + (1)); level = G__21148; continue; } else { return level; } break; } }); cljs.core.async.impl.timers.random_level.cljs$lang$maxFixedArity = 1; /** * @constructor * @implements {cljs.core.ISeqable} * @implements {cljs.core.IPrintWithWriter} */ cljs.core.async.impl.timers.SkipListNode = (function (key,val,forward){ this.key = key; this.val = val; this.forward = forward; this.cljs$lang$protocol_mask$partition0$ = 2155872256; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.impl.timers.SkipListNode.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (coll){ var self__ = this; var coll__$1 = this; return (new cljs.core.List(null,self__.key,(new cljs.core.List(null,self__.val,null,(1),null)),(2),null)); }); cljs.core.async.impl.timers.SkipListNode.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (coll,writer,opts){ var self__ = this; var coll__$1 = this; return cljs.core.pr_sequential_writer.call(null,writer,cljs.core.pr_writer,"["," ","]",opts,coll__$1); }); cljs.core.async.impl.timers.SkipListNode.getBasis = (function (){ return new cljs.core.PersistentVector(null, 3, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"key","key",124488940,null),cljs.core.with_meta(new cljs.core.Symbol(null,"val","val",1769233139,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null)),new cljs.core.Symbol(null,"forward","forward",1083186224,null)], null); }); cljs.core.async.impl.timers.SkipListNode.cljs$lang$type = true; cljs.core.async.impl.timers.SkipListNode.cljs$lang$ctorStr = "cljs.core.async.impl.timers/SkipListNode"; cljs.core.async.impl.timers.SkipListNode.cljs$lang$ctorPrWriter = (function (this__4374__auto__,writer__4375__auto__,opt__4376__auto__){ return cljs.core._write.call(null,writer__4375__auto__,"cljs.core.async.impl.timers/SkipListNode"); }); /** * Positional factory function for cljs.core.async.impl.timers/SkipListNode. */ cljs.core.async.impl.timers.__GT_SkipListNode = (function cljs$core$async$impl$timers$__GT_SkipListNode(key,val,forward){ return (new cljs.core.async.impl.timers.SkipListNode(key,val,forward)); }); cljs.core.async.impl.timers.skip_list_node = (function cljs$core$async$impl$timers$skip_list_node(var_args){ var G__21150 = arguments.length; switch (G__21150) { case 1: return cljs.core.async.impl.timers.skip_list_node.cljs$core$IFn$_invoke$arity$1((arguments[(0)])); break; case 3: return cljs.core.async.impl.timers.skip_list_node.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.impl.timers.skip_list_node.cljs$core$IFn$_invoke$arity$1 = (function (level){ return cljs.core.async.impl.timers.skip_list_node.call(null,null,null,level); }); cljs.core.async.impl.timers.skip_list_node.cljs$core$IFn$_invoke$arity$3 = (function (k,v,level){ var arr = (new Array((level + (1)))); var i_21152 = (0); while(true){ if((i_21152 < arr.length)){ (arr[i_21152] = null); var G__21153 = (i_21152 + (1)); i_21152 = G__21153; continue; } else { } break; } return (new cljs.core.async.impl.timers.SkipListNode(k,v,arr)); }); cljs.core.async.impl.timers.skip_list_node.cljs$lang$maxFixedArity = 3; cljs.core.async.impl.timers.least_greater_node = (function cljs$core$async$impl$timers$least_greater_node(var_args){ var G__21155 = arguments.length; switch (G__21155) { case 3: return cljs.core.async.impl.timers.least_greater_node.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)])); break; case 4: return cljs.core.async.impl.timers.least_greater_node.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)])); break; default: throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join(''))); } }); cljs.core.async.impl.timers.least_greater_node.cljs$core$IFn$_invoke$arity$3 = (function (x,k,level){ return cljs.core.async.impl.timers.least_greater_node.call(null,x,k,level,null); }); cljs.core.async.impl.timers.least_greater_node.cljs$core$IFn$_invoke$arity$4 = (function (x,k,level,update){ while(true){ if((!((level < (0))))){ var x__$1 = (function (){var x__$1 = x; while(true){ var temp__5718__auto__ = (((level < x__$1.forward.length))?(x__$1.forward[level]):null); if(cljs.core.truth_(temp__5718__auto__)){ var x_SINGLEQUOTE_ = temp__5718__auto__; if((x_SINGLEQUOTE_.key < k)){ var G__21157 = x_SINGLEQUOTE_; x__$1 = G__21157; continue; } else { return x__$1; } } else { return x__$1; } break; } })(); if((update == null)){ } else { (update[level] = x__$1); } var G__21158 = x__$1; var G__21159 = k; var G__21160 = (level - (1)); var G__21161 = update; x = G__21158; k = G__21159; level = G__21160; update = G__21161; continue; } else { return x; } break; } }); cljs.core.async.impl.timers.least_greater_node.cljs$lang$maxFixedArity = 4; /** * @constructor * @implements {cljs.core.async.impl.timers.Object} * @implements {cljs.core.ISeqable} * @implements {cljs.core.IPrintWithWriter} */ cljs.core.async.impl.timers.SkipList = (function (header,level){ this.header = header; this.level = level; this.cljs$lang$protocol_mask$partition0$ = 2155872256; this.cljs$lang$protocol_mask$partition1$ = 0; }); cljs.core.async.impl.timers.SkipList.prototype.put = (function (k,v){ var self__ = this; var coll = this; var update = (new Array(cljs.core.async.impl.timers.MAX_LEVEL)); var x = cljs.core.async.impl.timers.least_greater_node.call(null,self__.header,k,self__.level,update); var x__$1 = (x.forward[(0)]); if((((!((x__$1 == null)))) && ((x__$1.key === k)))){ return x__$1.val = v; } else { var new_level = cljs.core.async.impl.timers.random_level.call(null); if((new_level > self__.level)){ var i_21162 = (self__.level + (1)); while(true){ if((i_21162 <= (new_level + (1)))){ (update[i_21162] = self__.header); var G__21163 = (i_21162 + (1)); i_21162 = G__21163; continue; } else { } break; } self__.level = new_level; } else { } var x__$2 = cljs.core.async.impl.timers.skip_list_node.call(null,k,v,(new Array(new_level))); var i = (0); while(true){ if((i <= self__.level)){ var links = (update[i]).forward; (x__$2.forward[i] = (links[i])); return (links[i] = x__$2); } else { return null; } break; } } }); cljs.core.async.impl.timers.SkipList.prototype.remove = (function (k){ var self__ = this; var coll = this; var update = (new Array(cljs.core.async.impl.timers.MAX_LEVEL)); var x = cljs.core.async.impl.timers.least_greater_node.call(null,self__.header,k,self__.level,update); var x__$1 = (((x.forward.length === (0)))?null:(x.forward[(0)])); if((((!((x__$1 == null)))) && ((x__$1.key === k)))){ var i_21164 = (0); while(true){ if((i_21164 <= self__.level)){ var links_21165 = (update[i_21164]).forward; if((x__$1 === (((i_21164 < links_21165.length))?(links_21165[i_21164]):null))){ (links_21165[i_21164] = (x__$1.forward[i_21164])); var G__21166 = (i_21164 + (1)); i_21164 = G__21166; continue; } else { var G__21167 = (i_21164 + (1)); i_21164 = G__21167; continue; } } else { } break; } while(true){ if(((((((0) < self__.level)) && ((self__.level < self__.header.forward.length)))) && (((self__.header.forward[self__.level]) == null)))){ self__.level = (self__.level - (1)); continue; } else { return null; } break; } } else { return null; } }); cljs.core.async.impl.timers.SkipList.prototype.ceilingEntry = (function (k){ var self__ = this; var coll = this; var x = self__.header; var level__$1 = self__.level; while(true){ if((!((level__$1 < (0))))){ var nx = (function (){var x__$1 = x; while(true){ var x_SINGLEQUOTE_ = (((level__$1 < x__$1.forward.length))?(x__$1.forward[level__$1]):null); if((x_SINGLEQUOTE_ == null)){ return null; } else { if((x_SINGLEQUOTE_.key >= k)){ return x_SINGLEQUOTE_; } else { var G__21168 = x_SINGLEQUOTE_; x__$1 = G__21168; continue; } } break; } })(); if((!((nx == null)))){ var G__21169 = nx; var G__21170 = (level__$1 - (1)); x = G__21169; level__$1 = G__21170; continue; } else { var G__21171 = x; var G__21172 = (level__$1 - (1)); x = G__21171; level__$1 = G__21172; continue; } } else { if((x === self__.header)){ return null; } else { return x; } } break; } }); cljs.core.async.impl.timers.SkipList.prototype.floorEntry = (function (k){ var self__ = this; var coll = this; var x = self__.header; var level__$1 = self__.level; while(true){ if((!((level__$1 < (0))))){ var nx = (function (){var x__$1 = x; while(true){ var x_SINGLEQUOTE_ = (((level__$1 < x__$1.forward.length))?(x__$1.forward[level__$1]):null); if((!((x_SINGLEQUOTE_ == null)))){ if((x_SINGLEQUOTE_.key > k)){ return x__$1; } else { var G__21173 = x_SINGLEQUOTE_; x__$1 = G__21173; continue; } } else { if((level__$1 === (0))){ return x__$1; } else { return null; } } break; } })(); if(cljs.core.truth_(nx)){ var G__21174 = nx; var G__21175 = (level__$1 - (1)); x = G__21174; level__$1 = G__21175; continue; } else { var G__21176 = x; var G__21177 = (level__$1 - (1)); x = G__21176; level__$1 = G__21177; continue; } } else { if((x === self__.header)){ return null; } else { return x; } } break; } }); cljs.core.async.impl.timers.SkipList.prototype.cljs$core$ISeqable$_seq$arity$1 = (function (coll){ var self__ = this; var coll__$1 = this; var iter = ((function (coll__$1){ return (function cljs$core$async$impl$timers$iter(node){ return (new cljs.core.LazySeq(null,((function (coll__$1){ return (function (){ if((node == null)){ return null; } else { return cljs.core.cons.call(null,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [node.key,node.val], null),cljs$core$async$impl$timers$iter.call(null,(node.forward[(0)]))); } });})(coll__$1)) ,null,null)); });})(coll__$1)) ; return iter.call(null,(self__.header.forward[(0)])); }); cljs.core.async.impl.timers.SkipList.prototype.cljs$core$IPrintWithWriter$_pr_writer$arity$3 = (function (coll,writer,opts){ var self__ = this; var coll__$1 = this; var pr_pair = ((function (coll__$1){ return (function (keyval){ return cljs.core.pr_sequential_writer.call(null,writer,cljs.core.pr_writer,""," ","",opts,keyval); });})(coll__$1)) ; return cljs.core.pr_sequential_writer.call(null,writer,pr_pair,"{",", ","}",opts,coll__$1); }); cljs.core.async.impl.timers.SkipList.getBasis = (function (){ return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [new cljs.core.Symbol(null,"header","header",1759972661,null),cljs.core.with_meta(new cljs.core.Symbol(null,"level","level",-1363938217,null),new cljs.core.PersistentArrayMap(null, 1, [new cljs.core.Keyword(null,"mutable","mutable",875778266),true], null))], null); }); cljs.core.async.impl.timers.SkipList.cljs$lang$type = true; cljs.core.async.impl.timers.SkipList.cljs$lang$ctorStr = "cljs.core.async.impl.timers/SkipList"; cljs.core.async.impl.timers.SkipList.cljs$lang$ctorPrWriter = (function (this__4374__auto__,writer__4375__auto__,opt__4376__auto__){ return cljs.core._write.call(null,writer__4375__auto__,"cljs.core.async.impl.timers/SkipList"); }); /** * Positional factory function for cljs.core.async.impl.timers/SkipList. */ cljs.core.async.impl.timers.__GT_SkipList = (function cljs$core$async$impl$timers$__GT_SkipList(header,level){ return (new cljs.core.async.impl.timers.SkipList(header,level)); }); cljs.core.async.impl.timers.skip_list = (function cljs$core$async$impl$timers$skip_list(){ return (new cljs.core.async.impl.timers.SkipList(cljs.core.async.impl.timers.skip_list_node.call(null,(0)),(0))); }); cljs.core.async.impl.timers.timeouts_map = cljs.core.async.impl.timers.skip_list.call(null); cljs.core.async.impl.timers.TIMEOUT_RESOLUTION_MS = (10); /** * returns a channel that will close after msecs */ cljs.core.async.impl.timers.timeout = (function cljs$core$async$impl$timers$timeout(msecs){ var timeout = ((new Date()).valueOf() + msecs); var me = cljs.core.async.impl.timers.timeouts_map.ceilingEntry(timeout); var or__4131__auto__ = (cljs.core.truth_((function (){var and__4120__auto__ = me; if(cljs.core.truth_(and__4120__auto__)){ return (me.key < (timeout + cljs.core.async.impl.timers.TIMEOUT_RESOLUTION_MS)); } else { return and__4120__auto__; } })())?me.val:null); if(cljs.core.truth_(or__4131__auto__)){ return or__4131__auto__; } else { var timeout_channel = cljs.core.async.impl.channels.chan.call(null,null); cljs.core.async.impl.timers.timeouts_map.put(timeout,timeout_channel); cljs.core.async.impl.dispatch.queue_delay.call(null,((function (timeout_channel,or__4131__auto__,timeout,me){ return (function (){ cljs.core.async.impl.timers.timeouts_map.remove(timeout); return cljs.core.async.impl.protocols.close_BANG_.call(null,timeout_channel); });})(timeout_channel,or__4131__auto__,timeout,me)) ,msecs); return timeout_channel; } }); //# sourceMappingURL=timers.js.map
!function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};e.m=t,e.c=n,e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="/dist/",e(e.s=12)}([function(t,e){function n(t,e){var n=t[1]||"",i=t[3];if(!i)return n;if(e&&"function"==typeof btoa){var o=r(i);return[n].concat(i.sources.map(function(t){return"/*# sourceURL="+i.sourceRoot+t+" */"})).concat([o]).join("\n")}return[n].join("\n")}function r(t){return"/*# sourceMappingURL=data:application/json;charset=utf-8;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(t))))+" */"}t.exports=function(t){var e=[];return e.toString=function(){return this.map(function(e){var r=n(e,t);return e[2]?"@media "+e[2]+"{"+r+"}":r}).join("")},e.i=function(t,n){"string"==typeof t&&(t=[[null,t,""]]);for(var r={},i=0;i<this.length;i++){var o=this[i][0];"number"==typeof o&&(r[o]=!0)}for(i=0;i<t.length;i++){var a=t[i];"number"==typeof a[0]&&r[a[0]]||(n&&!a[2]?a[2]=n:n&&(a[2]="("+a[2]+") and ("+n+")"),e.push(a))}},e}},function(t,e,n){function r(t){for(var e=0;e<t.length;e++){var n=t[e],r=l[n.id];if(r){r.refs++;for(var i=0;i<r.parts.length;i++)r.parts[i](n.parts[i]);for(;i<n.parts.length;i++)r.parts.push(o(n.parts[i]));r.parts.length>n.parts.length&&(r.parts.length=n.parts.length)}else{for(var a=[],i=0;i<n.parts.length;i++)a.push(o(n.parts[i]));l[n.id]={id:n.id,refs:1,parts:a}}}}function i(){var t=document.createElement("style");return t.type="text/css",f.appendChild(t),t}function o(t){var e,n,r=document.querySelector("style["+y+'~="'+t.id+'"]');if(r){if(v)return h;r.parentNode.removeChild(r)}if(g){var o=p++;r=d||(d=i()),e=a.bind(null,r,o,!1),n=a.bind(null,r,o,!0)}else r=i(),e=s.bind(null,r),n=function(){r.parentNode.removeChild(r)};return e(t),function(r){if(r){if(r.css===t.css&&r.media===t.media&&r.sourceMap===t.sourceMap)return;e(t=r)}else n()}}function a(t,e,n,r){var i=n?"":r.css;if(t.styleSheet)t.styleSheet.cssText=b(e,i);else{var o=document.createTextNode(i),a=t.childNodes;a[e]&&t.removeChild(a[e]),a.length?t.insertBefore(o,a[e]):t.appendChild(o)}}function s(t,e){var n=e.css,r=e.media,i=e.sourceMap;if(r&&t.setAttribute("media",r),m.ssrId&&t.setAttribute(y,e.id),i&&(n+="\n/*# sourceURL="+i.sources[0]+" */",n+="\n/*# sourceMappingURL=data:application/json;base64,"+btoa(unescape(encodeURIComponent(JSON.stringify(i))))+" */"),t.styleSheet)t.styleSheet.cssText=n;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(n))}}var c="undefined"!=typeof document;if("undefined"!=typeof DEBUG&&DEBUG&&!c)throw new Error("vue-style-loader cannot be used in a non-browser environment. Use { target: 'node' } in your Webpack config to indicate a server-rendering environment.");var u=n(21),l={},f=c&&(document.head||document.getElementsByTagName("head")[0]),d=null,p=0,v=!1,h=function(){},m=null,y="data-vue-ssr-id",g="undefined"!=typeof navigator&&/msie [6-9]\b/.test(navigator.userAgent.toLowerCase());t.exports=function(t,e,n,i){v=n,m=i||{};var o=u(t,e);return r(o),function(e){for(var n=[],i=0;i<o.length;i++){var a=o[i],s=l[a.id];s.refs--,n.push(s)}e?(o=u(t,e),r(o)):o=[];for(var i=0;i<n.length;i++){var s=n[i];if(0===s.refs){for(var c=0;c<s.parts.length;c++)s.parts[c]();delete l[s.id]}}}};var b=function(){var t=[];return function(e,n){return t[e]=n,t.filter(Boolean).join("\n")}}()},function(t,e){t.exports=function(t,e,n,r,i,o){var a,s=t=t||{},c=typeof t.default;"object"!==c&&"function"!==c||(a=t,s=t.default);var u="function"==typeof s?s.options:s;e&&(u.render=e.render,u.staticRenderFns=e.staticRenderFns,u._compiled=!0),n&&(u.functional=!0),i&&(u._scopeId=i);var l;if(o?(l=function(t){t=t||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,t||"undefined"==typeof __VUE_SSR_CONTEXT__||(t=__VUE_SSR_CONTEXT__),r&&r.call(this,t),t&&t._registeredComponents&&t._registeredComponents.add(o)},u._ssrRegister=l):r&&(l=r),l){var f=u.functional,d=f?u.render:u.beforeCreate;f?(u._injectStyles=l,u.render=function(t,e){return l.call(e),d(t,e)}):u.beforeCreate=d?[].concat(d,l):[l]}return{esModule:a,exports:s,options:u}}},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){"use strict";var r=n(22),i=n(26),o=n(45);e.a={name:"app",components:{VmHeader:r.a,VmMainContent:i.a,VmFooter:o.a},data:function(){return{}}}},function(t,e,n){"use strict";e.a={}},function(t,e,n){"use strict";var r=n(29),i=n(36),o=n(40);e.a={components:{VmAsideLeft:r.a,VmAsideRight:i.a,VmMiddelContent:o.a}}},function(t,e,n){"use strict";var r=n(8);e.a={data:function(){return{tracks:[],searchQuery:""}},methods:{clearTracksList:function(){this.tracks=[],this.searchQuery=""},setTrack:function(t){this.$bus.$emit("set-track",t),this.$bus.$emit("set-artis-track",t.album.artists[0].name)}},watch:{searchQuery:function(){var t=this;this.searchQuery||(this.tracks=[]),r.a.search(this.searchQuery).then(function(e){t.tracks=e.tracks.items})}},filters:{maxLetters:function(t){return t.split("").splice(0,34).join("")}}}},function(t,e,n){"use strict";var r=n(32),i={};i.search=function(t){return r.a.get("/search",{params:{q:t,type:"track"}}).then(function(t){return t.data})},e.a=i},function(t,e,n){"use strict";var r=n(8);e.a={data:function(){return{tracks:[],artistsTracks:[],artist:""}},created:function(){var t=this;this.$bus.$on("set-artis-track",function(e){t.artist=e})},watch:{artist:function(){var t=this;this.artist||(this.tracks=[]),r.a.search(this.artist).then(function(e){t.tracks=e.tracks.items})},tracks:function(){var t=this;this.artist||(this.tracks=[]),this.artistsTracks=this.tracks.filter(function(e){return e.album.artists[0].name==t.artist})}},methods:{setTrack:function(t){this.$bus.$emit("set-track",t)}},filters:{maxLetters:function(t){return t.split("").splice(0,50).join("")}}}},function(t,e,n){"use strict";e.a={data:function(){return{track:{}}},created:function(){var t=this;this.$bus.$on("set-track",function(e){t.track=e})},computed:{theLink:function(){return this.track.uri.replace("spotify:track:","https://open.spotify.com/track/")}}}},function(t,e,n){"use strict";e.a={}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(13),i=n(17),o=n(50);r.a.use(o.a),new r.a({el:"#app",render:function(t){return t(i.a)}})},function(t,e,n){"use strict";(function(t,n){function r(t){return void 0===t||null===t}function i(t){return void 0!==t&&null!==t}function o(t){return!0===t}function a(t){return!1===t}function s(t){return"string"==typeof t||"number"==typeof t||"symbol"==typeof t||"boolean"==typeof t}function c(t){return null!==t&&"object"==typeof t}function u(t){return"[object Object]"===so.call(t)}function l(t){return"[object RegExp]"===so.call(t)}function f(t){var e=parseFloat(String(t));return e>=0&&Math.floor(e)===e&&isFinite(t)}function d(t){return null==t?"":"object"==typeof t?JSON.stringify(t,null,2):String(t)}function p(t){var e=parseFloat(t);return isNaN(e)?t:e}function v(t,e){for(var n=Object.create(null),r=t.split(","),i=0;i<r.length;i++)n[r[i]]=!0;return e?function(t){return n[t.toLowerCase()]}:function(t){return n[t]}}function h(t,e){if(t.length){var n=t.indexOf(e);if(n>-1)return t.splice(n,1)}}function m(t,e){return lo.call(t,e)}function y(t){var e=Object.create(null);return function(n){return e[n]||(e[n]=t(n))}}function g(t,e){function n(n){var r=arguments.length;return r?r>1?t.apply(e,arguments):t.call(e,n):t.call(e)}return n._length=t.length,n}function b(t,e){return t.bind(e)}function _(t,e){e=e||0;for(var n=t.length-e,r=new Array(n);n--;)r[n]=t[n+e];return r}function w(t,e){for(var n in e)t[n]=e[n];return t}function x(t){for(var e={},n=0;n<t.length;n++)t[n]&&w(e,t[n]);return e}function k(t,e,n){}function $(t,e){if(t===e)return!0;var n=c(t),r=c(e);if(!n||!r)return!n&&!r&&String(t)===String(e);try{var i=Array.isArray(t),o=Array.isArray(e);if(i&&o)return t.length===e.length&&t.every(function(t,n){return $(t,e[n])});if(i||o)return!1;var a=Object.keys(t),s=Object.keys(e);return a.length===s.length&&a.every(function(n){return $(t[n],e[n])})}catch(t){return!1}}function C(t,e){for(var n=0;n<t.length;n++)if($(t[n],e))return n;return-1}function A(t){var e=!1;return function(){e||(e=!0,t.apply(this,arguments))}}function O(t){var e=(t+"").charCodeAt(0);return 36===e||95===e}function T(t,e,n,r){Object.defineProperty(t,e,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function j(t){if(!$o.test(t)){var e=t.split(".");return function(t){for(var n=0;n<e.length;n++){if(!t)return;t=t[e[n]]}return t}}}function S(t){return"function"==typeof t&&/native code/.test(t.toString())}function E(t){zo.target&&qo.push(zo.target),zo.target=t}function L(){zo.target=qo.pop()}function N(t){return new Jo(void 0,void 0,void 0,String(t))}function I(t){var e=new Jo(t.tag,t.data,t.children,t.text,t.elm,t.context,t.componentOptions,t.asyncFactory);return e.ns=t.ns,e.isStatic=t.isStatic,e.key=t.key,e.isComment=t.isComment,e.fnContext=t.fnContext,e.fnOptions=t.fnOptions,e.fnScopeId=t.fnScopeId,e.isCloned=!0,e}function P(t){Zo=t}function D(t,e,n){t.__proto__=e}function M(t,e,n){for(var r=0,i=n.length;r<i;r++){var o=n[r];T(t,o,e[o])}}function R(t,e){if(c(t)&&!(t instanceof Jo)){var n;return m(t,"__ob__")&&t.__ob__ instanceof Yo?n=t.__ob__:Zo&&!Fo()&&(Array.isArray(t)||u(t))&&Object.isExtensible(t)&&!t._isVue&&(n=new Yo(t)),e&&n&&n.vmCount++,n}}function F(t,e,n,r,i){var o=new zo,a=Object.getOwnPropertyDescriptor(t,e);if(!a||!1!==a.configurable){var s=a&&a.get;s||2!==arguments.length||(n=t[e]);var c=a&&a.set,u=!i&&R(n);Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get:function(){var e=s?s.call(t):n;return zo.target&&(o.depend(),u&&(u.dep.depend(),Array.isArray(e)&&H(e))),e},set:function(e){var r=s?s.call(t):n;e===r||e!==e&&r!==r||(c?c.call(t,e):n=e,u=!i&&R(e),o.notify())}})}}function U(t,e,n){if(Array.isArray(t)&&f(e))return t.length=Math.max(t.length,e),t.splice(e,1,n),n;if(e in t&&!(e in Object.prototype))return t[e]=n,n;var r=t.__ob__;return t._isVue||r&&r.vmCount?n:r?(F(r.value,e,n),r.dep.notify(),n):(t[e]=n,n)}function B(t,e){if(Array.isArray(t)&&f(e))return void t.splice(e,1);var n=t.__ob__;t._isVue||n&&n.vmCount||m(t,e)&&(delete t[e],n&&n.dep.notify())}function H(t){for(var e=void 0,n=0,r=t.length;n<r;n++)e=t[n],e&&e.__ob__&&e.__ob__.dep.depend(),Array.isArray(e)&&H(e)}function V(t,e){if(!e)return t;for(var n,r,i,o=Object.keys(e),a=0;a<o.length;a++)n=o[a],r=t[n],i=e[n],m(t,n)?u(r)&&u(i)&&V(r,i):U(t,n,i);return t}function z(t,e,n){return n?function(){var r="function"==typeof e?e.call(n,n):e,i="function"==typeof t?t.call(n,n):t;return r?V(r,i):i}:e?t?function(){return V("function"==typeof e?e.call(this,this):e,"function"==typeof t?t.call(this,this):t)}:e:t}function q(t,e){return e?t?t.concat(e):Array.isArray(e)?e:[e]:t}function J(t,e,n,r){var i=Object.create(t||null);return e?w(i,e):i}function K(t,e){var n=t.props;if(n){var r,i,o,a={};if(Array.isArray(n))for(r=n.length;r--;)"string"==typeof(i=n[r])&&(o=po(i),a[o]={type:null});else if(u(n))for(var s in n)i=n[s],o=po(s),a[o]=u(i)?i:{type:i};t.props=a}}function W(t,e){var n=t.inject;if(n){var r=t.inject={};if(Array.isArray(n))for(var i=0;i<n.length;i++)r[n[i]]={from:n[i]};else if(u(n))for(var o in n){var a=n[o];r[o]=u(a)?w({from:o},a):{from:a}}}}function G(t){var e=t.directives;if(e)for(var n in e){var r=e[n];"function"==typeof r&&(e[n]={bind:r,update:r})}}function Q(t,e,n){function r(r){var i=ta[r]||ra;c[r]=i(t[r],e[r],n,r)}"function"==typeof e&&(e=e.options),K(e,n),W(e,n),G(e);var i=e.extends;if(i&&(t=Q(t,i,n)),e.mixins)for(var o=0,a=e.mixins.length;o<a;o++)t=Q(t,e.mixins[o],n);var s,c={};for(s in t)r(s);for(s in e)m(t,s)||r(s);return c}function X(t,e,n,r){if("string"==typeof n){var i=t[e];if(m(i,n))return i[n];var o=po(n);if(m(i,o))return i[o];var a=vo(o);if(m(i,a))return i[a];return i[n]||i[o]||i[a]}}function Z(t,e,n,r){var i=e[t],o=!m(n,t),a=n[t],s=nt(Boolean,i.type);if(s>-1)if(o&&!m(i,"default"))a=!1;else if(""===a||a===mo(t)){var c=nt(String,i.type);(c<0||s<c)&&(a=!0)}if(void 0===a){a=Y(r,i,t);var u=Zo;P(!0),R(a),P(u)}return a}function Y(t,e,n){if(m(e,"default")){var r=e.default;return t&&t.$options.propsData&&void 0===t.$options.propsData[n]&&void 0!==t._props[n]?t._props[n]:"function"==typeof r&&"Function"!==tt(e.type)?r.call(t):r}}function tt(t){var e=t&&t.toString().match(/^\s*function (\w+)/);return e?e[1]:""}function et(t,e){return tt(t)===tt(e)}function nt(t,e){if(!Array.isArray(e))return et(e,t)?0:-1;for(var n=0,r=e.length;n<r;n++)if(et(e[n],t))return n;return-1}function rt(t,e,n){if(e)for(var r=e;r=r.$parent;){var i=r.$options.errorCaptured;if(i)for(var o=0;o<i.length;o++)try{var a=!1===i[o].call(r,t,e,n);if(a)return}catch(t){it(t,r,"errorCaptured hook")}}it(t,e,n)}function it(t,e,n){if(ko.errorHandler)try{return ko.errorHandler.call(null,t,e,n)}catch(t){ot(t,null,"config.errorHandler")}ot(t,e,n)}function ot(t,e,n){if(!Ao&&!Oo||"undefined"==typeof console)throw t;console.error(t)}function at(){oa=!1;var t=ia.slice(0);ia.length=0;for(var e=0;e<t.length;e++)t[e]()}function st(t){return t._withTask||(t._withTask=function(){aa=!0;var e=t.apply(null,arguments);return aa=!1,e})}function ct(t,e){var n;if(ia.push(function(){if(t)try{t.call(e)}catch(t){rt(t,e,"nextTick")}else n&&n(e)}),oa||(oa=!0,aa?na():ea()),!t&&"undefined"!=typeof Promise)return new Promise(function(t){n=t})}function ut(t){lt(t,fa),fa.clear()}function lt(t,e){var n,r,i=Array.isArray(t);if(!(!i&&!c(t)||Object.isFrozen(t)||t instanceof Jo)){if(t.__ob__){var o=t.__ob__.dep.id;if(e.has(o))return;e.add(o)}if(i)for(n=t.length;n--;)lt(t[n],e);else for(r=Object.keys(t),n=r.length;n--;)lt(t[r[n]],e)}}function ft(t){function e(){var t=arguments,n=e.fns;if(!Array.isArray(n))return n.apply(null,arguments);for(var r=n.slice(),i=0;i<r.length;i++)r[i].apply(null,t)}return e.fns=t,e}function dt(t,e,n,i,o){var a,s,c,u;for(a in t)s=t[a],c=e[a],u=da(a),r(s)||(r(c)?(r(s.fns)&&(s=t[a]=ft(s)),n(u.name,s,u.once,u.capture,u.passive,u.params)):s!==c&&(c.fns=s,t[a]=c));for(a in e)r(t[a])&&(u=da(a),i(u.name,e[a],u.capture))}function pt(t,e,n){function a(){n.apply(this,arguments),h(s.fns,a)}t instanceof Jo&&(t=t.data.hook||(t.data.hook={}));var s,c=t[e];r(c)?s=ft([a]):i(c.fns)&&o(c.merged)?(s=c,s.fns.push(a)):s=ft([c,a]),s.merged=!0,t[e]=s}function vt(t,e,n){var o=e.options.props;if(!r(o)){var a={},s=t.attrs,c=t.props;if(i(s)||i(c))for(var u in o){var l=mo(u);ht(a,c,u,l,!0)||ht(a,s,u,l,!1)}return a}}function ht(t,e,n,r,o){if(i(e)){if(m(e,n))return t[n]=e[n],o||delete e[n],!0;if(m(e,r))return t[n]=e[r],o||delete e[r],!0}return!1}function mt(t){for(var e=0;e<t.length;e++)if(Array.isArray(t[e]))return Array.prototype.concat.apply([],t);return t}function yt(t){return s(t)?[N(t)]:Array.isArray(t)?bt(t):void 0}function gt(t){return i(t)&&i(t.text)&&a(t.isComment)}function bt(t,e){var n,a,c,u,l=[];for(n=0;n<t.length;n++)a=t[n],r(a)||"boolean"==typeof a||(c=l.length-1,u=l[c],Array.isArray(a)?a.length>0&&(a=bt(a,(e||"")+"_"+n),gt(a[0])&&gt(u)&&(l[c]=N(u.text+a[0].text),a.shift()),l.push.apply(l,a)):s(a)?gt(u)?l[c]=N(u.text+a):""!==a&&l.push(N(a)):gt(a)&&gt(u)?l[c]=N(u.text+a.text):(o(t._isVList)&&i(a.tag)&&r(a.key)&&i(e)&&(a.key="__vlist"+e+"_"+n+"__"),l.push(a)));return l}function _t(t,e){return(t.__esModule||Bo&&"Module"===t[Symbol.toStringTag])&&(t=t.default),c(t)?e.extend(t):t}function wt(t,e,n,r,i){var o=Wo();return o.asyncFactory=t,o.asyncMeta={data:e,context:n,children:r,tag:i},o}function xt(t,e,n){if(o(t.error)&&i(t.errorComp))return t.errorComp;if(i(t.resolved))return t.resolved;if(o(t.loading)&&i(t.loadingComp))return t.loadingComp;if(!i(t.contexts)){var a=t.contexts=[n],s=!0,u=function(){for(var t=0,e=a.length;t<e;t++)a[t].$forceUpdate()},l=A(function(n){t.resolved=_t(n,e),s||u()}),f=A(function(e){i(t.errorComp)&&(t.error=!0,u())}),d=t(l,f);return c(d)&&("function"==typeof d.then?r(t.resolved)&&d.then(l,f):i(d.component)&&"function"==typeof d.component.then&&(d.component.then(l,f),i(d.error)&&(t.errorComp=_t(d.error,e)),i(d.loading)&&(t.loadingComp=_t(d.loading,e),0===d.delay?t.loading=!0:setTimeout(function(){r(t.resolved)&&r(t.error)&&(t.loading=!0,u())},d.delay||200)),i(d.timeout)&&setTimeout(function(){r(t.resolved)&&f(null)},d.timeout))),s=!1,t.loading?t.loadingComp:t.resolved}t.contexts.push(n)}function kt(t){return t.isComment&&t.asyncFactory}function $t(t){if(Array.isArray(t))for(var e=0;e<t.length;e++){var n=t[e];if(i(n)&&(i(n.componentOptions)||kt(n)))return n}}function Ct(t){t._events=Object.create(null),t._hasHookEvent=!1;var e=t.$options._parentListeners;e&&Tt(t,e)}function At(t,e,n){n?la.$once(t,e):la.$on(t,e)}function Ot(t,e){la.$off(t,e)}function Tt(t,e,n){la=t,dt(e,n||{},At,Ot,t),la=void 0}function jt(t,e){var n={};if(!t)return n;for(var r=0,i=t.length;r<i;r++){var o=t[r],a=o.data;if(a&&a.attrs&&a.attrs.slot&&delete a.attrs.slot,o.context!==e&&o.fnContext!==e||!a||null==a.slot)(n.default||(n.default=[])).push(o);else{var s=a.slot,c=n[s]||(n[s]=[]);"template"===o.tag?c.push.apply(c,o.children||[]):c.push(o)}}for(var u in n)n[u].every(St)&&delete n[u];return n}function St(t){return t.isComment&&!t.asyncFactory||" "===t.text}function Et(t,e){e=e||{};for(var n=0;n<t.length;n++)Array.isArray(t[n])?Et(t[n],e):e[t[n].key]=t[n].fn;return e}function Lt(t){var e=t.$options,n=e.parent;if(n&&!e.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(t)}t.$parent=n,t.$root=n?n.$root:t,t.$children=[],t.$refs={},t._watcher=null,t._inactive=null,t._directInactive=!1,t._isMounted=!1,t._isDestroyed=!1,t._isBeingDestroyed=!1}function Nt(t,e,n){t.$el=e,t.$options.render||(t.$options.render=Wo),Rt(t,"beforeMount");var r;return r=function(){t._update(t._render(),n)},new wa(t,r,k,null,!0),n=!1,null==t.$vnode&&(t._isMounted=!0,Rt(t,"mounted")),t}function It(t,e,n,r,i){var o=!!(i||t.$options._renderChildren||r.data.scopedSlots||t.$scopedSlots!==ao);if(t.$options._parentVnode=r,t.$vnode=r,t._vnode&&(t._vnode.parent=r),t.$options._renderChildren=i,t.$attrs=r.data.attrs||ao,t.$listeners=n||ao,e&&t.$options.props){P(!1);for(var a=t._props,s=t.$options._propKeys||[],c=0;c<s.length;c++){var u=s[c],l=t.$options.props;a[u]=Z(u,l,e,t)}P(!0),t.$options.propsData=e}n=n||ao;var f=t.$options._parentListeners;t.$options._parentListeners=n,Tt(t,n,f),o&&(t.$slots=jt(i,r.context),t.$forceUpdate())}function Pt(t){for(;t&&(t=t.$parent);)if(t._inactive)return!0;return!1}function Dt(t,e){if(e){if(t._directInactive=!1,Pt(t))return}else if(t._directInactive)return;if(t._inactive||null===t._inactive){t._inactive=!1;for(var n=0;n<t.$children.length;n++)Dt(t.$children[n]);Rt(t,"activated")}}function Mt(t,e){if(!(e&&(t._directInactive=!0,Pt(t))||t._inactive)){t._inactive=!0;for(var n=0;n<t.$children.length;n++)Mt(t.$children[n]);Rt(t,"deactivated")}}function Rt(t,e){E();var n=t.$options[e];if(n)for(var r=0,i=n.length;r<i;r++)try{n[r].call(t)}catch(n){rt(n,t,e+" hook")}t._hasHookEvent&&t.$emit("hook:"+e),L()}function Ft(){ba=va.length=ha.length=0,ma={},ya=ga=!1}function Ut(){ga=!0;var t,e;for(va.sort(function(t,e){return t.id-e.id}),ba=0;ba<va.length;ba++)t=va[ba],e=t.id,ma[e]=null,t.run();var n=ha.slice(),r=va.slice();Ft(),Vt(n),Bt(r),Uo&&ko.devtools&&Uo.emit("flush")}function Bt(t){for(var e=t.length;e--;){var n=t[e],r=n.vm;r._watcher===n&&r._isMounted&&Rt(r,"updated")}}function Ht(t){t._inactive=!1,ha.push(t)}function Vt(t){for(var e=0;e<t.length;e++)t[e]._inactive=!0,Dt(t[e],!0)}function zt(t){var e=t.id;if(null==ma[e]){if(ma[e]=!0,ga){for(var n=va.length-1;n>ba&&va[n].id>t.id;)n--;va.splice(n+1,0,t)}else va.push(t);ya||(ya=!0,ct(Ut))}}function qt(t,e,n){xa.get=function(){return this[e][n]},xa.set=function(t){this[e][n]=t},Object.defineProperty(t,n,xa)}function Jt(t){t._watchers=[];var e=t.$options;e.props&&Kt(t,e.props),e.methods&&Yt(t,e.methods),e.data?Wt(t):R(t._data={},!0),e.computed&&Qt(t,e.computed),e.watch&&e.watch!==Io&&te(t,e.watch)}function Kt(t,e){var n=t.$options.propsData||{},r=t._props={},i=t.$options._propKeys=[];!t.$parent||P(!1);for(var o in e)!function(o){i.push(o);var a=Z(o,e,n,t);F(r,o,a),o in t||qt(t,"_props",o)}(o);P(!0)}function Wt(t){var e=t.$options.data;e=t._data="function"==typeof e?Gt(e,t):e||{},u(e)||(e={});for(var n=Object.keys(e),r=t.$options.props,i=(t.$options.methods,n.length);i--;){var o=n[i];r&&m(r,o)||O(o)||qt(t,"_data",o)}R(e,!0)}function Gt(t,e){E();try{return t.call(e,e)}catch(t){return rt(t,e,"data()"),{}}finally{L()}}function Qt(t,e){var n=t._computedWatchers=Object.create(null),r=Fo();for(var i in e){var o=e[i],a="function"==typeof o?o:o.get;r||(n[i]=new wa(t,a||k,k,ka)),i in t||Xt(t,i,o)}}function Xt(t,e,n){var r=!Fo();"function"==typeof n?(xa.get=r?Zt(e):n,xa.set=k):(xa.get=n.get?r&&!1!==n.cache?Zt(e):n.get:k,xa.set=n.set?n.set:k),Object.defineProperty(t,e,xa)}function Zt(t){return function(){var e=this._computedWatchers&&this._computedWatchers[t];if(e)return e.dirty&&e.evaluate(),zo.target&&e.depend(),e.value}}function Yt(t,e){t.$options.props;for(var n in e)t[n]=null==e[n]?k:yo(e[n],t)}function te(t,e){for(var n in e){var r=e[n];if(Array.isArray(r))for(var i=0;i<r.length;i++)ee(t,n,r[i]);else ee(t,n,r)}}function ee(t,e,n,r){return u(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=t[n]),t.$watch(e,n,r)}function ne(t){var e=t.$options.provide;e&&(t._provided="function"==typeof e?e.call(t):e)}function re(t){var e=ie(t.$options.inject,t);e&&(P(!1),Object.keys(e).forEach(function(n){F(t,n,e[n])}),P(!0))}function ie(t,e){if(t){for(var n=Object.create(null),r=Bo?Reflect.ownKeys(t).filter(function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}):Object.keys(t),i=0;i<r.length;i++){for(var o=r[i],a=t[o].from,s=e;s;){if(s._provided&&m(s._provided,a)){n[o]=s._provided[a];break}s=s.$parent}if(!s&&"default"in t[o]){var c=t[o].default;n[o]="function"==typeof c?c.call(e):c}}return n}}function oe(t,e){var n,r,o,a,s;if(Array.isArray(t)||"string"==typeof t)for(n=new Array(t.length),r=0,o=t.length;r<o;r++)n[r]=e(t[r],r);else if("number"==typeof t)for(n=new Array(t),r=0;r<t;r++)n[r]=e(r+1,r);else if(c(t))for(a=Object.keys(t),n=new Array(a.length),r=0,o=a.length;r<o;r++)s=a[r],n[r]=e(t[s],s,r);return i(n)&&(n._isVList=!0),n}function ae(t,e,n,r){var i,o=this.$scopedSlots[t];if(o)n=n||{},r&&(n=w(w({},r),n)),i=o(n)||e;else{var a=this.$slots[t];a&&(a._rendered=!0),i=a||e}var s=n&&n.slot;return s?this.$createElement("template",{slot:s},i):i}function se(t){return X(this.$options,"filters",t,!0)||bo}function ce(t,e){return Array.isArray(t)?-1===t.indexOf(e):t!==e}function ue(t,e,n,r,i){var o=ko.keyCodes[e]||n;return i&&r&&!ko.keyCodes[e]?ce(i,r):o?ce(o,t):r?mo(r)!==e:void 0}function le(t,e,n,r,i){if(n)if(c(n)){Array.isArray(n)&&(n=x(n));var o;for(var a in n)!function(a){if("class"===a||"style"===a||uo(a))o=t;else{var s=t.attrs&&t.attrs.type;o=r||ko.mustUseProp(e,s,a)?t.domProps||(t.domProps={}):t.attrs||(t.attrs={})}if(!(a in o)&&(o[a]=n[a],i)){(t.on||(t.on={}))["update:"+a]=function(t){n[a]=t}}}(a)}else;return t}function fe(t,e){var n=this._staticTrees||(this._staticTrees=[]),r=n[t];return r&&!e?r:(r=n[t]=this.$options.staticRenderFns[t].call(this._renderProxy,null,this),pe(r,"__static__"+t,!1),r)}function de(t,e,n){return pe(t,"__once__"+e+(n?"_"+n:""),!0),t}function pe(t,e,n){if(Array.isArray(t))for(var r=0;r<t.length;r++)t[r]&&"string"!=typeof t[r]&&ve(t[r],e+"_"+r,n);else ve(t,e,n)}function ve(t,e,n){t.isStatic=!0,t.key=e,t.isOnce=n}function he(t,e){if(e)if(u(e)){var n=t.on=t.on?w({},t.on):{};for(var r in e){var i=n[r],o=e[r];n[r]=i?[].concat(i,o):o}}else;return t}function me(t){t._o=de,t._n=p,t._s=d,t._l=oe,t._t=ae,t._q=$,t._i=C,t._m=fe,t._f=se,t._k=ue,t._b=le,t._v=N,t._e=Wo,t._u=Et,t._g=he}function ye(t,e,n,r,i){var a,s=i.options;m(r,"_uid")?(a=Object.create(r),a._original=r):(a=r,r=r._original);var c=o(s._compiled),u=!c;this.data=t,this.props=e,this.children=n,this.parent=r,this.listeners=t.on||ao,this.injections=ie(s.inject,r),this.slots=function(){return jt(n,r)},c&&(this.$options=s,this.$slots=this.slots(),this.$scopedSlots=t.scopedSlots||ao),s._scopeId?this._c=function(t,e,n,i){var o=Ce(a,t,e,n,i,u);return o&&!Array.isArray(o)&&(o.fnScopeId=s._scopeId,o.fnContext=r),o}:this._c=function(t,e,n,r){return Ce(a,t,e,n,r,u)}}function ge(t,e,n,r,o){var a=t.options,s={},c=a.props;if(i(c))for(var u in c)s[u]=Z(u,c,e||ao);else i(n.attrs)&&_e(s,n.attrs),i(n.props)&&_e(s,n.props);var l=new ye(n,s,o,r,t),f=a.render.call(null,l._c,l);if(f instanceof Jo)return be(f,n,l.parent,a);if(Array.isArray(f)){for(var d=yt(f)||[],p=new Array(d.length),v=0;v<d.length;v++)p[v]=be(d[v],n,l.parent,a);return p}}function be(t,e,n,r){var i=I(t);return i.fnContext=n,i.fnOptions=r,e.slot&&((i.data||(i.data={})).slot=e.slot),i}function _e(t,e){for(var n in e)t[po(n)]=e[n]}function we(t,e,n,a,s){if(!r(t)){var u=n.$options._base;if(c(t)&&(t=u.extend(t)),"function"==typeof t){var l;if(r(t.cid)&&(l=t,void 0===(t=xt(l,u,n))))return wt(l,e,n,a,s);e=e||{},Ee(t),i(e.model)&&$e(t.options,e);var f=vt(e,t,s);if(o(t.options.functional))return ge(t,f,e,n,a);var d=e.on;if(e.on=e.nativeOn,o(t.options.abstract)){var p=e.slot;e={},p&&(e.slot=p)}ke(e);var v=t.options.name||s;return new Jo("vue-component-"+t.cid+(v?"-"+v:""),e,void 0,void 0,void 0,n,{Ctor:t,propsData:f,listeners:d,tag:s,children:a},l)}}}function xe(t,e,n,r){var o={_isComponent:!0,parent:e,_parentVnode:t,_parentElm:n||null,_refElm:r||null},a=t.data.inlineTemplate;return i(a)&&(o.render=a.render,o.staticRenderFns=a.staticRenderFns),new t.componentOptions.Ctor(o)}function ke(t){for(var e=t.hook||(t.hook={}),n=0;n<Ca.length;n++){var r=Ca[n];e[r]=$a[r]}}function $e(t,e){var n=t.model&&t.model.prop||"value",r=t.model&&t.model.event||"input";(e.props||(e.props={}))[n]=e.model.value;var o=e.on||(e.on={});i(o[r])?o[r]=[e.model.callback].concat(o[r]):o[r]=e.model.callback}function Ce(t,e,n,r,i,a){return(Array.isArray(n)||s(n))&&(i=r,r=n,n=void 0),o(a)&&(i=Oa),Ae(t,e,n,r,i)}function Ae(t,e,n,r,o){if(i(n)&&i(n.__ob__))return Wo();if(i(n)&&i(n.is)&&(e=n.is),!e)return Wo();Array.isArray(r)&&"function"==typeof r[0]&&(n=n||{},n.scopedSlots={default:r[0]},r.length=0),o===Oa?r=yt(r):o===Aa&&(r=mt(r));var a,s;if("string"==typeof e){var c;s=t.$vnode&&t.$vnode.ns||ko.getTagNamespace(e),a=ko.isReservedTag(e)?new Jo(ko.parsePlatformTagName(e),n,r,void 0,void 0,t):i(c=X(t.$options,"components",e))?we(c,n,t,r,e):new Jo(e,n,r,void 0,void 0,t)}else a=we(e,n,t,r);return Array.isArray(a)?a:i(a)?(i(s)&&Oe(a,s),i(n)&&Te(n),a):Wo()}function Oe(t,e,n){if(t.ns=e,"foreignObject"===t.tag&&(e=void 0,n=!0),i(t.children))for(var a=0,s=t.children.length;a<s;a++){var c=t.children[a];i(c.tag)&&(r(c.ns)||o(n)&&"svg"!==c.tag)&&Oe(c,e,n)}}function Te(t){c(t.style)&&ut(t.style),c(t.class)&&ut(t.class)}function je(t){t._vnode=null,t._staticTrees=null;var e=t.$options,n=t.$vnode=e._parentVnode,r=n&&n.context;t.$slots=jt(e._renderChildren,r),t.$scopedSlots=ao,t._c=function(e,n,r,i){return Ce(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Ce(t,e,n,r,i,!0)};var i=n&&n.data;F(t,"$attrs",i&&i.attrs||ao,null,!0),F(t,"$listeners",e._parentListeners||ao,null,!0)}function Se(t,e){var n=t.$options=Object.create(t.constructor.options),r=e._parentVnode;n.parent=e.parent,n._parentVnode=r,n._parentElm=e._parentElm,n._refElm=e._refElm;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,e.render&&(n.render=e.render,n.staticRenderFns=e.staticRenderFns)}function Ee(t){var e=t.options;if(t.super){var n=Ee(t.super);if(n!==t.superOptions){t.superOptions=n;var r=Le(t);r&&w(t.extendOptions,r),e=t.options=Q(n,t.extendOptions),e.name&&(e.components[e.name]=t)}}return e}function Le(t){var e,n=t.options,r=t.extendOptions,i=t.sealedOptions;for(var o in n)n[o]!==i[o]&&(e||(e={}),e[o]=Ne(n[o],r[o],i[o]));return e}function Ne(t,e,n){if(Array.isArray(t)){var r=[];n=Array.isArray(n)?n:[n],e=Array.isArray(e)?e:[e];for(var i=0;i<t.length;i++)(e.indexOf(t[i])>=0||n.indexOf(t[i])<0)&&r.push(t[i]);return r}return t}function Ie(t){this._init(t)}function Pe(t){t.use=function(t){var e=this._installedPlugins||(this._installedPlugins=[]);if(e.indexOf(t)>-1)return this;var n=_(arguments,1);return n.unshift(this),"function"==typeof t.install?t.install.apply(t,n):"function"==typeof t&&t.apply(null,n),e.push(t),this}}function De(t){t.mixin=function(t){return this.options=Q(this.options,t),this}}function Me(t){t.cid=0;var e=1;t.extend=function(t){t=t||{};var n=this,r=n.cid,i=t._Ctor||(t._Ctor={});if(i[r])return i[r];var o=t.name||n.options.name,a=function(t){this._init(t)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=e++,a.options=Q(n.options,t),a.super=n,a.options.props&&Re(a),a.options.computed&&Fe(a),a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,wo.forEach(function(t){a[t]=n[t]}),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=t,a.sealedOptions=w({},a.options),i[r]=a,a}}function Re(t){var e=t.options.props;for(var n in e)qt(t.prototype,"_props",n)}function Fe(t){var e=t.options.computed;for(var n in e)Xt(t.prototype,n,e[n])}function Ue(t){wo.forEach(function(e){t[e]=function(t,n){return n?("component"===e&&u(n)&&(n.name=n.name||t,n=this.options._base.extend(n)),"directive"===e&&"function"==typeof n&&(n={bind:n,update:n}),this.options[e+"s"][t]=n,n):this.options[e+"s"][t]}})}function Be(t){return t&&(t.Ctor.options.name||t.tag)}function He(t,e){return Array.isArray(t)?t.indexOf(e)>-1:"string"==typeof t?t.split(",").indexOf(e)>-1:!!l(t)&&t.test(e)}function Ve(t,e){var n=t.cache,r=t.keys,i=t._vnode;for(var o in n){var a=n[o];if(a){var s=Be(a.componentOptions);s&&!e(s)&&ze(n,o,r,i)}}}function ze(t,e,n,r){var i=t[e];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),t[e]=null,h(n,e)}function qe(t){for(var e=t.data,n=t,r=t;i(r.componentInstance);)(r=r.componentInstance._vnode)&&r.data&&(e=Je(r.data,e));for(;i(n=n.parent);)n&&n.data&&(e=Je(e,n.data));return Ke(e.staticClass,e.class)}function Je(t,e){return{staticClass:We(t.staticClass,e.staticClass),class:i(t.class)?[t.class,e.class]:e.class}}function Ke(t,e){return i(t)||i(e)?We(t,Ge(e)):""}function We(t,e){return t?e?t+" "+e:t:e||""}function Ge(t){return Array.isArray(t)?Qe(t):c(t)?Xe(t):"string"==typeof t?t:""}function Qe(t){for(var e,n="",r=0,o=t.length;r<o;r++)i(e=Ge(t[r]))&&""!==e&&(n&&(n+=" "),n+=e);return n}function Xe(t){var e="";for(var n in t)t[n]&&(e&&(e+=" "),e+=n);return e}function Ze(t){return Za(t)?"svg":"math"===t?"math":void 0}function Ye(t){if(!Ao)return!0;if(ts(t))return!1;if(t=t.toLowerCase(),null!=es[t])return es[t];var e=document.createElement(t);return t.indexOf("-")>-1?es[t]=e.constructor===window.HTMLUnknownElement||e.constructor===window.HTMLElement:es[t]=/HTMLUnknownElement/.test(e.toString())}function tn(t){if("string"==typeof t){var e=document.querySelector(t);return e||document.createElement("div")}return t}function en(t,e){var n=document.createElement(t);return"select"!==t?n:(e.data&&e.data.attrs&&void 0!==e.data.attrs.multiple&&n.setAttribute("multiple","multiple"),n)}function nn(t,e){return document.createElementNS(Qa[t],e)}function rn(t){return document.createTextNode(t)}function on(t){return document.createComment(t)}function an(t,e,n){t.insertBefore(e,n)}function sn(t,e){t.removeChild(e)}function cn(t,e){t.appendChild(e)}function un(t){return t.parentNode}function ln(t){return t.nextSibling}function fn(t){return t.tagName}function dn(t,e){t.textContent=e}function pn(t,e){t.setAttribute(e,"")}function vn(t,e){var n=t.data.ref;if(i(n)){var r=t.context,o=t.componentInstance||t.elm,a=r.$refs;e?Array.isArray(a[n])?h(a[n],o):a[n]===o&&(a[n]=void 0):t.data.refInFor?Array.isArray(a[n])?a[n].indexOf(o)<0&&a[n].push(o):a[n]=[o]:a[n]=o}}function hn(t,e){return t.key===e.key&&(t.tag===e.tag&&t.isComment===e.isComment&&i(t.data)===i(e.data)&&mn(t,e)||o(t.isAsyncPlaceholder)&&t.asyncFactory===e.asyncFactory&&r(e.asyncFactory.error))}function mn(t,e){if("input"!==t.tag)return!0;var n,r=i(n=t.data)&&i(n=n.attrs)&&n.type,o=i(n=e.data)&&i(n=n.attrs)&&n.type;return r===o||ns(r)&&ns(o)}function yn(t,e,n){var r,o,a={};for(r=e;r<=n;++r)o=t[r].key,i(o)&&(a[o]=r);return a}function gn(t,e){(t.data.directives||e.data.directives)&&bn(t,e)}function bn(t,e){var n,r,i,o=t===os,a=e===os,s=_n(t.data.directives,t.context),c=_n(e.data.directives,e.context),u=[],l=[];for(n in c)r=s[n],i=c[n],r?(i.oldValue=r.value,xn(i,"update",e,t),i.def&&i.def.componentUpdated&&l.push(i)):(xn(i,"bind",e,t),i.def&&i.def.inserted&&u.push(i));if(u.length){var f=function(){for(var n=0;n<u.length;n++)xn(u[n],"inserted",e,t)};o?pt(e,"insert",f):f()}if(l.length&&pt(e,"postpatch",function(){for(var n=0;n<l.length;n++)xn(l[n],"componentUpdated",e,t)}),!o)for(n in s)c[n]||xn(s[n],"unbind",t,t,a)}function _n(t,e){var n=Object.create(null);if(!t)return n;var r,i;for(r=0;r<t.length;r++)i=t[r],i.modifiers||(i.modifiers=cs),n[wn(i)]=i,i.def=X(e.$options,"directives",i.name,!0);return n}function wn(t){return t.rawName||t.name+"."+Object.keys(t.modifiers||{}).join(".")}function xn(t,e,n,r,i){var o=t.def&&t.def[e];if(o)try{o(n.elm,t,n,r,i)}catch(r){rt(r,n.context,"directive "+t.name+" "+e+" hook")}}function kn(t,e){var n=e.componentOptions;if(!(i(n)&&!1===n.Ctor.options.inheritAttrs||r(t.data.attrs)&&r(e.data.attrs))){var o,a,s=e.elm,c=t.data.attrs||{},u=e.data.attrs||{};i(u.__ob__)&&(u=e.data.attrs=w({},u));for(o in u)a=u[o],c[o]!==a&&$n(s,o,a);(So||Lo)&&u.value!==c.value&&$n(s,"value",u.value);for(o in c)r(u[o])&&(Ka(o)?s.removeAttributeNS(Ja,Wa(o)):za(o)||s.removeAttribute(o))}}function $n(t,e,n){t.tagName.indexOf("-")>-1?Cn(t,e,n):qa(e)?Ga(n)?t.removeAttribute(e):(n="allowfullscreen"===e&&"EMBED"===t.tagName?"true":e,t.setAttribute(e,n)):za(e)?t.setAttribute(e,Ga(n)||"false"===n?"false":"true"):Ka(e)?Ga(n)?t.removeAttributeNS(Ja,Wa(e)):t.setAttributeNS(Ja,e,n):Cn(t,e,n)}function Cn(t,e,n){if(Ga(n))t.removeAttribute(e);else{if(So&&!Eo&&"TEXTAREA"===t.tagName&&"placeholder"===e&&!t.__ieph){var r=function(e){e.stopImmediatePropagation(),t.removeEventListener("input",r)};t.addEventListener("input",r),t.__ieph=!0}t.setAttribute(e,n)}}function An(t,e){var n=e.elm,o=e.data,a=t.data;if(!(r(o.staticClass)&&r(o.class)&&(r(a)||r(a.staticClass)&&r(a.class)))){var s=qe(e),c=n._transitionClasses;i(c)&&(s=We(s,Ge(c))),s!==n._prevClass&&(n.setAttribute("class",s),n._prevClass=s)}}function On(t){function e(){(a||(a=[])).push(t.slice(v,i).trim()),v=i+1}var n,r,i,o,a,s=!1,c=!1,u=!1,l=!1,f=0,d=0,p=0,v=0;for(i=0;i<t.length;i++)if(r=n,n=t.charCodeAt(i),s)39===n&&92!==r&&(s=!1);else if(c)34===n&&92!==r&&(c=!1);else if(u)96===n&&92!==r&&(u=!1);else if(l)47===n&&92!==r&&(l=!1);else if(124!==n||124===t.charCodeAt(i+1)||124===t.charCodeAt(i-1)||f||d||p){switch(n){case 34:c=!0;break;case 39:s=!0;break;case 96:u=!0;break;case 40:p++;break;case 41:p--;break;case 91:d++;break;case 93:d--;break;case 123:f++;break;case 125:f--}if(47===n){for(var h=i-1,m=void 0;h>=0&&" "===(m=t.charAt(h));h--);m&&ds.test(m)||(l=!0)}}else void 0===o?(v=i+1,o=t.slice(0,i).trim()):e();if(void 0===o?o=t.slice(0,i).trim():0!==v&&e(),a)for(i=0;i<a.length;i++)o=Tn(o,a[i]);return o}function Tn(t,e){var n=e.indexOf("(");if(n<0)return'_f("'+e+'")('+t+")";var r=e.slice(0,n),i=e.slice(n+1);return'_f("'+r+'")('+t+(")"!==i?","+i:i)}function jn(t){console.error("[Vue compiler]: "+t)}function Sn(t,e){return t?t.map(function(t){return t[e]}).filter(function(t){return t}):[]}function En(t,e,n){(t.props||(t.props=[])).push({name:e,value:n}),t.plain=!1}function Ln(t,e,n){(t.attrs||(t.attrs=[])).push({name:e,value:n}),t.plain=!1}function Nn(t,e,n){t.attrsMap[e]=n,t.attrsList.push({name:e,value:n})}function In(t,e,n,r,i,o){(t.directives||(t.directives=[])).push({name:e,rawName:n,value:r,arg:i,modifiers:o}),t.plain=!1}function Pn(t,e,n,r,i,o){r=r||ao,r.capture&&(delete r.capture,e="!"+e),r.once&&(delete r.once,e="~"+e),r.passive&&(delete r.passive,e="&"+e),"click"===e&&(r.right?(e="contextmenu",delete r.right):r.middle&&(e="mouseup"));var a;r.native?(delete r.native,a=t.nativeEvents||(t.nativeEvents={})):a=t.events||(t.events={});var s={value:n.trim()};r!==ao&&(s.modifiers=r);var c=a[e];Array.isArray(c)?i?c.unshift(s):c.push(s):a[e]=c?i?[s,c]:[c,s]:s,t.plain=!1}function Dn(t,e,n){var r=Mn(t,":"+e)||Mn(t,"v-bind:"+e);if(null!=r)return On(r);if(!1!==n){var i=Mn(t,e);if(null!=i)return JSON.stringify(i)}}function Mn(t,e,n){var r;if(null!=(r=t.attrsMap[e]))for(var i=t.attrsList,o=0,a=i.length;o<a;o++)if(i[o].name===e){i.splice(o,1);break}return n&&delete t.attrsMap[e],r}function Rn(t,e,n){var r=n||{},i=r.number,o=r.trim,a="$$v";o&&(a="(typeof $$v === 'string'? $$v.trim(): $$v)"),i&&(a="_n("+a+")");var s=Fn(e,a);t.model={value:"("+e+")",expression:'"'+e+'"',callback:"function ($$v) {"+s+"}"}}function Fn(t,e){var n=Un(t);return null===n.key?t+"="+e:"$set("+n.exp+", "+n.key+", "+e+")"}function Un(t){if(t=t.trim(),La=t.length,t.indexOf("[")<0||t.lastIndexOf("]")<La-1)return Pa=t.lastIndexOf("."),Pa>-1?{exp:t.slice(0,Pa),key:'"'+t.slice(Pa+1)+'"'}:{exp:t,key:null};for(Na=t,Pa=Da=Ma=0;!Hn();)Ia=Bn(),Vn(Ia)?qn(Ia):91===Ia&&zn(Ia);return{exp:t.slice(0,Da),key:t.slice(Da+1,Ma)}}function Bn(){return Na.charCodeAt(++Pa)}function Hn(){return Pa>=La}function Vn(t){return 34===t||39===t}function zn(t){var e=1;for(Da=Pa;!Hn();)if(t=Bn(),Vn(t))qn(t);else if(91===t&&e++,93===t&&e--,0===e){Ma=Pa;break}}function qn(t){for(var e=t;!Hn()&&(t=Bn())!==e;);}function Jn(t,e,n){Ra=n;var r=e.value,i=e.modifiers,o=t.tag,a=t.attrsMap.type;if(t.component)return Rn(t,r,i),!1;if("select"===o)Gn(t,r,i);else if("input"===o&&"checkbox"===a)Kn(t,r,i);else if("input"===o&&"radio"===a)Wn(t,r,i);else if("input"===o||"textarea"===o)Qn(t,r,i);else if(!ko.isReservedTag(o))return Rn(t,r,i),!1;return!0}function Kn(t,e,n){var r=n&&n.number,i=Dn(t,"value")||"null",o=Dn(t,"true-value")||"true",a=Dn(t,"false-value")||"false";En(t,"checked","Array.isArray("+e+")?_i("+e+","+i+")>-1"+("true"===o?":("+e+")":":_q("+e+","+o+")")),Pn(t,"change","var $$a="+e+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+Fn(e,"$$a.concat([$$v])")+")}else{$$i>-1&&("+Fn(e,"$$a.slice(0,$$i).concat($$a.slice($$i+1))")+")}}else{"+Fn(e,"$$c")+"}",null,!0)}function Wn(t,e,n){var r=n&&n.number,i=Dn(t,"value")||"null";i=r?"_n("+i+")":i,En(t,"checked","_q("+e+","+i+")"),Pn(t,"change",Fn(e,i),null,!0)}function Gn(t,e,n){var r=n&&n.number,i='Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return '+(r?"_n(val)":"val")+"})",o="var $$selectedVal = "+i+";";o=o+" "+Fn(e,"$event.target.multiple ? $$selectedVal : $$selectedVal[0]"),Pn(t,"change",o,null,!0)}function Qn(t,e,n){var r=t.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?ps:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=Fn(e,l);c&&(f="if($event.target.composing)return;"+f),En(t,"value","("+e+")"),Pn(t,u,f,null,!0),(s||a)&&Pn(t,"blur","$forceUpdate()")}function Xn(t){if(i(t[ps])){var e=So?"change":"input";t[e]=[].concat(t[ps],t[e]||[]),delete t[ps]}i(t[vs])&&(t.change=[].concat(t[vs],t.change||[]),delete t[vs])}function Zn(t,e,n){var r=Fa;return function i(){null!==t.apply(null,arguments)&&tr(e,i,n,r)}}function Yn(t,e,n,r,i){e=st(e),n&&(e=Zn(e,t,r)),Fa.addEventListener(t,e,Po?{capture:r,passive:i}:r)}function tr(t,e,n,r){(r||Fa).removeEventListener(t,e._withTask||e,n)}function er(t,e){if(!r(t.data.on)||!r(e.data.on)){var n=e.data.on||{},i=t.data.on||{};Fa=e.elm,Xn(n),dt(n,i,Yn,tr,e.context),Fa=void 0}}function nr(t,e){if(!r(t.data.domProps)||!r(e.data.domProps)){var n,o,a=e.elm,s=t.data.domProps||{},c=e.data.domProps||{};i(c.__ob__)&&(c=e.data.domProps=w({},c));for(n in s)r(c[n])&&(a[n]="");for(n in c){if(o=c[n],"textContent"===n||"innerHTML"===n){if(e.children&&(e.children.length=0),o===s[n])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===n){a._value=o;var u=r(o)?"":String(o);rr(a,u)&&(a.value=u)}else a[n]=o}}}function rr(t,e){return!t.composing&&("OPTION"===t.tagName||ir(t,e)||or(t,e))}function ir(t,e){var n=!0;try{n=document.activeElement!==t}catch(t){}return n&&t.value!==e}function or(t,e){var n=t.value,r=t._vModifiers;if(i(r)){if(r.lazy)return!1;if(r.number)return p(n)!==p(e);if(r.trim)return n.trim()!==e.trim()}return n!==e}function ar(t){var e=sr(t.style);return t.staticStyle?w(t.staticStyle,e):e}function sr(t){return Array.isArray(t)?x(t):"string"==typeof t?ys(t):t}function cr(t,e){var n,r={};if(e)for(var i=t;i.componentInstance;)(i=i.componentInstance._vnode)&&i.data&&(n=ar(i.data))&&w(r,n);(n=ar(t.data))&&w(r,n);for(var o=t;o=o.parent;)o.data&&(n=ar(o.data))&&w(r,n);return r}function ur(t,e){var n=e.data,o=t.data;if(!(r(n.staticStyle)&&r(n.style)&&r(o.staticStyle)&&r(o.style))){var a,s,c=e.elm,u=o.staticStyle,l=o.normalizedStyle||o.style||{},f=u||l,d=sr(e.data.style)||{};e.data.normalizedStyle=i(d.__ob__)?w({},d):d;var p=cr(e,!0);for(s in f)r(p[s])&&_s(c,s,"");for(s in p)(a=p[s])!==f[s]&&_s(c,s,null==a?"":a)}}function lr(t,e){if(e&&(e=e.trim()))if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.add(e)}):t.classList.add(e);else{var n=" "+(t.getAttribute("class")||"")+" ";n.indexOf(" "+e+" ")<0&&t.setAttribute("class",(n+e).trim())}}function fr(t,e){if(e&&(e=e.trim()))if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.remove(e)}):t.classList.remove(e),t.classList.length||t.removeAttribute("class");else{for(var n=" "+(t.getAttribute("class")||"")+" ",r=" "+e+" ";n.indexOf(r)>=0;)n=n.replace(r," ");n=n.trim(),n?t.setAttribute("class",n):t.removeAttribute("class")}}function dr(t){if(t){if("object"==typeof t){var e={};return!1!==t.css&&w(e,$s(t.name||"v")),w(e,t),e}return"string"==typeof t?$s(t):void 0}}function pr(t){Ls(function(){Ls(t)})}function vr(t,e){var n=t._transitionClasses||(t._transitionClasses=[]);n.indexOf(e)<0&&(n.push(e),lr(t,e))}function hr(t,e){t._transitionClasses&&h(t._transitionClasses,e),fr(t,e)}function mr(t,e,n){var r=yr(t,e),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===As?js:Es,c=0,u=function(){t.removeEventListener(s,l),n()},l=function(e){e.target===t&&++c>=a&&u()};setTimeout(function(){c<a&&u()},o+1),t.addEventListener(s,l)}function yr(t,e){var n,r=window.getComputedStyle(t),i=r[Ts+"Delay"].split(", "),o=r[Ts+"Duration"].split(", "),a=gr(i,o),s=r[Ss+"Delay"].split(", "),c=r[Ss+"Duration"].split(", "),u=gr(s,c),l=0,f=0;return e===As?a>0&&(n=As,l=a,f=o.length):e===Os?u>0&&(n=Os,l=u,f=c.length):(l=Math.max(a,u),n=l>0?a>u?As:Os:null,f=n?n===As?o.length:c.length:0),{type:n,timeout:l,propCount:f,hasTransform:n===As&&Ns.test(r[Ts+"Property"])}}function gr(t,e){for(;t.length<e.length;)t=t.concat(t);return Math.max.apply(null,e.map(function(e,n){return br(e)+br(t[n])}))}function br(t){return 1e3*Number(t.slice(0,-1))}function _r(t,e){var n=t.elm;i(n._leaveCb)&&(n._leaveCb.cancelled=!0,n._leaveCb());var o=dr(t.data.transition);if(!r(o)&&!i(n._enterCb)&&1===n.nodeType){for(var a=o.css,s=o.type,u=o.enterClass,l=o.enterToClass,f=o.enterActiveClass,d=o.appearClass,v=o.appearToClass,h=o.appearActiveClass,m=o.beforeEnter,y=o.enter,g=o.afterEnter,b=o.enterCancelled,_=o.beforeAppear,w=o.appear,x=o.afterAppear,k=o.appearCancelled,$=o.duration,C=pa,O=pa.$vnode;O&&O.parent;)O=O.parent,C=O.context;var T=!C._isMounted||!t.isRootInsert;if(!T||w||""===w){var j=T&&d?d:u,S=T&&h?h:f,E=T&&v?v:l,L=T?_||m:m,N=T&&"function"==typeof w?w:y,I=T?x||g:g,P=T?k||b:b,D=p(c($)?$.enter:$),M=!1!==a&&!Eo,R=kr(N),F=n._enterCb=A(function(){M&&(hr(n,E),hr(n,S)),F.cancelled?(M&&hr(n,j),P&&P(n)):I&&I(n),n._enterCb=null});t.data.show||pt(t,"insert",function(){var e=n.parentNode,r=e&&e._pending&&e._pending[t.key];r&&r.tag===t.tag&&r.elm._leaveCb&&r.elm._leaveCb(),N&&N(n,F)}),L&&L(n),M&&(vr(n,j),vr(n,S),pr(function(){hr(n,j),F.cancelled||(vr(n,E),R||(xr(D)?setTimeout(F,D):mr(n,s,F)))})),t.data.show&&(e&&e(),N&&N(n,F)),M||R||F()}}}function wr(t,e){function n(){k.cancelled||(t.data.show||((o.parentNode._pending||(o.parentNode._pending={}))[t.key]=t),v&&v(o),_&&(vr(o,l),vr(o,d),pr(function(){hr(o,l),k.cancelled||(vr(o,f),w||(xr(x)?setTimeout(k,x):mr(o,u,k)))})),h&&h(o,k),_||w||k())}var o=t.elm;i(o._enterCb)&&(o._enterCb.cancelled=!0,o._enterCb());var a=dr(t.data.transition);if(r(a)||1!==o.nodeType)return e();if(!i(o._leaveCb)){var s=a.css,u=a.type,l=a.leaveClass,f=a.leaveToClass,d=a.leaveActiveClass,v=a.beforeLeave,h=a.leave,m=a.afterLeave,y=a.leaveCancelled,g=a.delayLeave,b=a.duration,_=!1!==s&&!Eo,w=kr(h),x=p(c(b)?b.leave:b),k=o._leaveCb=A(function(){o.parentNode&&o.parentNode._pending&&(o.parentNode._pending[t.key]=null),_&&(hr(o,f),hr(o,d)),k.cancelled?(_&&hr(o,l),y&&y(o)):(e(),m&&m(o)),o._leaveCb=null});g?g(n):n()}}function xr(t){return"number"==typeof t&&!isNaN(t)}function kr(t){if(r(t))return!1;var e=t.fns;return i(e)?kr(Array.isArray(e)?e[0]:e):(t._length||t.length)>1}function $r(t,e){!0!==e.data.show&&_r(e)}function Cr(t,e,n){Ar(t,e,n),(So||Lo)&&setTimeout(function(){Ar(t,e,n)},0)}function Ar(t,e,n){var r=e.value,i=t.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,c=t.options.length;s<c;s++)if(a=t.options[s],i)o=C(r,Tr(a))>-1,a.selected!==o&&(a.selected=o);else if($(Tr(a),r))return void(t.selectedIndex!==s&&(t.selectedIndex=s));i||(t.selectedIndex=-1)}}function Or(t,e){return e.every(function(e){return!$(e,t)})}function Tr(t){return"_value"in t?t._value:t.value}function jr(t){t.target.composing=!0}function Sr(t){t.target.composing&&(t.target.composing=!1,Er(t.target,"input"))}function Er(t,e){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0),t.dispatchEvent(n)}function Lr(t){return!t.componentInstance||t.data&&t.data.transition?t:Lr(t.componentInstance._vnode)}function Nr(t){var e=t&&t.componentOptions;return e&&e.Ctor.options.abstract?Nr($t(e.children)):t}function Ir(t){var e={},n=t.$options;for(var r in n.propsData)e[r]=t[r];var i=n._parentListeners;for(var o in i)e[po(o)]=i[o];return e}function Pr(t,e){if(/\d-keep-alive$/.test(e.tag))return t("keep-alive",{props:e.componentOptions.propsData})}function Dr(t){for(;t=t.parent;)if(t.data.transition)return!0}function Mr(t,e){return e.key===t.key&&e.tag===t.tag}function Rr(t){t.elm._moveCb&&t.elm._moveCb(),t.elm._enterCb&&t.elm._enterCb()}function Fr(t){t.data.newPos=t.elm.getBoundingClientRect()}function Ur(t){var e=t.data.pos,n=t.data.newPos,r=e.left-n.left,i=e.top-n.top;if(r||i){t.data.moved=!0;var o=t.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}function Br(t,e){var n=e?Gs(e):Ks;if(n.test(t)){for(var r,i,o,a=[],s=[],c=n.lastIndex=0;r=n.exec(t);){i=r.index,i>c&&(s.push(o=t.slice(c,i)),a.push(JSON.stringify(o)));var u=On(r[1].trim());a.push("_s("+u+")"),s.push({"@binding":u}),c=i+r[0].length}return c<t.length&&(s.push(o=t.slice(c)),a.push(JSON.stringify(o))),{expression:a.join("+"),tokens:s}}}function Hr(t,e){var n=(e.warn,Mn(t,"class"));n&&(t.staticClass=JSON.stringify(n));var r=Dn(t,"class",!1);r&&(t.classBinding=r)}function Vr(t){var e="";return t.staticClass&&(e+="staticClass:"+t.staticClass+","),t.classBinding&&(e+="class:"+t.classBinding+","),e}function zr(t,e){var n=(e.warn,Mn(t,"style"));if(n){t.staticStyle=JSON.stringify(ys(n))}var r=Dn(t,"style",!1);r&&(t.styleBinding=r)}function qr(t){var e="";return t.staticStyle&&(e+="staticStyle:"+t.staticStyle+","),t.styleBinding&&(e+="style:("+t.styleBinding+"),"),e}function Jr(t,e){var n=e?Oc:Ac;return t.replace(n,function(t){return Cc[t]})}function Kr(t,e){function n(e){l+=e,t=t.substring(e)}function r(t,n,r){var i,s;if(null==n&&(n=l),null==r&&(r=l),t&&(s=t.toLowerCase()),t)for(i=a.length-1;i>=0&&a[i].lowerCasedTag!==s;i--);else i=0;if(i>=0){for(var c=a.length-1;c>=i;c--)e.end&&e.end(a[c].tag,n,r);a.length=i,o=i&&a[i-1].tag}else"br"===s?e.start&&e.start(t,[],!0,n,r):"p"===s&&(e.start&&e.start(t,[],!1,n,r),e.end&&e.end(t,n,r))}for(var i,o,a=[],s=e.expectHTML,c=e.isUnaryTag||go,u=e.canBeLeftOpenTag||go,l=0;t;){if(i=t,o&&kc(o)){var f=0,d=o.toLowerCase(),p=$c[d]||($c[d]=new RegExp("([\\s\\S]*?)(</"+d+"[^>]*>)","i")),v=t.replace(p,function(t,n,r){return f=r.length,kc(d)||"noscript"===d||(n=n.replace(/<!\--([\s\S]*?)-->/g,"$1").replace(/<!\[CDATA\[([\s\S]*?)]]>/g,"$1")),jc(d,n)&&(n=n.slice(1)),e.chars&&e.chars(n),""});l+=t.length-v.length,t=v,r(d,l-f,l)}else{var h=t.indexOf("<");if(0===h){if(uc.test(t)){var m=t.indexOf("--\x3e");if(m>=0){e.shouldKeepComment&&e.comment(t.substring(4,m)),n(m+3);continue}}if(lc.test(t)){var y=t.indexOf("]>");if(y>=0){n(y+2);continue}}var g=t.match(cc);if(g){n(g[0].length);continue}var b=t.match(sc);if(b){var _=l;n(b[0].length),r(b[1],_,l);continue}var w=function(){var e=t.match(oc);if(e){var r={tagName:e[1],attrs:[],start:l};n(e[0].length);for(var i,o;!(i=t.match(ac))&&(o=t.match(nc));)n(o[0].length),r.attrs.push(o);if(i)return r.unarySlash=i[1],n(i[0].length),r.end=l,r}}();if(w){!function(t){var n=t.tagName,i=t.unarySlash;s&&("p"===o&&ec(n)&&r(o),u(n)&&o===n&&r(n));for(var l=c(n)||!!i,f=t.attrs.length,d=new Array(f),p=0;p<f;p++){var v=t.attrs[p];fc&&-1===v[0].indexOf('""')&&(""===v[3]&&delete v[3],""===v[4]&&delete v[4],""===v[5]&&delete v[5]);var h=v[3]||v[4]||v[5]||"",m="a"===n&&"href"===v[1]?e.shouldDecodeNewlinesForHref:e.shouldDecodeNewlines;d[p]={name:v[1],value:Jr(h,m)}}l||(a.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:d}),o=n),e.start&&e.start(n,d,l,t.start,t.end)}(w),jc(o,t)&&n(1);continue}}var x=void 0,k=void 0,$=void 0;if(h>=0){for(k=t.slice(h);!(sc.test(k)||oc.test(k)||uc.test(k)||lc.test(k)||($=k.indexOf("<",1))<0);)h+=$,k=t.slice(h);x=t.substring(0,h),n(h)}h<0&&(x=t,t=""),e.chars&&x&&e.chars(x)}if(t===i){e.chars&&e.chars(t);break}}r()}function Wr(t,e,n){return{type:1,tag:t,attrsList:e,attrsMap:pi(e),parent:n,children:[]}}function Gr(t,e){function n(t){t.pre&&(s=!1),yc(t.tag)&&(c=!1);for(var n=0;n<mc.length;n++)mc[n](t,e)}dc=e.warn||jn,yc=e.isPreTag||go,gc=e.mustUseProp||go,bc=e.getTagNamespace||go,vc=Sn(e.modules,"transformNode"),hc=Sn(e.modules,"preTransformNode"),mc=Sn(e.modules,"postTransformNode"),pc=e.delimiters;var r,i,o=[],a=!1!==e.preserveWhitespace,s=!1,c=!1;return Kr(t,{warn:dc,expectHTML:e.expectHTML,isUnaryTag:e.isUnaryTag,canBeLeftOpenTag:e.canBeLeftOpenTag,shouldDecodeNewlines:e.shouldDecodeNewlines,shouldDecodeNewlinesForHref:e.shouldDecodeNewlinesForHref,shouldKeepComment:e.comments,start:function(t,a,u){var l=i&&i.ns||bc(t);So&&"svg"===l&&(a=mi(a));var f=Wr(t,a,i);l&&(f.ns=l),hi(f)&&!Fo()&&(f.forbidden=!0);for(var d=0;d<hc.length;d++)f=hc[d](f,e)||f;if(s||(Qr(f),f.pre&&(s=!0)),yc(f.tag)&&(c=!0),s?Xr(f):f.processed||(ei(f),ri(f),si(f),Zr(f,e)),r?o.length||r.if&&(f.elseif||f.else)&&ai(r,{exp:f.elseif,block:f}):r=f,i&&!f.forbidden)if(f.elseif||f.else)ii(f,i);else if(f.slotScope){i.plain=!1;var p=f.slotTarget||'"default"';(i.scopedSlots||(i.scopedSlots={}))[p]=f}else i.children.push(f),f.parent=i;u?n(f):(i=f,o.push(f))},end:function(){var t=o[o.length-1],e=t.children[t.children.length-1];e&&3===e.type&&" "===e.text&&!c&&t.children.pop(),o.length-=1,i=o[o.length-1],n(t)},chars:function(t){if(i&&(!So||"textarea"!==i.tag||i.attrsMap.placeholder!==t)){var e=i.children;if(t=c||t.trim()?vi(i)?t:Rc(t):a&&e.length?" ":""){var n;!s&&" "!==t&&(n=Br(t,pc))?e.push({type:2,expression:n.expression,tokens:n.tokens,text:t}):" "===t&&e.length&&" "===e[e.length-1].text||e.push({type:3,text:t})}}},comment:function(t){i.children.push({type:3,text:t,isComment:!0})}}),r}function Qr(t){null!=Mn(t,"v-pre")&&(t.pre=!0)}function Xr(t){var e=t.attrsList.length;if(e)for(var n=t.attrs=new Array(e),r=0;r<e;r++)n[r]={name:t.attrsList[r].name,value:JSON.stringify(t.attrsList[r].value)};else t.pre||(t.plain=!0)}function Zr(t,e){Yr(t),t.plain=!t.key&&!t.attrsList.length,ti(t),ci(t),ui(t);for(var n=0;n<vc.length;n++)t=vc[n](t,e)||t;li(t)}function Yr(t){var e=Dn(t,"key");e&&(t.key=e)}function ti(t){var e=Dn(t,"ref");e&&(t.ref=e,t.refInFor=fi(t))}function ei(t){var e;if(e=Mn(t,"v-for")){var n=ni(e);n&&w(t,n)}}function ni(t){var e=t.match(Lc);if(e){var n={};n.for=e[2].trim();var r=e[1].trim().replace(Ic,""),i=r.match(Nc);return i?(n.alias=r.replace(Nc,""),n.iterator1=i[1].trim(),i[2]&&(n.iterator2=i[2].trim())):n.alias=r,n}}function ri(t){var e=Mn(t,"v-if");if(e)t.if=e,ai(t,{exp:e,block:t});else{null!=Mn(t,"v-else")&&(t.else=!0);var n=Mn(t,"v-else-if");n&&(t.elseif=n)}}function ii(t,e){var n=oi(e.children);n&&n.if&&ai(n,{exp:t.elseif,block:t})}function oi(t){for(var e=t.length;e--;){if(1===t[e].type)return t[e];t.pop()}}function ai(t,e){t.ifConditions||(t.ifConditions=[]),t.ifConditions.push(e)}function si(t){null!=Mn(t,"v-once")&&(t.once=!0)}function ci(t){if("slot"===t.tag)t.slotName=Dn(t,"name");else{var e;"template"===t.tag?(e=Mn(t,"scope"),t.slotScope=e||Mn(t,"slot-scope")):(e=Mn(t,"slot-scope"))&&(t.slotScope=e);var n=Dn(t,"slot");n&&(t.slotTarget='""'===n?'"default"':n,"template"===t.tag||t.slotScope||Ln(t,"slot",n))}}function ui(t){var e;(e=Dn(t,"is"))&&(t.component=e),null!=Mn(t,"inline-template")&&(t.inlineTemplate=!0)}function li(t){var e,n,r,i,o,a,s,c=t.attrsList;for(e=0,n=c.length;e<n;e++)if(r=i=c[e].name,o=c[e].value,Ec.test(r))if(t.hasBindings=!0,a=di(r),a&&(r=r.replace(Mc,"")),Dc.test(r))r=r.replace(Dc,""),o=On(o),s=!1,a&&(a.prop&&(s=!0,"innerHtml"===(r=po(r))&&(r="innerHTML")),a.camel&&(r=po(r)),a.sync&&Pn(t,"update:"+po(r),Fn(o,"$event"))),s||!t.component&&gc(t.tag,t.attrsMap.type,r)?En(t,r,o):Ln(t,r,o);else if(Sc.test(r))r=r.replace(Sc,""),Pn(t,r,o,a,!1,dc);else{r=r.replace(Ec,"");var u=r.match(Pc),l=u&&u[1];l&&(r=r.slice(0,-(l.length+1))),In(t,r,i,o,l,a)}else{Ln(t,r,JSON.stringify(o)),!t.component&&"muted"===r&&gc(t.tag,t.attrsMap.type,r)&&En(t,r,"true")}}function fi(t){for(var e=t;e;){if(void 0!==e.for)return!0;e=e.parent}return!1}function di(t){var e=t.match(Mc);if(e){var n={};return e.forEach(function(t){n[t.slice(1)]=!0}),n}}function pi(t){for(var e={},n=0,r=t.length;n<r;n++)e[t[n].name]=t[n].value;return e}function vi(t){return"script"===t.tag||"style"===t.tag}function hi(t){return"style"===t.tag||"script"===t.tag&&(!t.attrsMap.type||"text/javascript"===t.attrsMap.type)}function mi(t){for(var e=[],n=0;n<t.length;n++){var r=t[n];Fc.test(r.name)||(r.name=r.name.replace(Uc,""),e.push(r))}return e}function yi(t,e){if("input"===t.tag){var n=t.attrsMap;if(!n["v-model"])return;var r;if((n[":type"]||n["v-bind:type"])&&(r=Dn(t,"type")),n.type||r||!n["v-bind"]||(r="("+n["v-bind"]+").type"),r){var i=Mn(t,"v-if",!0),o=i?"&&("+i+")":"",a=null!=Mn(t,"v-else",!0),s=Mn(t,"v-else-if",!0),c=gi(t);ei(c),Nn(c,"type","checkbox"),Zr(c,e),c.processed=!0,c.if="("+r+")==='checkbox'"+o,ai(c,{exp:c.if,block:c});var u=gi(t);Mn(u,"v-for",!0),Nn(u,"type","radio"),Zr(u,e),ai(c,{exp:"("+r+")==='radio'"+o,block:u});var l=gi(t);return Mn(l,"v-for",!0),Nn(l,":type",r),Zr(l,e),ai(c,{exp:i,block:l}),a?c.else=!0:s&&(c.elseif=s),c}}}function gi(t){return Wr(t.tag,t.attrsList.slice(),t.parent)}function bi(t,e){e.value&&En(t,"textContent","_s("+e.value+")")}function _i(t,e){e.value&&En(t,"innerHTML","_s("+e.value+")")}function wi(t,e){t&&(_c=qc(e.staticKeys||""),wc=e.isReservedTag||go,ki(t),$i(t,!1))}function xi(t){return v("type,tag,attrsList,attrsMap,plain,parent,children,attrs"+(t?","+t:""))}function ki(t){if(t.static=Ci(t),1===t.type){if(!wc(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var e=0,n=t.children.length;e<n;e++){var r=t.children[e];ki(r),r.static||(t.static=!1)}if(t.ifConditions)for(var i=1,o=t.ifConditions.length;i<o;i++){var a=t.ifConditions[i].block;ki(a),a.static||(t.static=!1)}}}function $i(t,e){if(1===t.type){if((t.static||t.once)&&(t.staticInFor=e),t.static&&t.children.length&&(1!==t.children.length||3!==t.children[0].type))return void(t.staticRoot=!0);if(t.staticRoot=!1,t.children)for(var n=0,r=t.children.length;n<r;n++)$i(t.children[n],e||!!t.for);if(t.ifConditions)for(var i=1,o=t.ifConditions.length;i<o;i++)$i(t.ifConditions[i].block,e)}}function Ci(t){return 2!==t.type&&(3===t.type||!(!t.pre&&(t.hasBindings||t.if||t.for||co(t.tag)||!wc(t.tag)||Ai(t)||!Object.keys(t).every(_c))))}function Ai(t){for(;t.parent;){if(t=t.parent,"template"!==t.tag)return!1;if(t.for)return!0}return!1}function Oi(t,e,n){var r=e?"nativeOn:{":"on:{";for(var i in t)r+='"'+i+'":'+Ti(i,t[i])+",";return r.slice(0,-1)+"}"}function Ti(t,e){if(!e)return"function(){}";if(Array.isArray(e))return"["+e.map(function(e){return Ti(t,e)}).join(",")+"]";var n=Kc.test(e.value),r=Jc.test(e.value);if(e.modifiers){var i="",o="",a=[];for(var s in e.modifiers)if(Xc[s])o+=Xc[s],Wc[s]&&a.push(s);else if("exact"===s){var c=e.modifiers;o+=Qc(["ctrl","shift","alt","meta"].filter(function(t){return!c[t]}).map(function(t){return"$event."+t+"Key"}).join("||"))}else a.push(s);a.length&&(i+=ji(a)),o&&(i+=o);return"function($event){"+i+(n?"return "+e.value+"($event)":r?"return ("+e.value+")($event)":e.value)+"}"}return n||r?e.value:"function($event){"+e.value+"}"}function ji(t){return"if(!('button' in $event)&&"+t.map(Si).join("&&")+")return null;"}function Si(t){var e=parseInt(t,10);if(e)return"$event.keyCode!=="+e;var n=Wc[t],r=Gc[t];return"_k($event.keyCode,"+JSON.stringify(t)+","+JSON.stringify(n)+",$event.key,"+JSON.stringify(r)+")"}function Ei(t,e){t.wrapListeners=function(t){return"_g("+t+","+e.value+")"}}function Li(t,e){t.wrapData=function(n){return"_b("+n+",'"+t.tag+"',"+e.value+","+(e.modifiers&&e.modifiers.prop?"true":"false")+(e.modifiers&&e.modifiers.sync?",true":"")+")"}}function Ni(t,e){var n=new Yc(e);return{render:"with(this){return "+(t?Ii(t,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function Ii(t,e){if(t.staticRoot&&!t.staticProcessed)return Pi(t,e);if(t.once&&!t.onceProcessed)return Di(t,e);if(t.for&&!t.forProcessed)return Fi(t,e);if(t.if&&!t.ifProcessed)return Mi(t,e);if("template"!==t.tag||t.slotTarget){if("slot"===t.tag)return Zi(t,e);var n;if(t.component)n=Yi(t.component,t,e);else{var r=t.plain?void 0:Ui(t,e),i=t.inlineTemplate?null:Ji(t,e,!0);n="_c('"+t.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o<e.transforms.length;o++)n=e.transforms[o](t,n);return n}return Ji(t,e)||"void 0"}function Pi(t,e){return t.staticProcessed=!0,e.staticRenderFns.push("with(this){return "+Ii(t,e)+"}"),"_m("+(e.staticRenderFns.length-1)+(t.staticInFor?",true":"")+")"}function Di(t,e){if(t.onceProcessed=!0,t.if&&!t.ifProcessed)return Mi(t,e);if(t.staticInFor){for(var n="",r=t.parent;r;){if(r.for){n=r.key;break}r=r.parent}return n?"_o("+Ii(t,e)+","+e.onceId+++","+n+")":Ii(t,e)}return Pi(t,e)}function Mi(t,e,n,r){return t.ifProcessed=!0,Ri(t.ifConditions.slice(),e,n,r)}function Ri(t,e,n,r){function i(t){return n?n(t,e):t.once?Di(t,e):Ii(t,e)}if(!t.length)return r||"_e()";var o=t.shift();return o.exp?"("+o.exp+")?"+i(o.block)+":"+Ri(t,e,n,r):""+i(o.block)}function Fi(t,e,n,r){var i=t.for,o=t.alias,a=t.iterator1?","+t.iterator1:"",s=t.iterator2?","+t.iterator2:"";return t.forProcessed=!0,(r||"_l")+"(("+i+"),function("+o+a+s+"){return "+(n||Ii)(t,e)+"})"}function Ui(t,e){var n="{",r=Bi(t,e);r&&(n+=r+","),t.key&&(n+="key:"+t.key+","),t.ref&&(n+="ref:"+t.ref+","),t.refInFor&&(n+="refInFor:true,"),t.pre&&(n+="pre:true,"),t.component&&(n+='tag:"'+t.tag+'",');for(var i=0;i<e.dataGenFns.length;i++)n+=e.dataGenFns[i](t);if(t.attrs&&(n+="attrs:{"+to(t.attrs)+"},"),t.props&&(n+="domProps:{"+to(t.props)+"},"),t.events&&(n+=Oi(t.events,!1,e.warn)+","),t.nativeEvents&&(n+=Oi(t.nativeEvents,!0,e.warn)+","),t.slotTarget&&!t.slotScope&&(n+="slot:"+t.slotTarget+","),t.scopedSlots&&(n+=Vi(t.scopedSlots,e)+","),t.model&&(n+="model:{value:"+t.model.value+",callback:"+t.model.callback+",expression:"+t.model.expression+"},"),t.inlineTemplate){var o=Hi(t,e);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",t.wrapData&&(n=t.wrapData(n)),t.wrapListeners&&(n=t.wrapListeners(n)),n}function Bi(t,e){var n=t.directives;if(n){var r,i,o,a,s="directives:[",c=!1;for(r=0,i=n.length;r<i;r++){o=n[r],a=!0;var u=e.directives[o.name];u&&(a=!!u(t,o,e.warn)),a&&(c=!0,s+='{name:"'+o.name+'",rawName:"'+o.rawName+'"'+(o.value?",value:("+o.value+"),expression:"+JSON.stringify(o.value):"")+(o.arg?',arg:"'+o.arg+'"':"")+(o.modifiers?",modifiers:"+JSON.stringify(o.modifiers):"")+"},")}return c?s.slice(0,-1)+"]":void 0}}function Hi(t,e){var n=t.children[0];if(1===n.type){var r=Ni(n,e.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(t){return"function(){"+t+"}"}).join(",")+"]}"}}function Vi(t,e){return"scopedSlots:_u(["+Object.keys(t).map(function(n){return zi(n,t[n],e)}).join(",")+"])"}function zi(t,e,n){return e.for&&!e.forProcessed?qi(t,e,n):"{key:"+t+",fn:function("+String(e.slotScope)+"){return "+("template"===e.tag?e.if?e.if+"?"+(Ji(e,n)||"undefined")+":undefined":Ji(e,n)||"undefined":Ii(e,n))+"}}"}function qi(t,e,n){var r=e.for,i=e.alias,o=e.iterator1?","+e.iterator1:"",a=e.iterator2?","+e.iterator2:"";return e.forProcessed=!0,"_l(("+r+"),function("+i+o+a+"){return "+zi(t,e,n)+"})"}function Ji(t,e,n,r,i){var o=t.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag)return(r||Ii)(a,e);var s=n?Ki(o,e.maybeComponent):0,c=i||Gi;return"["+o.map(function(t){return c(t,e)}).join(",")+"]"+(s?","+s:"")}}function Ki(t,e){for(var n=0,r=0;r<t.length;r++){var i=t[r];if(1===i.type){if(Wi(i)||i.ifConditions&&i.ifConditions.some(function(t){return Wi(t.block)})){n=2;break}(e(i)||i.ifConditions&&i.ifConditions.some(function(t){return e(t.block)}))&&(n=1)}}return n}function Wi(t){return void 0!==t.for||"template"===t.tag||"slot"===t.tag}function Gi(t,e){return 1===t.type?Ii(t,e):3===t.type&&t.isComment?Xi(t):Qi(t)}function Qi(t){return"_v("+(2===t.type?t.expression:eo(JSON.stringify(t.text)))+")"}function Xi(t){return"_e("+JSON.stringify(t.text)+")"}function Zi(t,e){var n=t.slotName||'"default"',r=Ji(t,e),i="_t("+n+(r?","+r:""),o=t.attrs&&"{"+t.attrs.map(function(t){return po(t.name)+":"+t.value}).join(",")+"}",a=t.attrsMap["v-bind"];return!o&&!a||r||(i+=",null"),o&&(i+=","+o),a&&(i+=(o?"":",null")+","+a),i+")"}function Yi(t,e,n){var r=e.inlineTemplate?null:Ji(e,n,!0);return"_c("+t+","+Ui(e,n)+(r?","+r:"")+")"}function to(t){for(var e="",n=0;n<t.length;n++){var r=t[n];e+='"'+r.name+'":'+eo(r.value)+","}return e.slice(0,-1)}function eo(t){return t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function no(t,e){try{return new Function(t)}catch(n){return e.push({err:n,code:t}),k}}function ro(t){var e=Object.create(null);return function(n,r,i){r=w({},r);r.warn;delete r.warn;var o=r.delimiters?String(r.delimiters)+n:n;if(e[o])return e[o];var a=t(n,r),s={},c=[];return s.render=no(a.render,c),s.staticRenderFns=a.staticRenderFns.map(function(t){return no(t,c)}),e[o]=s}}function io(t){return xc=xc||document.createElement("div"),xc.innerHTML=t?'<a href="\n"/>':'<div a="\n"/>',xc.innerHTML.indexOf("&#10;")>0}function oo(t){if(t.outerHTML)return t.outerHTML;var e=document.createElement("div");return e.appendChild(t.cloneNode(!0)),e.innerHTML}/*! * Vue.js v2.5.17 * (c) 2014-2018 Evan You * Released under the MIT License. */ var ao=Object.freeze({}),so=Object.prototype.toString,co=v("slot,component",!0),uo=v("key,ref,slot,slot-scope,is"),lo=Object.prototype.hasOwnProperty,fo=/-(\w)/g,po=y(function(t){return t.replace(fo,function(t,e){return e?e.toUpperCase():""})}),vo=y(function(t){return t.charAt(0).toUpperCase()+t.slice(1)}),ho=/\B([A-Z])/g,mo=y(function(t){return t.replace(ho,"-$1").toLowerCase()}),yo=Function.prototype.bind?b:g,go=function(t,e,n){return!1},bo=function(t){return t},_o="data-server-rendered",wo=["component","directive","filter"],xo=["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated","errorCaptured"],ko={optionMergeStrategies:Object.create(null),silent:!1,productionTip:!1,devtools:!1,performance:!1,errorHandler:null,warnHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:go,isReservedAttr:go,isUnknownElement:go,getTagNamespace:k,parsePlatformTagName:bo,mustUseProp:go,_lifecycleHooks:xo},$o=/[^\w.$]/,Co="__proto__"in{},Ao="undefined"!=typeof window,Oo="undefined"!=typeof WXEnvironment&&!!WXEnvironment.platform,To=Oo&&WXEnvironment.platform.toLowerCase(),jo=Ao&&window.navigator.userAgent.toLowerCase(),So=jo&&/msie|trident/.test(jo),Eo=jo&&jo.indexOf("msie 9.0")>0,Lo=jo&&jo.indexOf("edge/")>0,No=(jo&&jo.indexOf("android"),jo&&/iphone|ipad|ipod|ios/.test(jo)||"ios"===To),Io=(jo&&/chrome\/\d+/.test(jo),{}.watch),Po=!1;if(Ao)try{var Do={};Object.defineProperty(Do,"passive",{get:function(){Po=!0}}),window.addEventListener("test-passive",null,Do)}catch(t){}var Mo,Ro,Fo=function(){return void 0===Mo&&(Mo=!Ao&&!Oo&&void 0!==t&&"server"===t.process.env.VUE_ENV),Mo},Uo=Ao&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Bo="undefined"!=typeof Symbol&&S(Symbol)&&"undefined"!=typeof Reflect&&S(Reflect.ownKeys);Ro="undefined"!=typeof Set&&S(Set)?Set:function(){function t(){this.set=Object.create(null)}return t.prototype.has=function(t){return!0===this.set[t]},t.prototype.add=function(t){this.set[t]=!0},t.prototype.clear=function(){this.set=Object.create(null)},t}();var Ho=k,Vo=0,zo=function(){this.id=Vo++,this.subs=[]};zo.prototype.addSub=function(t){this.subs.push(t)},zo.prototype.removeSub=function(t){h(this.subs,t)},zo.prototype.depend=function(){zo.target&&zo.target.addDep(this)},zo.prototype.notify=function(){for(var t=this.subs.slice(),e=0,n=t.length;e<n;e++)t[e].update()},zo.target=null;var qo=[],Jo=function(t,e,n,r,i,o,a,s){this.tag=t,this.data=e,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.fnContext=void 0,this.fnOptions=void 0,this.fnScopeId=void 0,this.key=e&&e.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1,this.asyncFactory=s,this.asyncMeta=void 0,this.isAsyncPlaceholder=!1},Ko={child:{configurable:!0}};Ko.child.get=function(){return this.componentInstance},Object.defineProperties(Jo.prototype,Ko);var Wo=function(t){void 0===t&&(t="");var e=new Jo;return e.text=t,e.isComment=!0,e},Go=Array.prototype,Qo=Object.create(Go);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(t){var e=Go[t];T(Qo,t,function(){for(var n=[],r=arguments.length;r--;)n[r]=arguments[r];var i,o=e.apply(this,n),a=this.__ob__;switch(t){case"push":case"unshift":i=n;break;case"splice":i=n.slice(2)}return i&&a.observeArray(i),a.dep.notify(),o})});var Xo=Object.getOwnPropertyNames(Qo),Zo=!0,Yo=function(t){if(this.value=t,this.dep=new zo,this.vmCount=0,T(t,"__ob__",this),Array.isArray(t)){(Co?D:M)(t,Qo,Xo),this.observeArray(t)}else this.walk(t)};Yo.prototype.walk=function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)F(t,e[n])},Yo.prototype.observeArray=function(t){for(var e=0,n=t.length;e<n;e++)R(t[e])};var ta=ko.optionMergeStrategies;ta.data=function(t,e,n){return n?z(t,e,n):e&&"function"!=typeof e?t:z(t,e)},xo.forEach(function(t){ta[t]=q}),wo.forEach(function(t){ta[t+"s"]=J}),ta.watch=function(t,e,n,r){if(t===Io&&(t=void 0),e===Io&&(e=void 0),!e)return Object.create(t||null);if(!t)return e;var i={};w(i,t);for(var o in e){var a=i[o],s=e[o];a&&!Array.isArray(a)&&(a=[a]),i[o]=a?a.concat(s):Array.isArray(s)?s:[s]}return i},ta.props=ta.methods=ta.inject=ta.computed=function(t,e,n,r){if(!t)return e;var i=Object.create(null);return w(i,t),e&&w(i,e),i},ta.provide=z;var ea,na,ra=function(t,e){return void 0===e?t:e},ia=[],oa=!1,aa=!1;if(void 0!==n&&S(n))na=function(){n(at)};else if("undefined"==typeof MessageChannel||!S(MessageChannel)&&"[object MessageChannelConstructor]"!==MessageChannel.toString())na=function(){setTimeout(at,0)};else{var sa=new MessageChannel,ca=sa.port2;sa.port1.onmessage=at,na=function(){ca.postMessage(1)}}if("undefined"!=typeof Promise&&S(Promise)){var ua=Promise.resolve();ea=function(){ua.then(at),No&&setTimeout(k)}}else ea=na;var la,fa=new Ro,da=y(function(t){var e="&"===t.charAt(0);t=e?t.slice(1):t;var n="~"===t.charAt(0);t=n?t.slice(1):t;var r="!"===t.charAt(0);return t=r?t.slice(1):t,{name:t,once:n,capture:r,passive:e}}),pa=null,va=[],ha=[],ma={},ya=!1,ga=!1,ba=0,_a=0,wa=function(t,e,n,r,i){this.vm=t,i&&(t._watcher=this),t._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++_a,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new Ro,this.newDepIds=new Ro,this.expression="","function"==typeof e?this.getter=e:(this.getter=j(e),this.getter||(this.getter=function(){})),this.value=this.lazy?void 0:this.get()};wa.prototype.get=function(){E(this);var t,e=this.vm;try{t=this.getter.call(e,e)}catch(t){if(!this.user)throw t;rt(t,e,'getter for watcher "'+this.expression+'"')}finally{this.deep&&ut(t),L(),this.cleanupDeps()}return t},wa.prototype.addDep=function(t){var e=t.id;this.newDepIds.has(e)||(this.newDepIds.add(e),this.newDeps.push(t),this.depIds.has(e)||t.addSub(this))},wa.prototype.cleanupDeps=function(){for(var t=this,e=this.deps.length;e--;){var n=t.deps[e];t.newDepIds.has(n.id)||n.removeSub(t)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},wa.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():zt(this)},wa.prototype.run=function(){if(this.active){var t=this.get();if(t!==this.value||c(t)||this.deep){var e=this.value;if(this.value=t,this.user)try{this.cb.call(this.vm,t,e)}catch(t){rt(t,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,t,e)}}},wa.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},wa.prototype.depend=function(){for(var t=this,e=this.deps.length;e--;)t.deps[e].depend()},wa.prototype.teardown=function(){var t=this;if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)t.deps[e].removeSub(t);this.active=!1}};var xa={enumerable:!0,configurable:!0,get:k,set:k},ka={lazy:!0};me(ye.prototype);var $a={init:function(t,e,n,r){if(t.componentInstance&&!t.componentInstance._isDestroyed&&t.data.keepAlive){var i=t;$a.prepatch(i,i)}else{(t.componentInstance=xe(t,pa,n,r)).$mount(e?t.elm:void 0,e)}},prepatch:function(t,e){var n=e.componentOptions;It(e.componentInstance=t.componentInstance,n.propsData,n.listeners,e,n.children)},insert:function(t){var e=t.context,n=t.componentInstance;n._isMounted||(n._isMounted=!0,Rt(n,"mounted")),t.data.keepAlive&&(e._isMounted?Ht(n):Dt(n,!0))},destroy:function(t){var e=t.componentInstance;e._isDestroyed||(t.data.keepAlive?Mt(e,!0):e.$destroy())}},Ca=Object.keys($a),Aa=1,Oa=2,Ta=0;!function(t){t.prototype._init=function(t){var e=this;e._uid=Ta++,e._isVue=!0,t&&t._isComponent?Se(e,t):e.$options=Q(Ee(e.constructor),t||{},e),e._renderProxy=e,e._self=e,Lt(e),Ct(e),je(e),Rt(e,"beforeCreate"),re(e),Jt(e),ne(e),Rt(e,"created"),e.$options.el&&e.$mount(e.$options.el)}}(Ie),function(t){var e={};e.get=function(){return this._data};var n={};n.get=function(){return this._props},Object.defineProperty(t.prototype,"$data",e),Object.defineProperty(t.prototype,"$props",n),t.prototype.$set=U,t.prototype.$delete=B,t.prototype.$watch=function(t,e,n){var r=this;if(u(e))return ee(r,t,e,n);n=n||{},n.user=!0;var i=new wa(r,t,e,n);return n.immediate&&e.call(r,i.value),function(){i.teardown()}}}(Ie),function(t){var e=/^hook:/;t.prototype.$on=function(t,n){var r=this,i=this;if(Array.isArray(t))for(var o=0,a=t.length;o<a;o++)r.$on(t[o],n);else(i._events[t]||(i._events[t]=[])).push(n),e.test(t)&&(i._hasHookEvent=!0);return i},t.prototype.$once=function(t,e){function n(){r.$off(t,n),e.apply(r,arguments)}var r=this;return n.fn=e,r.$on(t,n),r},t.prototype.$off=function(t,e){var n=this,r=this;if(!arguments.length)return r._events=Object.create(null),r;if(Array.isArray(t)){for(var i=0,o=t.length;i<o;i++)n.$off(t[i],e);return r}var a=r._events[t];if(!a)return r;if(!e)return r._events[t]=null,r;if(e)for(var s,c=a.length;c--;)if((s=a[c])===e||s.fn===e){a.splice(c,1);break}return r},t.prototype.$emit=function(t){var e=this,n=e._events[t];if(n){n=n.length>1?_(n):n;for(var r=_(arguments,1),i=0,o=n.length;i<o;i++)try{n[i].apply(e,r)}catch(n){rt(n,e,'event handler for "'+t+'"')}}return e}}(Ie),function(t){t.prototype._update=function(t,e){var n=this;n._isMounted&&Rt(n,"beforeUpdate");var r=n.$el,i=n._vnode,o=pa;pa=n,n._vnode=t,i?n.$el=n.__patch__(i,t):(n.$el=n.__patch__(n.$el,t,e,!1,n.$options._parentElm,n.$options._refElm),n.$options._parentElm=n.$options._refElm=null),pa=o,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},t.prototype.$forceUpdate=function(){var t=this;t._watcher&&t._watcher.update()},t.prototype.$destroy=function(){var t=this;if(!t._isBeingDestroyed){Rt(t,"beforeDestroy"),t._isBeingDestroyed=!0;var e=t.$parent;!e||e._isBeingDestroyed||t.$options.abstract||h(e.$children,t),t._watcher&&t._watcher.teardown();for(var n=t._watchers.length;n--;)t._watchers[n].teardown();t._data.__ob__&&t._data.__ob__.vmCount--,t._isDestroyed=!0,t.__patch__(t._vnode,null),Rt(t,"destroyed"),t.$off(),t.$el&&(t.$el.__vue__=null),t.$vnode&&(t.$vnode.parent=null)}}}(Ie),function(t){me(t.prototype),t.prototype.$nextTick=function(t){return ct(t,this)},t.prototype._render=function(){var t=this,e=t.$options,n=e.render,r=e._parentVnode;r&&(t.$scopedSlots=r.data.scopedSlots||ao),t.$vnode=r;var i;try{i=n.call(t._renderProxy,t.$createElement)}catch(e){rt(e,t,"render"),i=t._vnode}return i instanceof Jo||(i=Wo()),i.parent=r,i}}(Ie);var ja=[String,RegExp,Array],Sa={name:"keep-alive",abstract:!0,props:{include:ja,exclude:ja,max:[String,Number]},created:function(){this.cache=Object.create(null),this.keys=[]},destroyed:function(){var t=this;for(var e in t.cache)ze(t.cache,e,t.keys)},mounted:function(){var t=this;this.$watch("include",function(e){Ve(t,function(t){return He(e,t)})}),this.$watch("exclude",function(e){Ve(t,function(t){return!He(e,t)})})},render:function(){var t=this.$slots.default,e=$t(t),n=e&&e.componentOptions;if(n){var r=Be(n),i=this,o=i.include,a=i.exclude;if(o&&(!r||!He(o,r))||a&&r&&He(a,r))return e;var s=this,c=s.cache,u=s.keys,l=null==e.key?n.Ctor.cid+(n.tag?"::"+n.tag:""):e.key;c[l]?(e.componentInstance=c[l].componentInstance,h(u,l),u.push(l)):(c[l]=e,u.push(l),this.max&&u.length>parseInt(this.max)&&ze(c,u[0],u,this._vnode)),e.data.keepAlive=!0}return e||t&&t[0]}},Ea={KeepAlive:Sa};!function(t){var e={};e.get=function(){return ko},Object.defineProperty(t,"config",e),t.util={warn:Ho,extend:w,mergeOptions:Q,defineReactive:F},t.set=U,t.delete=B,t.nextTick=ct,t.options=Object.create(null),wo.forEach(function(e){t.options[e+"s"]=Object.create(null)}),t.options._base=t,w(t.options.components,Ea),Pe(t),De(t),Me(t),Ue(t)}(Ie),Object.defineProperty(Ie.prototype,"$isServer",{get:Fo}),Object.defineProperty(Ie.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(Ie,"FunctionalRenderContext",{value:ye}),Ie.version="2.5.17";var La,Na,Ia,Pa,Da,Ma,Ra,Fa,Ua,Ba=v("style,class"),Ha=v("input,textarea,option,select,progress"),Va=function(t,e,n){return"value"===n&&Ha(t)&&"button"!==e||"selected"===n&&"option"===t||"checked"===n&&"input"===t||"muted"===n&&"video"===t},za=v("contenteditable,draggable,spellcheck"),qa=v("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),Ja="http://www.w3.org/1999/xlink",Ka=function(t){return":"===t.charAt(5)&&"xlink"===t.slice(0,5)},Wa=function(t){return Ka(t)?t.slice(6,t.length):""},Ga=function(t){return null==t||!1===t},Qa={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},Xa=v("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template,blockquote,iframe,tfoot"),Za=v("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,foreignObject,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),Ya=function(t){return"pre"===t},ts=function(t){return Xa(t)||Za(t)},es=Object.create(null),ns=v("text,number,password,search,email,tel,url"),rs=Object.freeze({createElement:en,createElementNS:nn,createTextNode:rn,createComment:on,insertBefore:an,removeChild:sn,appendChild:cn,parentNode:un,nextSibling:ln,tagName:fn,setTextContent:dn,setStyleScope:pn}),is={create:function(t,e){vn(e)},update:function(t,e){t.data.ref!==e.data.ref&&(vn(t,!0),vn(e))},destroy:function(t){vn(t,!0)}},os=new Jo("",{},[]),as=["create","activate","update","remove","destroy"],ss={create:gn,update:gn,destroy:function(t){gn(t,os)}},cs=Object.create(null),us=[is,ss],ls={create:kn,update:kn},fs={create:An,update:An},ds=/[\w).+\-_$\]]/,ps="__r",vs="__c",hs={create:er,update:er},ms={create:nr,update:nr},ys=y(function(t){var e={},n=/;(?![^(]*\))/g,r=/:(.+)/;return t.split(n).forEach(function(t){if(t){var n=t.split(r);n.length>1&&(e[n[0].trim()]=n[1].trim())}}),e}),gs=/^--/,bs=/\s*!important$/,_s=function(t,e,n){if(gs.test(e))t.style.setProperty(e,n);else if(bs.test(n))t.style.setProperty(e,n.replace(bs,""),"important");else{var r=xs(e);if(Array.isArray(n))for(var i=0,o=n.length;i<o;i++)t.style[r]=n[i];else t.style[r]=n}},ws=["Webkit","Moz","ms"],xs=y(function(t){if(Ua=Ua||document.createElement("div").style,"filter"!==(t=po(t))&&t in Ua)return t;for(var e=t.charAt(0).toUpperCase()+t.slice(1),n=0;n<ws.length;n++){var r=ws[n]+e;if(r in Ua)return r}}),ks={create:ur,update:ur},$s=y(function(t){return{enterClass:t+"-enter",enterToClass:t+"-enter-to",enterActiveClass:t+"-enter-active",leaveClass:t+"-leave",leaveToClass:t+"-leave-to",leaveActiveClass:t+"-leave-active"}}),Cs=Ao&&!Eo,As="transition",Os="animation",Ts="transition",js="transitionend",Ss="animation",Es="animationend";Cs&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(Ts="WebkitTransition",js="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Ss="WebkitAnimation",Es="webkitAnimationEnd"));var Ls=Ao?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(t){return t()},Ns=/\b(transform|all)(,|$)/,Is=Ao?{create:$r,activate:$r,remove:function(t,e){!0!==t.data.show?wr(t,e):e()}}:{},Ps=[ls,fs,hs,ms,ks,Is],Ds=Ps.concat(us),Ms=function(t){function e(t){return new Jo(E.tagName(t).toLowerCase(),{},[],void 0,t)}function n(t,e){function n(){0==--n.listeners&&a(t)}return n.listeners=e,n}function a(t){var e=E.parentNode(t);i(e)&&E.removeChild(e,t)}function c(t,e,n,r,a,s,c){if(i(t.elm)&&i(s)&&(t=s[c]=I(t)),t.isRootInsert=!a,!u(t,e,n,r)){var l=t.data,f=t.children,v=t.tag;i(v)?(t.elm=t.ns?E.createElementNS(t.ns,v):E.createElement(v,t),y(t),p(t,f,e),i(l)&&m(t,e),d(n,t.elm,r)):o(t.isComment)?(t.elm=E.createComment(t.text),d(n,t.elm,r)):(t.elm=E.createTextNode(t.text),d(n,t.elm,r))}}function u(t,e,n,r){var a=t.data;if(i(a)){var s=i(t.componentInstance)&&a.keepAlive;if(i(a=a.hook)&&i(a=a.init)&&a(t,!1,n,r),i(t.componentInstance))return l(t,e),o(s)&&f(t,e,n,r),!0}}function l(t,e){i(t.data.pendingInsert)&&(e.push.apply(e,t.data.pendingInsert),t.data.pendingInsert=null),t.elm=t.componentInstance.$el,h(t)?(m(t,e),y(t)):(vn(t),e.push(t))}function f(t,e,n,r){for(var o,a=t;a.componentInstance;)if(a=a.componentInstance._vnode,i(o=a.data)&&i(o=o.transition)){for(o=0;o<j.activate.length;++o)j.activate[o](os,a);e.push(a);break}d(n,t.elm,r)}function d(t,e,n){i(t)&&(i(n)?n.parentNode===t&&E.insertBefore(t,e,n):E.appendChild(t,e))}function p(t,e,n){if(Array.isArray(e))for(var r=0;r<e.length;++r)c(e[r],n,t.elm,null,!0,e,r);else s(t.text)&&E.appendChild(t.elm,E.createTextNode(String(t.text)))}function h(t){for(;t.componentInstance;)t=t.componentInstance._vnode;return i(t.tag)}function m(t,e){for(var n=0;n<j.create.length;++n)j.create[n](os,t);O=t.data.hook,i(O)&&(i(O.create)&&O.create(os,t),i(O.insert)&&e.push(t))}function y(t){var e;if(i(e=t.fnScopeId))E.setStyleScope(t.elm,e);else for(var n=t;n;)i(e=n.context)&&i(e=e.$options._scopeId)&&E.setStyleScope(t.elm,e),n=n.parent;i(e=pa)&&e!==t.context&&e!==t.fnContext&&i(e=e.$options._scopeId)&&E.setStyleScope(t.elm,e)}function g(t,e,n,r,i,o){for(;r<=i;++r)c(n[r],o,t,e,!1,n,r)}function b(t){var e,n,r=t.data;if(i(r))for(i(e=r.hook)&&i(e=e.destroy)&&e(t),e=0;e<j.destroy.length;++e)j.destroy[e](t);if(i(e=t.children))for(n=0;n<t.children.length;++n)b(t.children[n])}function _(t,e,n,r){for(;n<=r;++n){var o=e[n];i(o)&&(i(o.tag)?(w(o),b(o)):a(o.elm))}}function w(t,e){if(i(e)||i(t.data)){var r,o=j.remove.length+1;for(i(e)?e.listeners+=o:e=n(t.elm,o),i(r=t.componentInstance)&&i(r=r._vnode)&&i(r.data)&&w(r,e),r=0;r<j.remove.length;++r)j.remove[r](t,e);i(r=t.data.hook)&&i(r=r.remove)?r(t,e):e()}else a(t.elm)}function x(t,e,n,o,a){for(var s,u,l,f,d=0,p=0,v=e.length-1,h=e[0],m=e[v],y=n.length-1,b=n[0],w=n[y],x=!a;d<=v&&p<=y;)r(h)?h=e[++d]:r(m)?m=e[--v]:hn(h,b)?($(h,b,o),h=e[++d],b=n[++p]):hn(m,w)?($(m,w,o),m=e[--v],w=n[--y]):hn(h,w)?($(h,w,o),x&&E.insertBefore(t,h.elm,E.nextSibling(m.elm)),h=e[++d],w=n[--y]):hn(m,b)?($(m,b,o),x&&E.insertBefore(t,m.elm,h.elm),m=e[--v],b=n[++p]):(r(s)&&(s=yn(e,d,v)),u=i(b.key)?s[b.key]:k(b,e,d,v),r(u)?c(b,o,t,h.elm,!1,n,p):(l=e[u],hn(l,b)?($(l,b,o),e[u]=void 0,x&&E.insertBefore(t,l.elm,h.elm)):c(b,o,t,h.elm,!1,n,p)),b=n[++p]);d>v?(f=r(n[y+1])?null:n[y+1].elm,g(t,f,n,p,y,o)):p>y&&_(t,e,d,v)}function k(t,e,n,r){for(var o=n;o<r;o++){var a=e[o];if(i(a)&&hn(t,a))return o}}function $(t,e,n,a){if(t!==e){var s=e.elm=t.elm;if(o(t.isAsyncPlaceholder))return void(i(e.asyncFactory.resolved)?A(t.elm,e,n):e.isAsyncPlaceholder=!0);if(o(e.isStatic)&&o(t.isStatic)&&e.key===t.key&&(o(e.isCloned)||o(e.isOnce)))return void(e.componentInstance=t.componentInstance);var c,u=e.data;i(u)&&i(c=u.hook)&&i(c=c.prepatch)&&c(t,e);var l=t.children,f=e.children;if(i(u)&&h(e)){for(c=0;c<j.update.length;++c)j.update[c](t,e);i(c=u.hook)&&i(c=c.update)&&c(t,e)}r(e.text)?i(l)&&i(f)?l!==f&&x(s,l,f,n,a):i(f)?(i(t.text)&&E.setTextContent(s,""),g(s,null,f,0,f.length-1,n)):i(l)?_(s,l,0,l.length-1):i(t.text)&&E.setTextContent(s,""):t.text!==e.text&&E.setTextContent(s,e.text),i(u)&&i(c=u.hook)&&i(c=c.postpatch)&&c(t,e)}}function C(t,e,n){if(o(n)&&i(t.parent))t.parent.data.pendingInsert=e;else for(var r=0;r<e.length;++r)e[r].data.hook.insert(e[r])}function A(t,e,n,r){var a,s=e.tag,c=e.data,u=e.children;if(r=r||c&&c.pre,e.elm=t,o(e.isComment)&&i(e.asyncFactory))return e.isAsyncPlaceholder=!0,!0;if(i(c)&&(i(a=c.hook)&&i(a=a.init)&&a(e,!0),i(a=e.componentInstance)))return l(e,n),!0;if(i(s)){if(i(u))if(t.hasChildNodes())if(i(a=c)&&i(a=a.domProps)&&i(a=a.innerHTML)){if(a!==t.innerHTML)return!1}else{for(var f=!0,d=t.firstChild,v=0;v<u.length;v++){if(!d||!A(d,u[v],n,r)){f=!1;break}d=d.nextSibling}if(!f||d)return!1}else p(e,u,n);if(i(c)){var h=!1;for(var y in c)if(!L(y)){h=!0,m(e,n);break}!h&&c.class&&ut(c.class)}}else t.data!==e.text&&(t.data=e.text);return!0}var O,T,j={},S=t.modules,E=t.nodeOps;for(O=0;O<as.length;++O)for(j[as[O]]=[],T=0;T<S.length;++T)i(S[T][as[O]])&&j[as[O]].push(S[T][as[O]]);var L=v("attrs,class,staticClass,staticStyle,key");return function(t,n,a,s,u,l){if(r(n))return void(i(t)&&b(t));var f=!1,d=[];if(r(t))f=!0,c(n,d,u,l);else{var p=i(t.nodeType);if(!p&&hn(t,n))$(t,n,d,s);else{if(p){if(1===t.nodeType&&t.hasAttribute(_o)&&(t.removeAttribute(_o),a=!0),o(a)&&A(t,n,d))return C(n,d,!0),t;t=e(t)}var v=t.elm,m=E.parentNode(v);if(c(n,d,v._leaveCb?null:m,E.nextSibling(v)),i(n.parent))for(var y=n.parent,g=h(n);y;){for(var w=0;w<j.destroy.length;++w)j.destroy[w](y);if(y.elm=n.elm,g){for(var x=0;x<j.create.length;++x)j.create[x](os,y);var k=y.data.hook.insert;if(k.merged)for(var O=1;O<k.fns.length;O++)k.fns[O]()}else vn(y);y=y.parent}i(m)?_(m,[t],0,0):i(t.tag)&&b(t)}}return C(n,d,f),n.elm}}({nodeOps:rs,modules:Ds});Eo&&document.addEventListener("selectionchange",function(){var t=document.activeElement;t&&t.vmodel&&Er(t,"input")});var Rs={inserted:function(t,e,n,r){"select"===n.tag?(r.elm&&!r.elm._vOptions?pt(n,"postpatch",function(){Rs.componentUpdated(t,e,n)}):Cr(t,e,n.context),t._vOptions=[].map.call(t.options,Tr)):("textarea"===n.tag||ns(t.type))&&(t._vModifiers=e.modifiers,e.modifiers.lazy||(t.addEventListener("compositionstart",jr),t.addEventListener("compositionend",Sr),t.addEventListener("change",Sr),Eo&&(t.vmodel=!0)))},componentUpdated:function(t,e,n){if("select"===n.tag){Cr(t,e,n.context);var r=t._vOptions,i=t._vOptions=[].map.call(t.options,Tr);if(i.some(function(t,e){return!$(t,r[e])})){(t.multiple?e.value.some(function(t){return Or(t,i)}):e.value!==e.oldValue&&Or(e.value,i))&&Er(t,"change")}}}},Fs={bind:function(t,e,n){var r=e.value;n=Lr(n);var i=n.data&&n.data.transition,o=t.__vOriginalDisplay="none"===t.style.display?"":t.style.display;r&&i?(n.data.show=!0,_r(n,function(){t.style.display=o})):t.style.display=r?o:"none"},update:function(t,e,n){var r=e.value;!r!=!e.oldValue&&(n=Lr(n),n.data&&n.data.transition?(n.data.show=!0,r?_r(n,function(){t.style.display=t.__vOriginalDisplay}):wr(n,function(){t.style.display="none"})):t.style.display=r?t.__vOriginalDisplay:"none")},unbind:function(t,e,n,r,i){i||(t.style.display=t.__vOriginalDisplay)}},Us={model:Rs,show:Fs},Bs={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]},Hs={name:"transition",props:Bs,abstract:!0,render:function(t){var e=this,n=this.$slots.default;if(n&&(n=n.filter(function(t){return t.tag||kt(t)}),n.length)){var r=this.mode,i=n[0];if(Dr(this.$vnode))return i;var o=Nr(i);if(!o)return i;if(this._leaving)return Pr(t,i);var a="__transition-"+this._uid+"-";o.key=null==o.key?o.isComment?a+"comment":a+o.tag:s(o.key)?0===String(o.key).indexOf(a)?o.key:a+o.key:o.key;var c=(o.data||(o.data={})).transition=Ir(this),u=this._vnode,l=Nr(u);if(o.data.directives&&o.data.directives.some(function(t){return"show"===t.name})&&(o.data.show=!0),l&&l.data&&!Mr(o,l)&&!kt(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=w({},c);if("out-in"===r)return this._leaving=!0,pt(f,"afterLeave",function(){e._leaving=!1,e.$forceUpdate()}),Pr(t,i);if("in-out"===r){if(kt(o))return u;var d,p=function(){d()};pt(c,"afterEnter",p),pt(c,"enterCancelled",p),pt(f,"delayLeave",function(t){d=t})}}return i}}},Vs=w({tag:String,moveClass:String},Bs);delete Vs.mode;var zs={props:Vs,render:function(t){for(var e=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=Ir(this),s=0;s<i.length;s++){var c=i[s];if(c.tag)if(null!=c.key&&0!==String(c.key).indexOf("__vlist"))o.push(c),n[c.key]=c,(c.data||(c.data={})).transition=a;else;}if(r){for(var u=[],l=[],f=0;f<r.length;f++){var d=r[f];d.data.transition=a,d.data.pos=d.elm.getBoundingClientRect(),n[d.key]?u.push(d):l.push(d)}this.kept=t(e,null,u),this.removed=l}return t(e,null,o)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var t=this.prevChildren,e=this.moveClass||(this.name||"v")+"-move";t.length&&this.hasMove(t[0].elm,e)&&(t.forEach(Rr),t.forEach(Fr),t.forEach(Ur),this._reflow=document.body.offsetHeight,t.forEach(function(t){if(t.data.moved){var n=t.elm,r=n.style;vr(n,e),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(js,n._moveCb=function t(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(js,t),n._moveCb=null,hr(n,e))})}}))},methods:{hasMove:function(t,e){if(!Cs)return!1;if(this._hasMove)return this._hasMove;var n=t.cloneNode();t._transitionClasses&&t._transitionClasses.forEach(function(t){fr(n,t)}),lr(n,e),n.style.display="none",this.$el.appendChild(n);var r=yr(n);return this.$el.removeChild(n),this._hasMove=r.hasTransform}}},qs={Transition:Hs,TransitionGroup:zs};Ie.config.mustUseProp=Va,Ie.config.isReservedTag=ts,Ie.config.isReservedAttr=Ba,Ie.config.getTagNamespace=Ze,Ie.config.isUnknownElement=Ye,w(Ie.options.directives,Us),w(Ie.options.components,qs),Ie.prototype.__patch__=Ao?Ms:k,Ie.prototype.$mount=function(t,e){return t=t&&Ao?tn(t):void 0,Nt(this,t,e)},Ao&&setTimeout(function(){ko.devtools&&Uo&&Uo.emit("init",Ie)},0);var Js,Ks=/\{\{((?:.|\n)+?)\}\}/g,Ws=/[-.*+?^${}()|[\]\/\\]/g,Gs=y(function(t){var e=t[0].replace(Ws,"\\$&"),n=t[1].replace(Ws,"\\$&");return new RegExp(e+"((?:.|\\n)+?)"+n,"g")}),Qs={staticKeys:["staticClass"],transformNode:Hr,genData:Vr},Xs={staticKeys:["staticStyle"],transformNode:zr,genData:qr},Zs={decode:function(t){return Js=Js||document.createElement("div"),Js.innerHTML=t,Js.textContent}},Ys=v("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),tc=v("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),ec=v("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),nc=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,rc="[a-zA-Z_][\\w\\-\\.]*",ic="((?:"+rc+"\\:)?"+rc+")",oc=new RegExp("^<"+ic),ac=/^\s*(\/?)>/,sc=new RegExp("^<\\/"+ic+"[^>]*>"),cc=/^<!DOCTYPE [^>]+>/i,uc=/^<!\--/,lc=/^<!\[/,fc=!1;"x".replace(/x(.)?/g,function(t,e){fc=""===e});var dc,pc,vc,hc,mc,yc,gc,bc,_c,wc,xc,kc=v("script,style,textarea",!0),$c={},Cc={"&lt;":"<","&gt;":">","&quot;":'"',"&amp;":"&","&#10;":"\n","&#9;":"\t"},Ac=/&(?:lt|gt|quot|amp);/g,Oc=/&(?:lt|gt|quot|amp|#10|#9);/g,Tc=v("pre,textarea",!0),jc=function(t,e){return t&&Tc(t)&&"\n"===e[0]},Sc=/^@|^v-on:/,Ec=/^v-|^@|^:/,Lc=/([^]*?)\s+(?:in|of)\s+([^]*)/,Nc=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,Ic=/^\(|\)$/g,Pc=/:(.*)$/,Dc=/^:|^v-bind:/,Mc=/\.[^.]+/g,Rc=y(Zs.decode),Fc=/^xmlns:NS\d+/,Uc=/^NS\d+:/,Bc={preTransformNode:yi},Hc=[Qs,Xs,Bc],Vc={model:Jn,text:bi,html:_i},zc={expectHTML:!0,modules:Hc,directives:Vc,isPreTag:Ya,isUnaryTag:Ys,mustUseProp:Va,canBeLeftOpenTag:tc,isReservedTag:ts,getTagNamespace:Ze,staticKeys:function(t){return t.reduce(function(t,e){return t.concat(e.staticKeys||[])},[]).join(",")}(Hc)},qc=y(xi),Jc=/^([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/,Kc=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/,Wc={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Gc={esc:"Escape",tab:"Tab",enter:"Enter",space:" ",up:["Up","ArrowUp"],left:["Left","ArrowLeft"],right:["Right","ArrowRight"],down:["Down","ArrowDown"],delete:["Backspace","Delete"]},Qc=function(t){return"if("+t+")return null;"},Xc={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:Qc("$event.target !== $event.currentTarget"),ctrl:Qc("!$event.ctrlKey"),shift:Qc("!$event.shiftKey"),alt:Qc("!$event.altKey"),meta:Qc("!$event.metaKey"),left:Qc("'button' in $event && $event.button !== 0"),middle:Qc("'button' in $event && $event.button !== 1"),right:Qc("'button' in $event && $event.button !== 2")},Zc={on:Ei,bind:Li,cloak:k},Yc=function(t){this.options=t,this.warn=t.warn||jn,this.transforms=Sn(t.modules,"transformCode"),this.dataGenFns=Sn(t.modules,"genData"),this.directives=w(w({},Zc),t.directives);var e=t.isReservedTag||go;this.maybeComponent=function(t){return!e(t.tag)},this.onceId=0,this.staticRenderFns=[]},tu=(new RegExp("\\b"+"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments".split(",").join("\\b|\\b")+"\\b"),new RegExp("\\b"+"delete,typeof,void".split(",").join("\\s*\\([^\\)]*\\)|\\b")+"\\s*\\([^\\)]*\\)"),function(t){return function(e){function n(n,r){var i=Object.create(e),o=[],a=[];if(i.warn=function(t,e){(e?a:o).push(t)},r){r.modules&&(i.modules=(e.modules||[]).concat(r.modules)),r.directives&&(i.directives=w(Object.create(e.directives||null),r.directives));for(var s in r)"modules"!==s&&"directives"!==s&&(i[s]=r[s])}var c=t(n,i);return c.errors=o,c.tips=a,c}return{compile:n,compileToFunctions:ro(n)}}}(function(t,e){var n=Gr(t.trim(),e);!1!==e.optimize&&wi(n,e);var r=Ni(n,e);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}})),eu=tu(zc),nu=eu.compileToFunctions,ru=!!Ao&&io(!1),iu=!!Ao&&io(!0),ou=y(function(t){var e=tn(t);return e&&e.innerHTML}),au=Ie.prototype.$mount;Ie.prototype.$mount=function(t,e){if((t=t&&tn(t))===document.body||t===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=ou(r));else{if(!r.nodeType)return this;r=r.innerHTML}else t&&(r=oo(t));if(r){var i=nu(r,{shouldDecodeNewlines:ru,shouldDecodeNewlinesForHref:iu,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return au.call(this,t,e)},Ie.compile=nu,e.a=Ie}).call(e,n(3),n(14).setImmediate)},function(t,e,n){(function(t){function r(t,e){this._id=t,this._clearFn=e}var i=void 0!==t&&t||"undefined"!=typeof self&&self||window,o=Function.prototype.apply;e.setTimeout=function(){return new r(o.call(setTimeout,i,arguments),clearTimeout)},e.setInterval=function(){return new r(o.call(setInterval,i,arguments),clearInterval)},e.clearTimeout=e.clearInterval=function(t){t&&t.close()},r.prototype.unref=r.prototype.ref=function(){},r.prototype.close=function(){this._clearFn.call(i,this._id)},e.enroll=function(t,e){clearTimeout(t._idleTimeoutId),t._idleTimeout=e},e.unenroll=function(t){clearTimeout(t._idleTimeoutId),t._idleTimeout=-1},e._unrefActive=e.active=function(t){clearTimeout(t._idleTimeoutId);var e=t._idleTimeout;e>=0&&(t._idleTimeoutId=setTimeout(function(){t._onTimeout&&t._onTimeout()},e))},n(15),e.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==t&&t.setImmediate||this&&this.setImmediate,e.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==t&&t.clearImmediate||this&&this.clearImmediate}).call(e,n(3))},function(t,e,n){(function(t,e){!function(t,n){"use strict";function r(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var r={callback:t,args:e};return u[c]=r,s(c),c++}function i(t){delete u[t]}function o(t){var e=t.callback,r=t.args;switch(r.length){case 0:e();break;case 1:e(r[0]);break;case 2:e(r[0],r[1]);break;case 3:e(r[0],r[1],r[2]);break;default:e.apply(n,r)}}function a(t){if(l)setTimeout(a,0,t);else{var e=u[t];if(e){l=!0;try{o(e)}finally{i(t),l=!1}}}}if(!t.setImmediate){var s,c=1,u={},l=!1,f=t.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(t);d=d&&d.setTimeout?d:t,"[object process]"==={}.toString.call(t.process)?function(){s=function(t){e.nextTick(function(){a(t)})}}():function(){if(t.postMessage&&!t.importScripts){var e=!0,n=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=n,e}}()?function(){var e="setImmediate$"+Math.random()+"$",n=function(n){n.source===t&&"string"==typeof n.data&&0===n.data.indexOf(e)&&a(+n.data.slice(e.length))};t.addEventListener?t.addEventListener("message",n,!1):t.attachEvent("onmessage",n),s=function(n){t.postMessage(e+n,"*")}}():t.MessageChannel?function(){var t=new MessageChannel;t.port1.onmessage=function(t){a(t.data)},s=function(e){t.port2.postMessage(e)}}():f&&"onreadystatechange"in f.createElement("script")?function(){var t=f.documentElement;s=function(e){var n=f.createElement("script");n.onreadystatechange=function(){a(e),n.onreadystatechange=null,t.removeChild(n),n=null},t.appendChild(n)}}():function(){s=function(t){setTimeout(a,0,t)}}(),d.setImmediate=r,d.clearImmediate=i}}("undefined"==typeof self?void 0===t?this:t:self)}).call(e,n(3),n(16))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(t){if(l===setTimeout)return setTimeout(t,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function o(t){if(f===clearTimeout)return clearTimeout(t);if((f===r||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(t);try{return f(t)}catch(e){try{return f.call(null,t)}catch(e){return f.call(this,t)}}}function a(){h&&p&&(h=!1,p.length?v=p.concat(v):m=-1,v.length&&s())}function s(){if(!h){var t=i(a);h=!0;for(var e=v.length;e;){for(p=v,v=[];++m<e;)p&&p[m].run();m=-1,e=v.length}p=null,h=!1,o(t)}}function c(t,e){this.fun=t,this.array=e}function u(){}var l,f,d=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{f="function"==typeof clearTimeout?clearTimeout:r}catch(t){f=r}}();var p,v=[],h=!1,m=-1;d.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];v.push(new c(t,e)),1!==v.length||h||i(s)},c.prototype.run=function(){this.fun.apply(null,this.array)},d.title="browser",d.browser=!0,d.env={},d.argv=[],d.version="",d.versions={},d.on=u,d.addListener=u,d.once=u,d.off=u,d.removeListener=u,d.removeAllListeners=u,d.emit=u,d.prependListener=u,d.prependOnceListener=u,d.listeners=function(t){return[]},d.binding=function(t){throw new Error("process.binding is not supported")},d.cwd=function(){return"/"},d.chdir=function(t){throw new Error("process.chdir is not supported")},d.umask=function(){return 0}},function(t,e,n){"use strict";function r(t){n(18)}var i=n(4),o=n(49),a=n(2),s=r,c=a(i.a,o.a,!1,s,null,null);e.a=c.exports},function(t,e,n){var r=n(19);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("9151d162",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.i(n(20),""),e.push([t.i,"#app{display:flex;flex-direction:column;min-height:100vh}",""])},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,"@import url(https://fonts.googleapis.com/css?family=Roboto);",""]),e.push([t.i,":root{--v-green:#41b883;--v-blue:#35495e}*{margin:0}body{min-height:100vh;display:flex;flex-direction:column;font-family:Roboto,sans-serif}img{vertical-align:bottom}",""])},function(t,e){t.exports=function(t,e){for(var n=[],r={},i=0;i<e.length;i++){var o=e[i],a=o[0],s=o[1],c=o[2],u=o[3],l={id:t+":"+i,css:s,media:c,sourceMap:u};r[a]?r[a].parts.push(l):n.push(r[a]={id:a,parts:[l]})}return n}},function(t,e,n){"use strict";function r(t){n(23)}var i=n(5),o=n(25),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-3bd4b924",null);e.a=c.exports},function(t,e,n){var r=n(24);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("742f2cba",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,".header[data-v-3bd4b924]{background:#191919;color:#fff;padding:3vh 0;display:flex;justify-content:space-around}.logo[data-v-3bd4b924]{display:flex}.logo h1[data-v-3bd4b924],h2[data-v-3bd4b924]{display:flex;flex-direction:column;justify-content:flex-end}.figure[data-v-3bd4b924]{width:50px}.img[data-v-3bd4b924]{max-width:100%}",""])},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},i=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("header",{staticClass:"header"},[n("div",{staticClass:"logo"},[n("figure",{staticClass:"figure"},[n("img",{staticClass:"img",attrs:{src:"https://vuejs.org/images/logo.png"}})]),n("h1",[t._v("Vue Music")])]),n("h2",[t._v("Tus mejores canciones")])])}],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";function r(t){n(27)}var i=n(6),o=n(44),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-3fa12b14",null);e.a=c.exports},function(t,e,n){var r=n(28);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("6efd4949",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,"div[data-v-3fa12b14]{display:flex;justify-content:center;flex-direction:row;flex:1}",""])},function(t,e,n){"use strict";function r(t){n(30)}var i=n(7),o=n(35),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-c534fd1a",null);e.a=c.exports},function(t,e,n){var r=n(31);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("01385c5c",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,".more-tracks[data-v-c534fd1a]{display:flex;justify-content:center;color:#fff;background:#000;border-radius:0 0 20px 20px}.search[data-v-c534fd1a]{margin:15px 0}.tracks-list[data-v-c534fd1a]{border:1px solid rgba(0,0,0,.1);height:65vh;overflow:auto}.tracks-list[data-v-c534fd1a]::-webkit-scrollbar{width:7px;background:rgba(0,0,0,.1)}.tracks-list[data-v-c534fd1a]::-webkit-scrollbar-thumb{width:8px;background:rgba(0,0,0,.5)}input[data-v-c534fd1a]{font-size:1.8rem;padding:0 10px;border-radius:30px 0 0 30px;border:1px solid;border-right:none;outline:none;box-shadow:6px 4px 8px 0 #000}button[data-v-c534fd1a]{font-size:1.8rem;border-radius:0 30px 30px 0;padding:0 10px;border:1px solid;background-color:#fff;border-left:none;box-shadow:5px 4px 8px 0 #000;outline:none}.main[data-v-c534fd1a]{display:inline-block;padding:0 10px}figure[data-v-c534fd1a]{width:50px;height:50px;padding:0 10px}.track[data-v-c534fd1a]{cursor:pointer;display:flex;justify-content:flex-start;border:1px solid #000;border-radius:30px;padding:5px 0;margin:5px 0}img[data-v-c534fd1a]{width:100%;border-radius:50%;object-fit:cover}",""])},function(t,e,n){"use strict";var r=n(33),i=n.n(r),o=n(34),a=i.a.create({baseUrl:o.a.apiUrl});e.a=a},function(t,e,n){(function(e){!function(e,n){t.exports=n()}(0,function(){"use strict";function t(t,e){return e={exports:{}},t(e,e.exports),e.exports}function n(t,e){return e?(t+"?"+N(e)).replace(/\?$/,""):t}function r(t,e){return t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,"")}function i(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}function o(t,e,o){return!t||i(e)?n(e,o):n(r(t,e),o)}function a(){for(var t=arguments.length,e=Array(t),n=0;n<t;n++)e[n]=arguments[n];return I.recursive.apply(I,[!0].concat(e))}function s(t,e){var n={};return Object.keys(t).filter(function(t){return!e.includes(t)}).forEach(function(e){n[e]=t[e]}),n}function c(t,e,n){return t&&z(n)?n:(e.get("Content-Type")||"").includes("application/json")?"json":"text"}function u(t,e){var n=t.ok,r=t.headers,i=t.status,o=t.statusText,a=e.config.bodyType;e.headers=r,e.status=i,e.statusText=o;var s=c(n,r,a);return"raw"===s?(e.data=t.body,Promise.resolve(e)):t[s]().then(function(t){return e.data=t,e})}function l(t,e){if(!t.ok){var n=new Error(t.statusText);return n.config=e,u(t,n).then(function(t){throw t})}return u(t,{config:e})}!function(t){function e(t){if("string"!=typeof t&&(t=String(t)),/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(t))throw new TypeError("Invalid character in header field name");return t.toLowerCase()}function n(t){return"string"!=typeof t&&(t=String(t)),t}function r(t){var e={next:function(){var e=t.shift();return{done:void 0===e,value:e}}};return y.iterable&&(e[Symbol.iterator]=function(){return e}),e}function i(t){this.map={},t instanceof i?t.forEach(function(t,e){this.append(e,t)},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}function o(t){return t.bodyUsed?Promise.reject(new TypeError("Already read")):void(t.bodyUsed=!0)}function a(t){return new Promise(function(e,n){t.onload=function(){e(t.result)},t.onerror=function(){n(t.error)}})}function s(t){var e=new FileReader,n=a(e);return e.readAsArrayBuffer(t),n}function c(t){var e=new FileReader,n=a(e);return e.readAsText(t),n}function u(t){for(var e=new Uint8Array(t),n=new Array(e.length),r=0;r<e.length;r++)n[r]=String.fromCharCode(e[r]);return n.join("")}function l(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function f(){return this.bodyUsed=!1,this._initBody=function(t){if(this._bodyInit=t,t)if("string"==typeof t)this._bodyText=t;else if(y.blob&&Blob.prototype.isPrototypeOf(t))this._bodyBlob=t;else if(y.formData&&FormData.prototype.isPrototypeOf(t))this._bodyFormData=t;else if(y.searchParams&&URLSearchParams.prototype.isPrototypeOf(t))this._bodyText=t.toString();else if(y.arrayBuffer&&y.blob&&b(t))this._bodyArrayBuffer=l(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer]);else{if(!y.arrayBuffer||!ArrayBuffer.prototype.isPrototypeOf(t)&&!_(t))throw new Error("unsupported BodyInit type");this._bodyArrayBuffer=l(t)}else this._bodyText="";this.headers.get("content-type")||("string"==typeof t?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):y.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},y.blob&&(this.blob=function(){var t=o(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))},this.arrayBuffer=function(){return this._bodyArrayBuffer?o(this)||Promise.resolve(this._bodyArrayBuffer):this.blob().then(s)}),this.text=function(){var t=o(this);if(t)return t;if(this._bodyBlob)return c(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(u(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},y.formData&&(this.formData=function(){return this.text().then(v)}),this.json=function(){return this.text().then(JSON.parse)},this}function d(t){var e=t.toUpperCase();return w.indexOf(e)>-1?e:t}function p(t,e){e=e||{};var n=e.body;if("string"==typeof t)this.url=t;else{if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new i(t.headers)),this.method=t.method,this.mode=t.mode,n||null==t._bodyInit||(n=t._bodyInit,t.bodyUsed=!0)}if(this.credentials=e.credentials||this.credentials||"omit",!e.headers&&this.headers||(this.headers=new i(e.headers)),this.method=d(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.referrer=null,("GET"===this.method||"HEAD"===this.method)&&n)throw new TypeError("Body not allowed for GET or HEAD requests");this._initBody(n)}function v(t){var e=new FormData;return t.trim().split("&").forEach(function(t){if(t){var n=t.split("="),r=n.shift().replace(/\+/g," "),i=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(r),decodeURIComponent(i))}}),e}function h(t){var e=new i;return t.split("\r\n").forEach(function(t){var n=t.split(":"),r=n.shift().trim();if(r){var i=n.join(":").trim();e.append(r,i)}}),e}function m(t,e){e||(e={}),this.type="default",this.status="status"in e?e.status:200,this.ok=this.status>=200&&this.status<300,this.statusText="statusText"in e?e.statusText:"OK",this.headers=new i(e.headers),this.url=e.url||"",this._initBody(t)}if(!t.fetch){var y={searchParams:"URLSearchParams"in t,iterable:"Symbol"in t&&"iterator"in Symbol,blob:"FileReader"in t&&"Blob"in t&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in t,arrayBuffer:"ArrayBuffer"in t};if(y.arrayBuffer)var g=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],b=function(t){return t&&DataView.prototype.isPrototypeOf(t)},_=ArrayBuffer.isView||function(t){return t&&g.indexOf(Object.prototype.toString.call(t))>-1};i.prototype.append=function(t,r){t=e(t),r=n(r);var i=this.map[t];this.map[t]=i?i+","+r:r},i.prototype.delete=function(t){delete this.map[e(t)]},i.prototype.get=function(t){return t=e(t),this.has(t)?this.map[t]:null},i.prototype.has=function(t){return this.map.hasOwnProperty(e(t))},i.prototype.set=function(t,r){this.map[e(t)]=n(r)},i.prototype.forEach=function(t,e){for(var n in this.map)this.map.hasOwnProperty(n)&&t.call(e,this.map[n],n,this)},i.prototype.keys=function(){var t=[];return this.forEach(function(e,n){t.push(n)}),r(t)},i.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),r(t)},i.prototype.entries=function(){var t=[];return this.forEach(function(e,n){t.push([n,e])}),r(t)},y.iterable&&(i.prototype[Symbol.iterator]=i.prototype.entries);var w=["DELETE","GET","HEAD","OPTIONS","POST","PUT"];p.prototype.clone=function(){return new p(this,{body:this._bodyInit})},f.call(p.prototype),f.call(m.prototype),m.prototype.clone=function(){return new m(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new i(this.headers),url:this.url})},m.error=function(){var t=new m(null,{status:0,statusText:""});return t.type="error",t};var x=[301,302,303,307,308];m.redirect=function(t,e){if(-1===x.indexOf(e))throw new RangeError("Invalid status code");return new m(null,{status:e,headers:{location:t}})},t.Headers=i,t.Request=p,t.Response=m,t.fetch=function(t,e){return new Promise(function(n,r){var i=new p(t,e),o=new XMLHttpRequest;o.onload=function(){var t={status:o.status,statusText:o.statusText,headers:h(o.getAllResponseHeaders()||"")};t.url="responseURL"in o?o.responseURL:t.headers.get("X-Request-URL");var e="response"in o?o.response:o.responseText;n(new m(e,t))},o.onerror=function(){r(new TypeError("Network request failed"))},o.ontimeout=function(){r(new TypeError("Network request failed"))},o.open(i.method,i.url,!0),"include"===i.credentials&&(o.withCredentials=!0),"responseType"in o&&y.blob&&(o.responseType="blob"),i.headers.forEach(function(t,e){o.setRequestHeader(e,t)}),o.send(void 0===i._bodyInit?null:i._bodyInit)})},t.fetch.polyfill=!0}}("undefined"!=typeof self?self:e);var f=(self.fetch.bind(self),t(function(t,e){var n=Object.prototype.hasOwnProperty,r=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}();e.arrayToObject=function(t,e){for(var n=e&&e.plainObjects?Object.create(null):{},r=0;r<t.length;++r)void 0!==t[r]&&(n[r]=t[r]);return n},e.merge=function(t,r,i){if(!r)return t;if("object"!=typeof r){if(Array.isArray(t))t.push(r);else{if("object"!=typeof t)return[t,r];t[r]=!0}return t}if("object"!=typeof t)return[t].concat(r);var o=t;return Array.isArray(t)&&!Array.isArray(r)&&(o=e.arrayToObject(t,i)),Array.isArray(t)&&Array.isArray(r)?(r.forEach(function(r,o){n.call(t,o)?t[o]&&"object"==typeof t[o]?t[o]=e.merge(t[o],r,i):t.push(r):t[o]=r}),t):Object.keys(r).reduce(function(t,n){var o=r[n];return Object.prototype.hasOwnProperty.call(t,n)?t[n]=e.merge(t[n],o,i):t[n]=o,t},o)},e.decode=function(t){try{return decodeURIComponent(t.replace(/\+/g," "))}catch(e){return t}},e.encode=function(t){if(0===t.length)return t;for(var e="string"==typeof t?t:String(t),n="",i=0;i<e.length;++i){var o=e.charCodeAt(i);45===o||46===o||95===o||126===o||o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?n+=e.charAt(i):o<128?n+=r[o]:o<2048?n+=r[192|o>>6]+r[128|63&o]:o<55296||o>=57344?n+=r[224|o>>12]+r[128|o>>6&63]+r[128|63&o]:(i+=1,o=65536+((1023&o)<<10|1023&e.charCodeAt(i)),n+=r[240|o>>18]+r[128|o>>12&63]+r[128|o>>6&63]+r[128|63&o])}return n},e.compact=function(t,n){if("object"!=typeof t||null===t)return t;var r=n||[],i=r.indexOf(t);if(-1!==i)return r[i];if(r.push(t),Array.isArray(t)){for(var o=[],a=0;a<t.length;++a)t[a]&&"object"==typeof t[a]?o.push(e.compact(t[a],r)):void 0!==t[a]&&o.push(t[a]);return o}return Object.keys(t).forEach(function(n){t[n]=e.compact(t[n],r)}),t},e.isRegExp=function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},e.isBuffer=function(t){return null!==t&&void 0!==t&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}})),d=String.prototype.replace,p=/%20/g,v={default:"RFC3986",formatters:{RFC1738:function(t){return d.call(t,p,"+")},RFC3986:function(t){return t}},RFC1738:"RFC1738",RFC3986:"RFC3986"},h=f,m=v,y={brackets:function(t){return t+"[]"},indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},g=Date.prototype.toISOString,b={delimiter:"&",encode:!0,encoder:h.encode,serializeDate:function(t){return g.call(t)},skipNulls:!1,strictNullHandling:!1},_=function t(e,n,r,i,o,a,s,c,u,l,f){var d=e;if("function"==typeof s)d=s(n,d);else if(d instanceof Date)d=l(d);else if(null===d){if(i)return a?a(n):n;d=""}if("string"==typeof d||"number"==typeof d||"boolean"==typeof d||h.isBuffer(d))return a?[f(a(n))+"="+f(a(d))]:[f(n)+"="+f(String(d))];var p=[];if(void 0===d)return p;var v;if(Array.isArray(s))v=s;else{var m=Object.keys(d);v=c?m.sort(c):m}for(var y=0;y<v.length;++y){var g=v[y];o&&null===d[g]||(p=Array.isArray(d)?p.concat(t(d[g],r(n,g),r,i,o,a,s,c,u,l,f)):p.concat(t(d[g],n+(u?"."+g:"["+g+"]"),r,i,o,a,s,c,u,l,f)))}return p},w=function(t,e){var n=t,r=e||{};if(null!==r.encoder&&void 0!==r.encoder&&"function"!=typeof r.encoder)throw new TypeError("Encoder has to be a function.");var i=void 0===r.delimiter?b.delimiter:r.delimiter,o="boolean"==typeof r.strictNullHandling?r.strictNullHandling:b.strictNullHandling,a="boolean"==typeof r.skipNulls?r.skipNulls:b.skipNulls,s="boolean"==typeof r.encode?r.encode:b.encode,c=s?"function"==typeof r.encoder?r.encoder:b.encoder:null,u="function"==typeof r.sort?r.sort:null,l=void 0!==r.allowDots&&r.allowDots,f="function"==typeof r.serializeDate?r.serializeDate:b.serializeDate;if(void 0===r.format)r.format=m.default;else if(!Object.prototype.hasOwnProperty.call(m.formatters,r.format))throw new TypeError("Unknown format option provided.");var d,p,v=m.formatters[r.format];"function"==typeof r.filter?(p=r.filter,n=p("",n)):Array.isArray(r.filter)&&(p=r.filter,d=p);var h=[];if("object"!=typeof n||null===n)return"";var g;g=r.arrayFormat in y?r.arrayFormat:"indices"in r?r.indices?"indices":"repeat":"indices";var w=y[g];d||(d=Object.keys(n)),u&&d.sort(u);for(var x=0;x<d.length;++x){var k=d[x];a&&null===n[k]||(h=h.concat(_(n[k],k,w,o,a,c,p,u,l,f,v)))}return h.join(i)},x=f,k=Object.prototype.hasOwnProperty,$={allowDots:!1,allowPrototypes:!1,arrayLimit:20,decoder:x.decode,delimiter:"&",depth:5,parameterLimit:1e3,plainObjects:!1,strictNullHandling:!1},C=function(t,e){for(var n={},r=t.split(e.delimiter,e.parameterLimit===1/0?void 0:e.parameterLimit),i=0;i<r.length;++i){var o,a,s=r[i],c=-1===s.indexOf("]=")?s.indexOf("="):s.indexOf("]=")+1;-1===c?(o=e.decoder(s),a=e.strictNullHandling?null:""):(o=e.decoder(s.slice(0,c)),a=e.decoder(s.slice(c+1))),k.call(n,o)?n[o]=[].concat(n[o]).concat(a):n[o]=a}return n},A=function(t,e,n){if(!t.length)return e;var r,i=t.shift();if("[]"===i)r=[],r=r.concat(A(t,e,n));else{r=n.plainObjects?Object.create(null):{};var o="["===i.charAt(0)&&"]"===i.charAt(i.length-1)?i.slice(1,-1):i,a=parseInt(o,10);!isNaN(a)&&i!==o&&String(a)===o&&a>=0&&n.parseArrays&&a<=n.arrayLimit?(r=[],r[a]=A(t,e,n)):r[o]=A(t,e,n)}return r},O=function(t,e,n){if(t){var r=n.allowDots?t.replace(/\.([^.[]+)/g,"[$1]"):t,i=/^([^[]*)/,o=/(\[[^[\]]*])/g,a=i.exec(r),s=[];if(a[1]){if(!n.plainObjects&&k.call(Object.prototype,a[1])&&!n.allowPrototypes)return;s.push(a[1])}for(var c=0;null!==(a=o.exec(r))&&c<n.depth;){if(c+=1,!n.plainObjects&&k.call(Object.prototype,a[1].slice(1,-1))&&!n.allowPrototypes)return;s.push(a[1])}return a&&s.push("["+r.slice(a.index)+"]"),A(s,e,n)}},T=function(t,e){var n=e||{};if(null!==n.decoder&&void 0!==n.decoder&&"function"!=typeof n.decoder)throw new TypeError("Decoder has to be a function.");if(n.delimiter="string"==typeof n.delimiter||x.isRegExp(n.delimiter)?n.delimiter:$.delimiter,n.depth="number"==typeof n.depth?n.depth:$.depth,n.arrayLimit="number"==typeof n.arrayLimit?n.arrayLimit:$.arrayLimit,n.parseArrays=!1!==n.parseArrays,n.decoder="function"==typeof n.decoder?n.decoder:$.decoder,n.allowDots="boolean"==typeof n.allowDots?n.allowDots:$.allowDots,n.plainObjects="boolean"==typeof n.plainObjects?n.plainObjects:$.plainObjects,n.allowPrototypes="boolean"==typeof n.allowPrototypes?n.allowPrototypes:$.allowPrototypes,n.parameterLimit="number"==typeof n.parameterLimit?n.parameterLimit:$.parameterLimit,n.strictNullHandling="boolean"==typeof n.strictNullHandling?n.strictNullHandling:$.strictNullHandling,""===t||null===t||void 0===t)return n.plainObjects?Object.create(null):{};for(var r="string"==typeof t?C(t,n):t,i=n.plainObjects?Object.create(null):{},o=Object.keys(r),a=0;a<o.length;++a){var s=o[a],c=O(s,r[s],n);i=x.merge(i,c,n)}return x.compact(i)},j=w,S=T,E=v,L={formats:E,parse:S,stringify:j},N=L.stringify,I=t(function(t){!function(e){function n(t,e){if("object"!==i(t))return e;for(var r in e)"object"===i(t[r])&&"object"===i(e[r])?t[r]=n(t[r],e[r]):t[r]=e[r];return t}function r(t,e,r){var a=r[0],s=r.length;(t||"object"!==i(a))&&(a={});for(var c=0;c<s;++c){var u=r[c];if("object"===i(u))for(var l in u){var f=t?o.clone(u[l]):u[l];a[l]=e?n(a[l],f):f}}return a}function i(t){return{}.toString.call(t).slice(8,-1).toLowerCase()}var o=function(t){return r(!0===t,!1,arguments)};o.recursive=function(t){return r(!0===t,!0,arguments)},o.clone=function(t){var e,n,r=t,a=i(t);if("array"===a)for(r=[],n=t.length,e=0;e<n;++e)r[e]=o.clone(t[e]);else if("object"===a){r={};for(e in t)r[e]=o.clone(t[e])}return r},e?t.exports=o:window.merge=o}(t&&!0&&t.exports)}),P="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},D=function(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")},M=function(){function t(t,e){for(var n=0;n<e.length;n++){var r=e[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(t,r.key,r)}}return function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),e}}(),R=function(t,e,n){return e in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t},F=function(t){return t},U=function(t){return Promise.reject(t)},B=function(){function t(){D(this,t),this._before=[],this._after=[],this._finally=[]}return M(t,[{key:"before",value:function(t){return this._before.push(t),this._before.length-1}},{key:"after",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:F,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:U;return this._after.push({fulfill:t,reject:e}),this._after.length-1}},{key:"finally",value:function(t){return this._finally.push(t),this._finally.length-1}},{key:"resolveBefore",value:function(t){var e=function(t,e){return t.then(e)};return this._before.reduce(e,Promise.resolve(t))}},{key:"resolveAfter",value:function(t,e){var n=function(t,e){return t.then(e.fulfill,e.reject)},r=t?Promise.reject(t):Promise.resolve(e);return this._after.reduce(n,r)}},{key:"resolveFinally",value:function(t,e){this._finally.forEach(function(n){return n(t,e)})}}]),t}(),H=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};D(this,t),this._config={headers:{}},this.set(e)}return M(t,[{key:"merge",value:function(){var t=a.apply(void 0,arguments),e=a(this.skipNotUsedMethods(t.method),this._config[t.method],t);return"object"===P(e.body)&&e.headers&&"application/json"===e.headers["Content-Type"]&&(e.body=JSON.stringify(e.body)),e}},{key:"skipNotUsedMethods",value:function(t){var e=["delete","get","head","patch","post","put"].filter(function(e){return t!==e.toLowerCase()});return s(this._config,e)}},{key:"set",value:function(t){this._config=a(this._config,t)}},{key:"get",value:function(){return a(this._config)}}]),t}(),V=["arrayBuffer","blob","formData","json","text","raw"],z=function(t){return V.includes(t)};return new(function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};D(this,t),this._middleware=new B,this._config=new H(s(e,["baseUrl"])),this.baseUrl(e.baseUrl||""),this._initMethodsWithBody(),this._initMethodsWithNoBody(),this._initMiddlewareMethods(),this.version="1.4.2"}return M(t,[{key:"create",value:function(t){var e=new this.constructor(a(this.defaults(),t)),n=function(t){var n=t.fulfill,r=t.reject;return e.after(n,r)};return this._middleware._before.forEach(e.before),this._middleware._after.forEach(n),this._middleware._finally.forEach(e.finally),e}},{key:"defaults",value:function(t){if(void 0===t){var e=this._config.get();return this.baseUrl()&&(e.baseUrl=this.baseUrl()),e}return this._config.set(s(t,["baseUrl"])),t.baseUrl&&this.baseUrl(t.baseUrl),this._config.get()}},{key:"baseUrl",value:function(t){return void 0===t?this._baseUrl:(this._baseUrl=t,this._baseUrl)}},{key:"request",value:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t.method||(t.method="get");var e=this._config.merge(t),n=o(this._baseUrl,t.url,t.params);return this._fetch(n,e)}},{key:"_fetch",value:function(t,e){var n=this,r=a(e,{method:e.method.toUpperCase()}),i=function(){var t;return(t=n._middleware).resolveFinally.apply(t,arguments)};return this._middleware.resolveBefore(r).then(function(e){return fetch(t,e)}).then(function(t){return l(t,r)}).then(function(t){return n._middleware.resolveAfter(void 0,t)},function(t){return n._middleware.resolveAfter(t)}).then(function(e){return Promise.resolve(i(r,t)).then(function(){return e})},function(e){return Promise.resolve(i(r,t)).then(function(){throw e})})}},{key:"_initMethodsWithNoBody",value:function(){var t=this;["get","delete","head"].forEach(function(e){t[e]=function(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=o(t._baseUrl,n,r.params),a=t._config.merge(r,{method:e,url:i});return t._fetch(i,a)}})}},{key:"_initMethodsWithBody",value:function(){var t=this,e={headers:{"Content-Type":"application/json"}};["post","put","patch"].forEach(function(n){t._config.set(R({},n,e)),t[n]=function(e){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},a=o(t._baseUrl,e,i.params),s=t._config.merge(i,{body:r,method:n,url:a});return t._fetch(a,s)}})}},{key:"_initMiddlewareMethods",value:function(){var t=this;["before","after","finally"].forEach(function(e){t[e]=function(){var n;return(n=t._middleware)[e].apply(n,arguments)}})}}]),t}())})}).call(e,n(3))},function(t,e,n){"use strict";var r={apiUrl:"https://platzi-music-api.now.sh"};e.a=r},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"main"},[n("div",[n("div",{staticClass:"search"},[n("input",{directives:[{name:"model",rawName:"v-model",value:t.searchQuery,expression:"searchQuery"}],attrs:{type:"text",placeholder:"Busca Canciones"},domProps:{value:t.searchQuery},on:{input:function(e){e.target.composing||(t.searchQuery=e.target.value)}}}),n("button",{on:{click:t.clearTracksList}},[t._v("×")])]),n("div",{staticClass:"tracks-list"},t._l(t.tracks,function(e){return n("div",{staticClass:"track",on:{click:function(n){t.setTrack(e)}}},[n("figure",[n("img",{attrs:{src:e.album.images[0].url}})]),n("div",[n("p",[n("strong",[t._v(t._s(t._f("maxLetters")(e.name)))])]),n("p",[t._v(t._s(e.album.artists[0].name))])])])})),n("div",{directives:[{name:"show",rawName:"v-show",value:!0,expression:" true "}],staticClass:"more-tracks"},[t._v("V")])])])},i=[],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";function r(t){n(37)}var i=n(9),o=n(39),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-1d88c0c2",null);e.a=c.exports},function(t,e,n){var r=n(38);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("3da9f528",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,".main[data-v-1d88c0c2]{display:flex;flex-direction:column;align-items:center;justify-content:flex-start;max-width:35vw}figure[data-v-1d88c0c2]{width:200px}img[data-v-1d88c0c2]{width:100%;obeject-fit:cover}ul[data-v-1d88c0c2]{list-style:none;padding:0;max-height:40vh;overflow:auto;border-top:1px dashed}ul[data-v-1d88c0c2]::-webkit-scrollbar{display:none}span[data-v-1d88c0c2]{cursor:pointer;text-decoration:none;color:inherit}span[data-v-1d88c0c2]:hover{color:#41b883}span[data-v-1d88c0c2]:active{color:#385b7f}",""])},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"main"},[n("h1",[t._v(t._s(t.artist))]),n("figure",[n("img",{attrs:{src:t.tracks[0].album.images[0].url}})]),n("h3",[t._v("Otras canciones")]),n("ul",t._l(t.artistsTracks,function(e){return n("li",{on:{click:function(n){t.setTrack(e)}}},[n("span",[t._v(t._s(t._f("maxLetters")(e.name)))])])}))])},i=[],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";function r(t){n(41)}var i=n(10),o=n(43),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-48f4a6e6",null);e.a=c.exports},function(t,e,n){var r=n(42);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("bf46df22",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,".main[data-v-48f4a6e6]{display:flax;flex-direction:column;align-items:center;padding:10px;border-left:1px solid #000;border-right:1px solid #000;max-width:30vw}.name-song[data-v-48f4a6e6]{font-size:1.8rem}.name-artist[data-v-48f4a6e6]{padding-left:10px}figure[data-v-48f4a6e6]{width:300px}img[data-v-48f4a6e6]{width:100%;obeject-fit:cover}.description[data-v-48f4a6e6]{display:flex;margin:10px 0 0;align-self:flex-start}.description figure[data-v-48f4a6e6]{width:50px}.link[data-v-48f4a6e6]{text-decoration:none;color:inherit}.link[data-v-48f4a6e6]:hover{color:#41b883}.link[data-v-48f4a6e6]:active{color:#385b7f}",""])},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"main"},[n("div",{staticClass:"name-song"},[n("p",[t._v(t._s(t.track.name?t.track.name:"cancion"))])]),n("figure",[n("img",{attrs:{src:t.track.album.images[0].url}})]),n("div",{staticClass:"description"},[n("figure",[n("img",{attrs:{src:t.track.album.images[0].url}})]),n("div",{staticClass:"name-artist"},[n("p",[t._v(t._s(t.track.name?t.track.album.artists[0].name:"Artista"))]),n("div",{staticClass:"time"},[n("span",[t._v(t._s(t.track.duration_ms))])])])]),n("a",{staticClass:"link",attrs:{target:"_blank",href:t.theLink}},[n("p",[t._v("go to spotify")])]),n("div",{staticClass:"player"},[n("audio",{attrs:{controls:"controls",autoplay:"autoplay",src:t.track.preview_url}})])])},i=[],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("vm-aside-left"),n("vm-middel-content"),n("vm-aside-right")],1)},i=[],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";function r(t){n(46)}var i=n(11),o=n(48),a=n(2),s=r,c=a(i.a,o.a,!1,s,"data-v-23a4a0a2",null);e.a=c.exports},function(t,e,n){var r=n(47);"string"==typeof r&&(r=[[t.i,r,""]]),r.locals&&(t.exports=r.locals);n(1)("2ea2b887",r,!0,{})},function(t,e,n){e=t.exports=n(0)(!1),e.push([t.i,"div[data-v-23a4a0a2]{background-color:#191919;color:#fff;min-height:5vh;display:flex;justify-content:space-between;align-items:center}.name[data-v-23a4a0a2]{padding-left:20px}ul[data-v-23a4a0a2]{list-style:none;padding:0}li[data-v-23a4a0a2]{display:inline-block;padding:0 10px;border-right:1px solid}li[data-v-23a4a0a2]:last-child{border-right:none}a[data-v-23a4a0a2]{text-decoration:none;color:inherit}a[data-v-23a4a0a2]:hover{color:#41b883}a[data-v-23a4a0a2]:active{color:#385b7f}",""])},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement;t._self._c;return t._m(0)},i=[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",[n("span",{staticClass:"name"},[t._v("2018 by D4ndres")]),n("ul",[n("li",[n("span",[n("a",{attrs:{target:"_blank",href:"https://codepen.io/d4ndres/"}},[t._v(" codepen")])])]),n("li",[n("span",[n("a",{attrs:{href:"https://github.com/d4ndres"}},[t._v("GitHub")])])]),n("li",[n("span",[n("a",{attrs:{href:"https://d4ndres.github.io/portafolio/"}},[t._v("portafolio")])])])])])}],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";var r=function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{attrs:{id:"app"}},[n("vm-header"),n("vm-main-content"),n("vm-footer")],1)},i=[],o={render:r,staticRenderFns:i};e.a=o},function(t,e,n){"use strict";var r={};r.install=function(t){t.prototype.$bus=new t},e.a=r}]); //# sourceMappingURL=build.js.map
mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "payroll taxes", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "66625", "MEMO CODE": "", "PAYEE STATE": "KS", "PAYEE LAST NAME": "", "PAYEE CITY": "Topeka", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00019380", "EXPENDITURE AMOUNT (F3L Bundled)": "240.68", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "915 SW Harrison", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727387.fec_1.yml", "CONDUIT STATE": "", "CATEGORY CODE": "", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "D137865", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20100921", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Kansas Department of Revenue", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB30B"}); mycallback( {"ELECTION CODE": "G2010", "EXPENDITURE PURPOSE DESCRIP": "payroll taxes", "BENEFICIARY CANDIDATE OFFICE": "", "PAYEE ZIP": "66625", "MEMO CODE": "", "PAYEE STATE": "KS", "PAYEE LAST NAME": "", "PAYEE CITY": "Topeka", "PAYEE SUFFIX": "", "CONDUIT STREET 2": "", "CONDUIT STREET 1": "", "PAYEE FIRST NAME": "", "BACK REFERENCE SCHED NAME": "", "BENEFICIARY COMMITTEE NAME": "", "PAYEE PREFIX": "", "MEMO TEXT/DESCRIPTION": "", "FILER COMMITTEE ID NUMBER": "C00019380", "EXPENDITURE AMOUNT (F3L Bundled)": "240.68", "BENEFICIARY CANDIDATE MIDDLE NAME": "", "BENEFICIARY CANDIDATE LAST NAME": "", "_record_type": "fec.version.v7_0.SB", "PAYEE STREET 2": "", "PAYEE STREET 1": "915 SW Harrison", "SEMI-ANNUAL REFUNDED BUNDLED AMT": "", "Reference to SI or SL system code that identifies the Account": "", "CONDUIT CITY": "", "ENTITY TYPE": "ORG", "BENEFICIARY CANDIDATE FEC ID": "", "BENEFICIARY COMMITTEE FEC ID": "", "BENEFICIARY CANDIDATE STATE": "", "BENEFICIARY CANDIDATE FIRST NAME": "", "PAYEE MIDDLE NAME": "", "ELECTION OTHER DESCRIPTION": "", "_src_file": "2011/20110504/727387.fec_1.yml", "CONDUIT STATE": "", "CATEGORY CODE": "", "EXPENDITURE PURPOSE CODE": "", "BENEFICIARY CANDIDATE DISTRICT": "", "TRANSACTION ID NUMBER": "D137865", "BACK REFERENCE TRAN ID NUMBER": "", "EXPENDITURE DATE": "20100921", "BENEFICIARY CANDIDATE PREFIX": "", "CONDUIT NAME": "", "PAYEE ORGANIZATION NAME": "Kansas Department of Revenue", "BENEFICIARY CANDIDATE SUFFIX": "", "CONDUIT ZIP": "", "FORM TYPE": "SB30B"});
/** * @author mrdoob / http://mrdoob.com/ * @author jetienne / http://jetienne.com/ * @author paulirish / http://paulirish.com/ */ var MemoryStats = function () { var msMin = 100; var msMax = 0; var container = document.createElement('div'); container.id = 'stats'; container.style.cssText = 'width:80px;opacity:0.9;cursor:pointer'; var msDiv = document.createElement('div'); msDiv.id = 'ms'; msDiv.style.cssText = 'padding:0 0 3px 3px;text-align:left;background-color:#020;'; container.appendChild(msDiv); var msText = document.createElement('div'); msText.id = 'msText'; msText.style.cssText = 'color:#0f0;font-family:Helvetica,Arial,sans-serif;font-size:9px;font-weight:bold;line-height:15px'; msText.innerHTML = 'Memory'; msDiv.appendChild(msText); var msGraph = document.createElement('div'); msGraph.id = 'msGraph'; msGraph.style.cssText = 'position:relative;width:74px;height:30px;background-color:#0f0'; msDiv.appendChild(msGraph); while (msGraph.children.length < 74) { var bar = document.createElement('span'); bar.style.cssText = 'width:1px;height:30px;float:left;background-color:#131'; msGraph.appendChild(bar); } var updateGraph = function (dom, height, color) { var child = dom.appendChild(dom.firstChild); child.style.height = height + 'px'; if (color) child.style.backgroundColor = color; }; var perf = window.performance || {}; // polyfill usedJSHeapSize if (!perf && !perf.memory) { perf.memory = { usedJSHeapSize: 0 }; } if (perf && !perf.memory) { perf.memory = { usedJSHeapSize: 0 }; } // support of the API? if (perf.memory.totalJSHeapSize === 0) { console.warn('totalJSHeapSize === 0... performance.memory is only available in Chrome .'); } // TODO, add a sanity check to see if values are bucketed. // If so, reminde user to adopt the --enable-precise-memory-info flag. // open -a "/Applications/Google Chrome.app" --args --enable-precise-memory-info var lastTime = Date.now(); var lastUsedHeap = perf.memory.usedJSHeapSize; return { domElement: container, update: function () { // refresh only 30time per second if (Date.now() - lastTime < 1000 / 30) return; lastTime = Date.now(); var delta = perf.memory.usedJSHeapSize - lastUsedHeap; lastUsedHeap = perf.memory.usedJSHeapSize; var color = delta < 0 ? '#830' : '#131'; var ms = perf.memory.usedJSHeapSize; msMin = Math.min(msMin, ms); msMax = Math.max(msMax, ms); msText.textContent = 'Mem: ' + bytesToSize(ms, 2); var normValue = ms / (30 * 1024 * 1024); var height = Math.min(30, 30 - normValue * 30); updateGraph(msGraph, height, color); function bytesToSize(bytes, nFractDigit) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return 'n/a'; nFractDigit = nFractDigit !== undefined ? nFractDigit : 0; var precision = Math.pow(10, nFractDigit); var i = Math.floor(Math.log(bytes) / Math.log(1024)); return Math.round((bytes * precision) / Math.pow(1024, i)) / precision + ' ' + sizes[i]; } }, }; }; (function () { var stats = new MemoryStats(); stats.domElement.style.position = 'fixed'; stats.domElement.style.right = '0px'; stats.domElement.style.bottom = '0px'; document.body.appendChild(stats.domElement); requestAnimationFrame(function rAFloop() { stats.update(); requestAnimationFrame(rAFloop); }); return { memoryStats: stats, renderRate: renderRate, }; })();
module.exports = { importer: { isImporter() { return true; } }, data: ['a', 'b', 'c'], };
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/402/A def f(l): k,a,b,v = l ns = (a+v-1)//v return max(ns-b,(ns+k-1)//k) l = list(map(int,input().split())) print(f(l))
const router = require('express').Router(); const { Tag, Product, ProductTag } = require('../../models'); // The `/api/tags` endpoint // find all tags router.get('/', async (req, data) => { try { const tags = await Tag.findAll( {include: [{ model: Product, as: "product_tags"}]} ) data.status(200).json(tags) } catch (error) { data.status(500).json(error) } }); // find a single tag by its `id` router.get('/:id', async (req, data) => { try { const tags = await Tag.findByPk(req.params.id, { include: [{ model: Product, as: "product_tags"}]}) data.status(200).json(tags) } catch (error) { data.status(500).json(error) } }); // create a new tag router.post('/', async (req, data) => { try { const tags = await Tag.create(req.body) data.status(200).json(tags) } catch (error) { data.status(500).json(error) } }); // update a tag's name by its `id` value router.put('/:id', async (req, data) => { try { const tags = await Tag.update(req.body, {where: { id: req.params.id}} ) data.status(200).json(tags) } catch (error) { data.status(500).json(error) } }); // delete on tag by its `id` value router.delete('/:id', async (req, data) => { try { const tags = await Tag.destroy({where: { id: req.params.id}}) data.status(200).json(tags) } catch (error) { data.status(500).json(error) } }); module.exports = router;
'use strict'; /** * Module dependencies */ var should = require('should'), mongoose = require('mongoose'), request = require('supertest')('http://localhost:3000'), passport = require('passport'), Campaign = mongoose.model('Campaign'), User = mongoose.model('User'); var agent = require('supertest').agent('http://localhost:3000'); var campaign, user1, user2; /** * Unit tests */ describe('Campaign route unit tests:', function() { before(function(done) { user1 = new User({ firstName: 'Bayo', lastname: 'Mando', displayName: 'BayoMando', email: '[email protected]', username:'username', provider:'google' }); //invalid user user2 = new User({ firstName: 'User2', lastname: 'Mando2', displayName:'Manod2User2', email: '[email protected]', username:'username2', provider: 'google' }); campaign = new Campaign({ title: 'A mock Campaign', description: 'This is a description campaign', youtubeUrl: 'https://www.youtube.com/watch?v=kC0JYp79tdo', amount: '1223232', dueDate: new Date() }); campaign.save(function(err, campaign) { if(err){ done(err); } else { user1.save(done); } }); }); describe('When the user is not logged in', function() { it('fails to update a campaign', function(done) { campaign.title = 'Edited campaign'; agent .put('/campaign/' + campaign._id + '/edit') .send(campaign) .expect('Content-Type', /json/) .expect(401) .end(function(err, res) { if (err) { return done(err); } res.body.should.have.property('message', 'User is not logged in'); done(); }); }); }); describe('When the user is logged in', function() { before(function(done) { this.timeout(3000); agent .post('/auth/mock') .send({ firstName: 'A new test', lastName: 'User', username: 'tuser', email: '[email protected]', provider: 'google' }) .expect(200) .end(function(err, res) { if (err) { return done(err); } res.body.should.have.property('success', true); var user = res.body.user; done(); }); }); it('should create a campaign', function (done) { agent.post('/campaign/add').expect('Content-Type', /json/).end(function (err, res) { if (err) { return done(err); } res.body.title.should.equal(campaign.title); done(); }); }); it('should update a campaign', function(done){ campaign.title = 'After Editing'; agent .put('/campaign/' + campaign._id + '/edit') .send(campaign) .expect(200) .expect('Content-Type', /json/) .end(function(err, res){ if(err){ return done(err); } res.body.title.should.equal(campaign.title); done(); }); }); after(function(done) { agent .get('/auth/mock/logout') .expect('Content-Type', /json/) .expect(200) .end(function(err, res) { if (err) { return done(err); } res.body.should.have.property('success', true); done(); }); }); }); after(function(done) { User.remove().exec(); Campaign.remove().exec(); done(); }); });
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs __all__ = [ 'GetKeysResult', 'AwaitableGetKeysResult', 'get_keys', 'get_keys_output', ] @pulumi.output_type class GetKeysResult: """ A collection of values returned by getKeys. """ def __init__(__self__, id=None, key_signing_keys=None, managed_zone=None, project=None, zone_signing_keys=None): if id and not isinstance(id, str): raise TypeError("Expected argument 'id' to be a str") pulumi.set(__self__, "id", id) if key_signing_keys and not isinstance(key_signing_keys, list): raise TypeError("Expected argument 'key_signing_keys' to be a list") pulumi.set(__self__, "key_signing_keys", key_signing_keys) if managed_zone and not isinstance(managed_zone, str): raise TypeError("Expected argument 'managed_zone' to be a str") pulumi.set(__self__, "managed_zone", managed_zone) if project and not isinstance(project, str): raise TypeError("Expected argument 'project' to be a str") pulumi.set(__self__, "project", project) if zone_signing_keys and not isinstance(zone_signing_keys, list): raise TypeError("Expected argument 'zone_signing_keys' to be a list") pulumi.set(__self__, "zone_signing_keys", zone_signing_keys) @property @pulumi.getter def id(self) -> str: """ The provider-assigned unique ID for this managed resource. """ return pulumi.get(self, "id") @property @pulumi.getter(name="keySigningKeys") def key_signing_keys(self) -> Sequence['outputs.GetKeysKeySigningKeyResult']: """ A list of Key-signing key (KSK) records. Structure is documented below. Additionally, the DS record is provided: """ return pulumi.get(self, "key_signing_keys") @property @pulumi.getter(name="managedZone") def managed_zone(self) -> str: return pulumi.get(self, "managed_zone") @property @pulumi.getter def project(self) -> str: return pulumi.get(self, "project") @property @pulumi.getter(name="zoneSigningKeys") def zone_signing_keys(self) -> Sequence['outputs.GetKeysZoneSigningKeyResult']: """ A list of Zone-signing key (ZSK) records. Structure is documented below. """ return pulumi.get(self, "zone_signing_keys") class AwaitableGetKeysResult(GetKeysResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetKeysResult( id=self.id, key_signing_keys=self.key_signing_keys, managed_zone=self.managed_zone, project=self.project, zone_signing_keys=self.zone_signing_keys) def get_keys(managed_zone: Optional[str] = None, project: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetKeysResult: """ Get the DNSKEY and DS records of DNSSEC-signed managed zones. For more information see the [official documentation](https://cloud.google.com/dns/docs/dnskeys/) and [API](https://cloud.google.com/dns/docs/reference/v1/dnsKeys). ## Example Usage ```python import pulumi import pulumi_gcp as gcp foo = gcp.dns.ManagedZone("foo", dns_name="foo.bar.", dnssec_config=gcp.dns.ManagedZoneDnssecConfigArgs( state="on", non_existence="nsec3", )) foo_dns_keys = gcp.dns.get_keys_output(managed_zone=foo.id) pulumi.export("fooDnsDsRecord", foo_dns_keys.key_signing_keys[0].ds_record) ``` :param str managed_zone: The name or id of the Cloud DNS managed zone. :param str project: The ID of the project in which the resource belongs. If `project` is not provided, the provider project is used. """ __args__ = dict() __args__['managedZone'] = managed_zone __args__['project'] = project if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('gcp:dns/getKeys:getKeys', __args__, opts=opts, typ=GetKeysResult).value return AwaitableGetKeysResult( id=__ret__.id, key_signing_keys=__ret__.key_signing_keys, managed_zone=__ret__.managed_zone, project=__ret__.project, zone_signing_keys=__ret__.zone_signing_keys) @_utilities.lift_output_func(get_keys) def get_keys_output(managed_zone: Optional[pulumi.Input[str]] = None, project: Optional[pulumi.Input[Optional[str]]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetKeysResult]: """ Get the DNSKEY and DS records of DNSSEC-signed managed zones. For more information see the [official documentation](https://cloud.google.com/dns/docs/dnskeys/) and [API](https://cloud.google.com/dns/docs/reference/v1/dnsKeys). ## Example Usage ```python import pulumi import pulumi_gcp as gcp foo = gcp.dns.ManagedZone("foo", dns_name="foo.bar.", dnssec_config=gcp.dns.ManagedZoneDnssecConfigArgs( state="on", non_existence="nsec3", )) foo_dns_keys = gcp.dns.get_keys_output(managed_zone=foo.id) pulumi.export("fooDnsDsRecord", foo_dns_keys.key_signing_keys[0].ds_record) ``` :param str managed_zone: The name or id of the Cloud DNS managed zone. :param str project: The ID of the project in which the resource belongs. If `project` is not provided, the provider project is used. """ ...
# tasks.py import collections import json import os import sys import uuid from pathlib import Path from nltk.corpus import stopwords COMMON_WORDS = set(stopwords.words("english")) BASE_DIR = Path(__file__).resolve(strict=True).parent DATA_DIR = Path(BASE_DIR).joinpath("data") OUTPUT_DIR = Path(BASE_DIR).joinpath("output") def save_file(filename, data): random_str = uuid.uuid4().hex outfile = f"{filename}_{random_str}.txt" with open(Path(OUTPUT_DIR).joinpath(outfile), "w") as outfile: outfile.write(data) def get_word_counts(filename): wordcount = collections.Counter() # get counts with open(Path(DATA_DIR).joinpath(filename), "r") as f: for line in f: wordcount.update(line.split()) for word in set(COMMON_WORDS): del wordcount[word] # save file save_file(filename, json.dumps(dict(wordcount.most_common(20)))) proc = os.getpid() print(f"Processed {filename} with process id: {proc}") if __name__ == "__main__": get_word_counts(sys.argv[1])
/** * Created by WangFeng on 2017/1/21 0021. */ const exp = require('express'); const Student = require('./student'); const router = exp.Router(); router.get('/remove/:id', (req, res)=> { var id = req.params.id; Student.findByIdAndRemove(id, (err)=> { if (err) { res.json({result: 0}); } else { res.json({result: 1}); } }) }); module.exports = router;
//>>built require({cache:{ 'url:dijit/form/templates/DropDownBox.html':"<div class=\"dijit dijitReset dijitInline dijitLeft\"\n\tid=\"widget_${id}\"\n\trole=\"combobox\"\n\t><div class='dijitReset dijitRight dijitButtonNode dijitArrowButton dijitDownArrowButton dijitArrowButtonContainer'\n\t\tdata-dojo-attach-point=\"_buttonNode, _popupStateNode\" role=\"presentation\"\n\t\t><input class=\"dijitReset dijitInputField dijitArrowButtonInner\" value=\"&#9660; \" type=\"text\" tabIndex=\"-1\" readonly=\"readonly\" role=\"presentation\"\n\t\t\t${_buttonInputDisabled}\n\t/></div\n\t><div class='dijitReset dijitValidationContainer'\n\t\t><input class=\"dijitReset dijitInputField dijitValidationIcon dijitValidationInner\" value=\"&#935; \" type=\"text\" tabIndex=\"-1\" readonly=\"readonly\" role=\"presentation\"\n\t/></div\n\t><div class=\"dijitReset dijitInputField dijitInputContainer\"\n\t\t><input class='dijitReset dijitInputInner' ${!nameAttrSetting} type=\"text\" autocomplete=\"off\"\n\t\t\tdata-dojo-attach-point=\"textbox,focusNode\" role=\"textbox\" aria-haspopup=\"true\"\n\t/></div\n></div>\n"}}); define("dijit/form/_DateTimeTextBox", [ "dojo/date", // date date.compare "dojo/date/locale", // locale.regexp "dojo/date/stamp", // stamp.fromISOString stamp.toISOString "dojo/_base/declare", // declare "dojo/_base/lang", // lang.getObject "./RangeBoundTextBox", "../_HasDropDown", "dojo/text!./templates/DropDownBox.html" ], function(date, locale, stamp, declare, lang, RangeBoundTextBox, _HasDropDown, template){ /*===== var _HasDropDown = dijit._HasDropDown; var RangeBoundTextBox = dijit.form.RangeBoundTextBox; =====*/ // module: // dijit/form/_DateTimeTextBox // summary: // Base class for validating, serializable, range-bound date or time text box. new Date("X"); // workaround for #11279, new Date("") == NaN /*===== declare( "dijit.form._DateTimeTextBox.__Constraints", [RangeBoundTextBox.__Constraints, locale.__FormatOptions], { // summary: // Specifies both the rules on valid/invalid values (first/last date/time allowed), // and also formatting options for how the date/time is displayed. // example: // To restrict to dates within 2004, displayed in a long format like "December 25, 2005": // | {min:'2004-01-01',max:'2004-12-31', formatLength:'long'} }); =====*/ var _DateTimeTextBox = declare("dijit.form._DateTimeTextBox", [RangeBoundTextBox, _HasDropDown], { // summary: // Base class for validating, serializable, range-bound date or time text box. templateString: template, // hasDownArrow: [const] Boolean // Set this textbox to display a down arrow button, to open the drop down list. hasDownArrow: true, // openOnClick: [const] Boolean // Set to true to open drop down upon clicking anywhere on the textbox. openOnClick: true, /*===== // constraints: dijit.form._DateTimeTextBox.__Constraints // Despite the name, this parameter specifies both constraints on the input // (including starting/ending dates/times allowed) as well as // formatting options like whether the date is displayed in long (ex: December 25, 2005) // or short (ex: 12/25/2005) format. See `dijit.form._DateTimeTextBox.__Constraints` for details. constraints: {}, ======*/ // Override ValidationTextBox.regExpGen().... we use a reg-ex generating function rather // than a straight regexp to deal with locale (plus formatting options too?) regExpGen: locale.regexp, // datePackage: String // JavaScript namespace to find calendar routines. Uses Gregorian calendar routines // at dojo.date, by default. datePackage: date, postMixInProperties: function(){ this.inherited(arguments); this._set("type", "text"); // in case type="date"|"time" was specified which messes up parse/format }, // Override _FormWidget.compare() to work for dates/times compare: function(/*Date*/ val1, /*Date*/ val2){ var isInvalid1 = this._isInvalidDate(val1); var isInvalid2 = this._isInvalidDate(val2); return isInvalid1 ? (isInvalid2 ? 0 : -1) : (isInvalid2 ? 1 : date.compare(val1, val2, this._selector)); }, // flag to _HasDropDown to make drop down Calendar width == <input> width forceWidth: true, format: function(/*Date*/ value, /*dojo.date.locale.__FormatOptions*/ constraints){ // summary: // Formats the value as a Date, according to specified locale (second argument) // tags: // protected if(!value){ return ''; } return this.dateLocaleModule.format(value, constraints); }, "parse": function(/*String*/ value, /*dojo.date.locale.__FormatOptions*/ constraints){ // summary: // Parses as string as a Date, according to constraints // tags: // protected return this.dateLocaleModule.parse(value, constraints) || (this._isEmpty(value) ? null : undefined); // Date }, // Overrides ValidationTextBox.serialize() to serialize a date in canonical ISO format. serialize: function(/*anything*/ val, /*Object?*/ options){ if(val.toGregorian){ val = val.toGregorian(); } return stamp.toISOString(val, options); }, // dropDownDefaultValue: Date // The default value to focus in the popupClass widget when the textbox value is empty. dropDownDefaultValue : new Date(), // value: Date // The value of this widget as a JavaScript Date object. Use get("value") / set("value", val) to manipulate. // When passed to the parser in markup, must be specified according to `dojo.date.stamp.fromISOString` value: new Date(""), // value.toString()="NaN" _blankValue: null, // used by filter() when the textbox is blank // popupClass: [protected extension] String // Name of the popup widget class used to select a date/time. // Subclasses should specify this. popupClass: "", // default is no popup = text only // _selector: [protected extension] String // Specifies constraints.selector passed to dojo.date functions, should be either // "date" or "time". // Subclass must specify this. _selector: "", constructor: function(/*Object*/ args){ this.datePackage = args.datePackage || this.datePackage; this.dateFuncObj = typeof this.datePackage == "string" ? lang.getObject(this.datePackage, false) :// "string" part for back-compat, remove for 2.0 this.datePackage; this.dateClassObj = this.dateFuncObj.Date || Date; this.dateLocaleModule = lang.getObject("locale", false, this.dateFuncObj); this.regExpGen = this.dateLocaleModule.regexp; this._invalidDate = this.constructor.prototype.value.toString(); }, buildRendering: function(){ this.inherited(arguments); if(!this.hasDownArrow){ this._buttonNode.style.display = "none"; } // If openOnClick is true, we basically just want to treat the whole widget as the // button. We need to do that also if the actual drop down button will be hidden, // so that there's a mouse method for opening the drop down. if(this.openOnClick || !this.hasDownArrow){ this._buttonNode = this.domNode; this.baseClass += " dijitComboBoxOpenOnClick"; } }, _setConstraintsAttr: function(/*Object*/ constraints){ constraints.selector = this._selector; constraints.fullYear = true; // see #5465 - always format with 4-digit years var fromISO = stamp.fromISOString; if(typeof constraints.min == "string"){ constraints.min = fromISO(constraints.min); } if(typeof constraints.max == "string"){ constraints.max = fromISO(constraints.max); } this.inherited(arguments); }, _isInvalidDate: function(/*Date*/ value){ // summary: // Runs various tests on the value, checking for invalid conditions // tags: // private return !value || isNaN(value) || typeof value != "object" || value.toString() == this._invalidDate; }, _setValueAttr: function(/*Date|String*/ value, /*Boolean?*/ priorityChange, /*String?*/ formattedValue){ // summary: // Sets the date on this textbox. Note: value can be a JavaScript Date literal or a string to be parsed. if(value !== undefined){ if(typeof value == "string"){ value = stamp.fromISOString(value); } if(this._isInvalidDate(value)){ value = null; } if(value instanceof Date && !(this.dateClassObj instanceof Date)){ value = new this.dateClassObj(value); } } this.inherited(arguments); if(this.dropDown){ this.dropDown.set('value', value, false); } }, _set: function(attr, value){ // Avoid spurious watch() notifications when value is changed to new Date object w/the same value if(attr == "value" && this.value instanceof Date && this.compare(value, this.value) == 0){ return; } this.inherited(arguments); }, _setDropDownDefaultValueAttr: function(/*Date*/ val){ if(this._isInvalidDate(val)){ // convert null setting into today's date, since there needs to be *some* default at all times. val = new this.dateClassObj() } this.dropDownDefaultValue = val; }, openDropDown: function(/*Function*/ callback){ // rebuild drop down every time, so that constraints get copied (#6002) if(this.dropDown){ this.dropDown.destroy(); } var PopupProto = lang.isString(this.popupClass) ? lang.getObject(this.popupClass, false) : this.popupClass, textBox = this, value = this.get("value"); this.dropDown = new PopupProto({ onChange: function(value){ // this will cause InlineEditBox and other handlers to do stuff so make sure it's last _DateTimeTextBox.superclass._setValueAttr.call(textBox, value, true); }, id: this.id + "_popup", dir: textBox.dir, lang: textBox.lang, value: value, currentFocus: !this._isInvalidDate(value) ? value : this.dropDownDefaultValue, constraints: textBox.constraints, filterString: textBox.filterString, // for TimeTextBox, to filter times shown datePackage: textBox.datePackage, isDisabledDate: function(/*Date*/ date){ // summary: // disables dates outside of the min/max of the _DateTimeTextBox return !textBox.rangeCheck(date, textBox.constraints); } }); this.inherited(arguments); }, _getDisplayedValueAttr: function(){ return this.textbox.value; }, _setDisplayedValueAttr: function(/*String*/ value, /*Boolean?*/ priorityChange){ this._setValueAttr(this.parse(value, this.constraints), priorityChange, value); } }); return _DateTimeTextBox; });
import React from 'react'; import RenderAuthorized from '@/components/Authorized'; import Exception from '@/components/Exception'; import { matchRoutes } from 'react-router-config'; import uniq from 'lodash/uniq'; import { formatMessage } from 'umi/locale'; import Link from 'umi/link'; import { getAuthority } from '../utils/authority'; const Authorized = RenderAuthorized(getAuthority()); export default ({ children, route, location }) => { const routes = matchRoutes(route.routes, location.pathname); let authorities = []; routes.forEach(item => { if (Array.isArray(item.route.authority)) { authorities = authorities.concat(item.route.authority); } else if (typeof item.route.authority === 'string') { authorities.push(item.route.authority); } }); const noMatch = ( <Exception type="403" desc={formatMessage({ id: 'app.exception.description.403' })} linkElement={Link} backText={formatMessage({ id: 'app.exception.back' })} /> ); return ( <Authorized authority={authorities.length === 0 ? undefined : uniq(authorities)} noMatch={noMatch} > {children} </Authorized> ); };
import Vue from 'vue' import Vuex from 'vuex' import app from './modules/app' import user from './modules/user' import permission from './modules/permission' import getters from './getters' Vue.use(Vuex) console.log(user) const store = new Vuex.Store({ modules: { app, user, permission }, getters }) export default store
const { Listener } = require('discord-akairo'); var cLog = require("../helpers/log"); const generateNlp = require("../helpers/generateNlp"); var messagesPerMin = 0; class NlpListener extends Listener { constructor() { super('nlp', { emitter: 'client', eventName: 'message' }); } exec(message) { if (message.channel.name != "general") return; messagesPerMin += 1; setTimeout(() => { messagesPerMin -= 1 }, 430 * 1000); } } setInterval(() => { if (messagesPerMin == 0) { /*generateNlp({ len: 300 }).then(x => //global.client.guilds.get("300155035558346752").channels.get("300155035558346752").send(x) )*/ } }, 111 * 1000) module.exports = NlpListener;
""" Leetcode: https://leetcode.com/problems/two-sum/ Question: Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. You may assume that each input would have exactly one solution, and you may not use the same element twice. You can return the answer in any order Example 1: Input: nums = [2,7,11,15], target = 9 Output: [0,1] Output: Because nums[0] + nums[1] == 9, we return [0, 1] Constraints: 2 <= nums.length <= 104 -109 <= nums[i] <= 109 -109 <= target <= 109 Only one valid answer exists. Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity? """ class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: for i in range(len(nums)): if(target-nums[i]) in nums[i+1:]: return [i, nums[i+1:].index(target - nums[i])+(i+1)] """ Time Complexity: O(n) Space Complexity: O(n) """
export { default as MasterPage } from './MasterPage' export { default as UserMenu } from './UserMenu' export { default as SearchBar } from './SearchBar' export { default as MovieCard } from './MovieCard' export { default as Footer } from './Footer' export { default as MoviesList } from './MoviesList' export { default as Loader } from './Loader' export { default as LoadMore } from './LoadMore'
import React from 'react'; export const Modal = (props) => { const {dismissModal, submitModal, children} = props; document.addEventListener('keypress', (e) => { if(e.keyCode == 13){ submitModal(); } }); return( <div className="modal-mask"> <div className="modal"> {children} <div className="modal__actions"> <a onClick={dismissModal}>{submitModal ? 'Cancel' : 'Dismiss'}</a> {submitModal && <a onClick={submitModal}>Submit</a>} </div> </div> </div> ); } export default Modal;
#!/usr/bin/env node /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * 'License'); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var fs = require('fs'); var path = require('path'); var thrift = require('../lib/thrift'); var program = require('commander'); var helpers = require('./helpers'); var ThriftTest = require('./gen-nodejs/ThriftTest'); var SecondService = require('./gen-nodejs/SecondService'); var ThriftTestHandler = require('./test_handler').AsyncThriftTestHandler; var ThriftTestHandlerPromise = require('./test_handler').SyncThriftTestHandler; var ttypes = require('./gen-nodejs/ThriftTest_types'); program .option('-p, --protocol <protocol>', 'Set thrift protocol (binary|compact|json)', 'binary') .option('-t, --transport <transport>', 'Set thrift transport (buffered|framed|http)', 'buffered') .option('--ssl', 'use ssl transport') .option('--port <port>', 'Set thrift server port', 9090) .option('--domain-socket <path>', 'Set thift server unix domain socket') .option('--promise', 'test with promise style functions') .option('-t, --type <type>', 'Select server type (http|multiplex|tcp|websocket)', 'tcp') .parse(process.argv); var port = program.port; var domainSocket = program.domainSocket; var type = program.type; var ssl = program.ssl; var promise = program.promise; var handler = program.promise ? ThriftTestHandler : ThriftTestHandlerPromise; if (program.transport === 'http') { program.transport = 'buffered'; type = 'http'; } var options = { transport: helpers.transports[program.transport], protocol: helpers.protocols[program.protocol] }; if (type === 'http' || type ==='websocket') { options.handler = handler; options.processor = ThriftTest; options = { services: { "/test": options }, cors: { '*': true } } } if (type === 'multiplex') { var SecondServiceHandler = { secondtestString: function(thing, result) { console.log('testString("' + thing + '")'); result(null, 'testString("' + thing + '")'); } }; var processor = new thrift.MultiplexedProcessor(); processor.registerProcessor("ThriftTest", new ThriftTest.Processor(ThriftTestHandler)); processor.registerProcessor("SecondService", new SecondService.Processor(SecondServiceHandler)); } if (ssl) { if (type === 'tcp' || type === 'multiplex' || type === 'http' || type === 'websocket') { options.tls = { key: fs.readFileSync(path.resolve(__dirname, 'server.key')), cert: fs.readFileSync(path.resolve(__dirname, 'server.crt')) }; } } var server; if (type === 'tcp') { server = thrift.createServer(ThriftTest, handler, options); } else if (type === 'multiplex') { server = thrift.createMultiplexServer(processor, options); } else if (type === 'http' || type === 'websocket') { server = thrift.createWebServer(options); } if (domainSocket) { server.listen(domainSocket); } else if (type === 'tcp' || type === 'multiplex' || type === 'http' || type === 'websocket') { server.listen(port); }
# -*- coding: utf-8 -*- from unittest import mock from unittest.mock import MagicMock from unittest.mock import mock_open from unittest.mock import patch import pytest from pytube import Caption from pytube import CaptionQuery from pytube import captions def test_float_to_srt_time_format(): caption1 = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) assert caption1.float_to_srt_time_format(3.89) == "00:00:03,890" def test_caption_query_sequence(): caption1 = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) caption2 = Caption( {"url": "url2", "name": {"simpleText": "name2"}, "languageCode": "fr"} ) caption_query = CaptionQuery(captions=[caption1, caption2]) assert len(caption_query) == 2 assert caption_query["en"] == caption1 assert caption_query["fr"] == caption2 with pytest.raises(KeyError): assert caption_query["nada"] is not None def test_caption_query_get_by_language_code_when_exists(): caption1 = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) caption2 = Caption( {"url": "url2", "name": {"simpleText": "name2"}, "languageCode": "fr"} ) caption_query = CaptionQuery(captions=[caption1, caption2]) assert caption_query["en"] == caption1 def test_caption_query_get_by_language_code_when_not_exists(): caption1 = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) caption2 = Caption( {"url": "url2", "name": {"simpleText": "name2"}, "languageCode": "fr"} ) caption_query = CaptionQuery(captions=[caption1, caption2]) with pytest.raises(KeyError): assert caption_query["hello"] is not None # assert not_found is not None # should never reach here @mock.patch("pytube.captions.Caption.generate_srt_captions") def test_download(srt): open_mock = mock_open() with patch("builtins.open", open_mock): srt.return_value = "" caption = Caption( { "url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en", } ) caption.download("title") assert ( open_mock.call_args_list[0][0][0].split("/")[-1] == "title (en).srt" ) @mock.patch("pytube.captions.Caption.generate_srt_captions") def test_download_with_prefix(srt): open_mock = mock_open() with patch("builtins.open", open_mock): srt.return_value = "" caption = Caption( { "url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en", } ) caption.download("title", filename_prefix="1 ") assert ( open_mock.call_args_list[0][0][0].split("/")[-1] == "1 title (en).srt" ) @mock.patch("pytube.captions.Caption.generate_srt_captions") def test_download_with_output_path(srt): open_mock = mock_open() captions.target_directory = MagicMock(return_value="/target") with patch("builtins.open", open_mock): srt.return_value = "" caption = Caption( { "url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en", } ) file_path = caption.download("title", output_path="blah") assert file_path == "/target/title (en).srt" captions.target_directory.assert_called_with("blah") @mock.patch("pytube.captions.Caption.xml_captions") def test_download_xml_and_trim_extension(xml): open_mock = mock_open() with patch("builtins.open", open_mock): xml.return_value = "" caption = Caption( { "url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en", } ) caption.download("title.xml", srt=False) assert ( open_mock.call_args_list[0][0][0].split("/")[-1] == "title (en).xml" ) def test_repr(): caption = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) assert str(caption) == '<Caption lang="name1" code="en">' caption_query = CaptionQuery(captions=[caption]) assert repr(caption_query) == '{\'en\': <Caption lang="name1" code="en">}' @mock.patch("pytube.request.get") def test_xml_captions(request_get): request_get.return_value = "test" caption = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) assert caption.xml_captions == "test" @mock.patch("pytube.captions.request") def test_generate_srt_captions(request): request.get.return_value = ( '<?xml version="1.0" encoding="utf-8" ?><transcript><text start="6.5" dur="1.7">[' 'Herb, Software Engineer]\n本影片包含隱藏式字幕。</text><text start="8.3" dur="2.7">' "如要啓動字幕,請按一下這裡的圖示。</text></transcript>" ) caption = Caption( {"url": "url1", "name": {"simpleText": "name1"}, "languageCode": "en"} ) assert caption.generate_srt_captions() == ( "1\n" "00:00:06,500 --> 00:00:08,200\n" "[Herb, Software Engineer] 本影片包含隱藏式字幕。\n" "\n" "2\n" "00:00:08,300 --> 00:00:11,000\n" "如要啓動字幕,請按一下這裡的圖示。" )
var classes; export default classes = { "Anchor" : 1, "Appearance" : 1, "Arc2D" : 1, "ArcClose2D" : 1, "AudioClip" : 1, "Background" : 1, "BallJoint" : 1, "Billboard" : 1, "BlendedVolumeStyle" : 1, "BooleanFilter" : 1, "BooleanSequencer" : 1, "BooleanToggle" : 1, "BooleanTrigger" : 1, "BoundaryEnhancementVolumeStyle" : 1, "BoundedPhysicsModel" : 1, "Box" : 1, "CADAssembly" : 1, "CADFace" : 1, "CADLayer" : 1, "CADPart" : 1, "CartoonVolumeStyle" : 1, "Circle2D" : 1, "ClipPlane" : 1, "CollidableOffset" : 1, "CollidableShape" : 1, "Collision" : 1, "CollisionCollection" : 1, "CollisionSensor" : 1, "CollisionSpace" : 1, "Color" : 1, "ColorChaser" : 1, "ColorDamper" : 1, "ColorInterpolator" : 1, "ColorRGBA" : 1, "component" : 1, "ComposedCubeMapTexture" : 1, "ComposedShader" : 1, "ComposedTexture3D" : 1, "ComposedVolumeStyle" : 1, "Cone" : 1, "ConeEmitter" : 1, "connect" : 1, "Contact" : 1, "Contour2D" : 1, "ContourPolyline2D" : 1, "Coordinate" : 1, "CoordinateChaser" : 1, "CoordinateDamper" : 1, "CoordinateDouble" : 1, "CoordinateInterpolator" : 1, "CoordinateInterpolator2D" : 1, "Cylinder" : 1, "CylinderSensor" : 1, "DirectionalLight" : 1, "DISEntityManager" : 1, "DISEntityTypeMapping" : 1, "Disk2D" : 1, "DoubleAxisHingeJoint" : 1, "EaseInEaseOut" : 1, "EdgeEnhancementVolumeStyle" : 1, "ElevationGrid" : 1, "EspduTransform" : 1, "ExplosionEmitter" : 1, "EXPORT" : 1, "ExternProtoDeclare" : 1, "Extrusion" : 1, "field" : 1, "fieldValue" : 1, "FillProperties" : 1, "FloatVertexAttribute" : 1, "Fog" : 1, "FogCoordinate" : 1, "FontStyle" : 1, "ForcePhysicsModel" : 1, "GeneratedCubeMapTexture" : 1, "GeoCoordinate" : 1, "GeoElevationGrid" : 1, "GeoLocation" : 1, "GeoLOD" : 1, "GeoMetadata" : 1, "GeoOrigin" : 1, "GeoPositionInterpolator" : 1, "GeoProximitySensor" : 1, "GeoTouchSensor" : 1, "GeoTransform" : 1, "GeoViewpoint" : 1, "Group" : 1, "HAnimDisplacer" : 1, "HAnimHumanoid" : 1, "HAnimJoint" : 1, "HAnimMotion" : 1, "HAnimSegment" : 1, "HAnimSite" : 1, "head" : 1, "ImageCubeMapTexture" : 1, "ImageTexture" : 1, "ImageTexture3D" : 1, "IMPORT" : 1, "IndexedFaceSet" : 1, "IndexedLineSet" : 1, "IndexedQuadSet" : 1, "IndexedTriangleFanSet" : 1, "IndexedTriangleSet" : 1, "IndexedTriangleStripSet" : 1, "Inline" : 1, "IntegerSequencer" : 1, "IntegerTrigger" : 1, "IS" : 1, "IsoSurfaceVolumeData" : 1, "KeySensor" : 1, "Layer" : 1, "LayerSet" : 1, "Layout" : 1, "LayoutGroup" : 1, "LayoutLayer" : 1, "LinePickSensor" : 1, "LineProperties" : 1, "LineSet" : 1, "LoadSensor" : 1, "LocalFog" : 1, "LOD" : 1, "Material" : 1, "Matrix3VertexAttribute" : 1, "Matrix4VertexAttribute" : 1, "meta" : 1, "MetadataBoolean" : 1, "MetadataDouble" : 1, "MetadataFloat" : 1, "MetadataInteger" : 1, "MetadataSet" : 1, "MetadataString" : 1, "MFBool" : 1, "MFColor" : 1, "MFColorRGBA" : 1, "MFDouble" : 1, "MFFloat" : 1, "MFImage" : 1, "MFInt32" : 1, "MFMatrix3d" : 1, "MFMatrix3f" : 1, "MFMatrix4d" : 1, "MFMatrix4f" : 1, "MFNode" : 1, "MFRotation" : 1, "MFString" : 1, "MFTime" : 1, "MFVec2d" : 1, "MFVec2f" : 1, "MFVec3d" : 1, "MFVec3f" : 1, "MFVec4d" : 1, "MFVec4f" : 1, "MotorJoint" : 1, "MovieTexture" : 1, "MultiTexture" : 1, "MultiTextureCoordinate" : 1, "MultiTextureTransform" : 1, "NavigationInfo" : 1, "Normal" : 1, "NormalInterpolator" : 1, "NurbsCurve" : 1, "NurbsCurve2D" : 1, "NurbsOrientationInterpolator" : 1, "NurbsPatchSurface" : 1, "NurbsPositionInterpolator" : 1, "NurbsSet" : 1, "NurbsSurfaceInterpolator" : 1, "NurbsSweptSurface" : 1, "NurbsSwungSurface" : 1, "NurbsTextureCoordinate" : 1, "NurbsTrimmedSurface" : 1, "OpacityMapVolumeStyle" : 1, "OrientationChaser" : 1, "OrientationDamper" : 1, "OrientationInterpolator" : 1, "OrthoViewpoint" : 1, "PackagedShader" : 1, "ParticleSystem" : 1, "PickableGroup" : 1, "PixelTexture" : 1, "PixelTexture3D" : 1, "PlaneSensor" : 1, "PointEmitter" : 1, "PointLight" : 1, "PointPickSensor" : 1, "PointProperties" : 1, "PointSet" : 1, "Polyline2D" : 1, "PolylineEmitter" : 1, "Polypoint2D" : 1, "PositionChaser" : 1, "PositionChaser2D" : 1, "PositionDamper" : 1, "PositionDamper2D" : 1, "PositionInterpolator" : 1, "PositionInterpolator2D" : 1, "PrimitivePickSensor" : 1, "ProgramShader" : 1, "ProjectionVolumeStyle" : 1, "ProtoBody" : 1, "ProtoDeclare" : 1, "ProtoInstance" : 1, "ProtoInterface" : 1, "ProximitySensor" : 1, "QuadSet" : 1, "ReceiverPdu" : 1, "Rectangle2D" : 1, "RigidBody" : 1, "RigidBodyCollection" : 1, "ROUTE" : 1, "ScalarChaser" : 1, "ScalarDamper" : 1, "ScalarInterpolator" : 1, "Scene" : 1, "ScreenFontStyle" : 1, "ScreenGroup" : 1, "Script" : 1, "SegmentedVolumeData" : 1, "SFBool" : 1, "SFColor" : 1, "SFColorRGBA" : 1, "SFDouble" : 1, "SFFloat" : 1, "SFImage" : 1, "SFInt32" : 1, "SFMatrix3d" : 1, "SFMatrix3f" : 1, "SFMatrix4d" : 1, "SFMatrix4f" : 1, "SFNode" : 1, "SFRotation" : 1, "SFString" : 1, "SFTime" : 1, "SFVec2d" : 1, "SFVec2f" : 1, "SFVec3d" : 1, "SFVec3f" : 1, "SFVec4d" : 1, "SFVec4f" : 1, "ShadedVolumeStyle" : 1, "ShaderPart" : 1, "ShaderProgram" : 1, "Shape" : 1, "SignalPdu" : 1, "SilhouetteEnhancementVolumeStyle" : 1, "SingleAxisHingeJoint" : 1, "SliderJoint" : 1, "Sound" : 1, "Sphere" : 1, "SphereSensor" : 1, "SplinePositionInterpolator" : 1, "SplinePositionInterpolator2D" : 1, "SplineScalarInterpolator" : 1, "SpotLight" : 1, "SquadOrientationInterpolator" : 1, "StaticGroup" : 1, "StringSensor" : 1, "SurfaceEmitter" : 1, "Switch" : 1, "TexCoordChaser2D" : 1, "TexCoordDamper2D" : 1, "Text" : 1, "TextureBackground" : 1, "TextureCoordinate" : 1, "TextureCoordinate3D" : 1, "TextureCoordinate4D" : 1, "TextureCoordinateGenerator" : 1, "TextureProperties" : 1, "TextureTransform" : 1, "TextureTransform3D" : 1, "TextureTransformMatrix3D" : 1, "TimeSensor" : 1, "TimeTrigger" : 1, "ToneMappedVolumeStyle" : 1, "TouchSensor" : 1, "Transform" : 1, "TransformSensor" : 1, "TransmitterPdu" : 1, "TriangleFanSet" : 1, "TriangleSet" : 1, "TriangleSet2D" : 1, "TriangleStripSet" : 1, "TwoSidedMaterial" : 1, "unit" : 1, "UniversalJoint" : 1, "Viewpoint" : 1, "ViewpointGroup" : 1, "Viewport" : 1, "VisibilitySensor" : 1, "VolumeData" : 1, "VolumeEmitter" : 1, "VolumePickSensor" : 1, "WindPhysicsModel" : 1, "WorldInfo" : 1, "X3D" : 1, "X3DAppearanceChildNode" : 1, "X3DAppearanceNode" : 1, "X3DBackgroundNode" : 1, "X3DBindableNode" : 1, "X3DBoundedObject" : 1, "X3DChaserNode" : 1, "X3DChildNode" : 1, "X3DColorNode" : 1, "X3DComposableVolumeRenderStyleNode" : 1, "X3DComposedGeometryNode" : 1, "X3DCoordinateNode" : 1, "X3DDamperNode" : 1, "X3DDragSensorNode" : 1, "X3DEnvironmentalSensorNode" : 1, "X3DEnvironmentTextureNode" : 1, "X3DFogObject" : 1, "X3DFollowerNode" : 1, "X3DFontStyleNode" : 1, "X3DGeometricPropertyNode" : 1, "X3DGeometryNode" : 1, "X3DGroupingNode" : 1, "X3DInfoNode" : 1, "X3DInterpolatorNode" : 1, "X3DKeyDeviceSensorNode" : 1, "X3DLayerNode" : 1, "X3DLayoutNode" : 1, "X3DLightNode" : 1, "X3DMaterialNode" : 1, "X3DMetadataObject" : 1, "X3DNBodyCollidableNode" : 1, "X3DNBodyCollisionSpaceNode" : 1, "X3DNetworkSensorNode" : 1, "X3DNode" : 1, "X3DNormalNode" : 1, "X3DNurbsControlCurveNode" : 1, "X3DNurbsSurfaceGeometryNode" : 1, "X3DParametricGeometryNode" : 1, "X3DParticleEmitterNode" : 1, "X3DParticlePhysicsModelNode" : 1, "X3DPickableObject" : 1, "X3DPickSensorNode" : 1, "X3DPointingDeviceSensorNode" : 1, "X3DProductStructureChildNode" : 1, "X3DProgrammableShaderObject" : 1, "X3DPrototypeInstance" : 1, "X3DRigidJointNode" : 1, "X3DScriptNode" : 1, "X3DSensorNode" : 1, "X3DSequencerNode" : 1, "X3DShaderNode" : 1, "X3DShapeNode" : 1, "X3DSoundNode" : 1, "X3DSoundSourceNode" : 1, "X3DTexture2DNode" : 1, "X3DTexture3DNode" : 1, "X3DTextureCoordinateNode" : 1, "X3DTextureNode" : 1, "X3DTextureTransformNode" : 1, "X3DTimeDependentNode" : 1, "X3DTouchSensorNode" : 1, "X3DTriggerNode" : 1, "X3DUrlObject" : 1, "X3DVertexAttributeNode" : 1, "X3DViewpointNode" : 1, "X3DViewportNode" : 1, "X3DVolumeDataNode" : 1, "X3DVolumeRenderStyleNode" : 1 };
#!/usr/bin/env python import os import shutil from glob import glob from tempfile import mkdtemp from collections import OrderedDict import numpy as np import pandas as pd from gsw import z_from_p, p_from_z from gutils import ( generate_stream, get_decimal_degrees, interpolate_gps, masked_epoch, safe_makedirs ) from gutils.ctd import calculate_practical_salinity, calculate_density import logging L = logging.getLogger(__name__) MODE_MAPPING = { "rt": ["sbd", "tbd", "mbd", "nbd"], "delayed": ["dbd", "ebd"] } ALL_EXTENSIONS = [".sbd", ".tbd", ".mbd", ".nbd", ".dbd", ".ebd"] class SlocumReader(object): TIMESTAMP_SENSORS = ['m_present_time', 'sci_m_present_time'] PRESSURE_SENSORS = ['sci_water_pressure', 'sci_water_pressure2', 'm_water_pressure', 'm_pressure'] DEPTH_SENSORS = ['m_depth', 'm_water_depth'] TEMPERATURE_SENSORS = ['sci_water_temp', 'sci_water_temp2'] CONDUCTIVITY_SENSORS = ['sci_water_cond', 'sci_water_cond2'] def __init__(self, ascii_file): self.ascii_file = ascii_file self.metadata, self.data = self.read() # Set the mode to 'rt' or 'delayed' self.mode = None if 'filename_extension' in self.metadata: filemode = self.metadata['filename_extension'] for m, extensions in MODE_MAPPING.items(): if filemode in extensions: self.mode = m break def read(self): metadata = OrderedDict() headers = None with open(self.ascii_file, 'rt') as af: for li, al in enumerate(af): if 'm_present_time' in al: headers = al.strip().split(' ') elif headers is not None: data_start = li + 2 # Skip units line and the interger row after that break else: title, value = al.split(':', 1) metadata[title.strip()] = value.strip() # Pull out the number of bytes for each column # The last numerical field is the number of bytes transmitted for each sensor: # 1 A 1 byte integer value [-128 .. 127]. # 2 A 2 byte integer value [-32768 .. 32767]. # 4 A 4 byte float value (floating point, 6-7 significant digits, # approximately 10^-38 to 10^38 dynamic range). # 8 An 8 byte double value (floating point, 15-16 significant digits, # approximately 10^-308 to 10^308 dyn. range). dtypedf = pd.read_csv( self.ascii_file, index_col=False, skiprows=data_start - 1, nrows=1, header=None, names=headers, sep=' ', skip_blank_lines=True, ) def intflag_to_dtype(intvalue): if intvalue == 1: return np.object # ints can't have NaN so use object for now elif intvalue == 2: return np.object # ints can't have NaN so use object for now elif intvalue == 4: return np.float32 elif intvalue == 8: return np.float64 else: return np.object inttypes = [ intflag_to_dtype(x) for x in dtypedf.iloc[0].astype(int).values ] dtypes = dict(zip(dtypedf.columns, inttypes)) df = pd.read_csv( self.ascii_file, index_col=False, skiprows=data_start, header=None, names=headers, dtype=dtypes, sep=' ', skip_blank_lines=True, ) return metadata, df def standardize(self, gps_prefix=None): df = self.data.copy() # Convert NMEA coordinates to decimal degrees for col in df.columns: # Ignore if the m_gps_lat and/or m_gps_lon value is the default masterdata value if col.endswith('_lat'): df[col] = df[col].map(lambda x: get_decimal_degrees(x) if x <= 9000 else np.nan) elif col.endswith('_lon'): df[col] = df[col].map(lambda x: get_decimal_degrees(x) if x < 18000 else np.nan) # Standardize 'time' to the 't' column for t in self.TIMESTAMP_SENSORS: if t in df.columns: df['t'] = pd.to_datetime(df[t], unit='s') break # Interpolate GPS coordinates if 'm_gps_lat' in df.columns and 'm_gps_lon' in df.columns: df['drv_m_gps_lat'] = df.m_gps_lat.copy() df['drv_m_gps_lon'] = df.m_gps_lon.copy() # Fill in data will nulls where value is the default masterdata value masterdatas = (df.drv_m_gps_lon >= 18000) | (df.drv_m_gps_lat > 9000) df.loc[masterdatas, 'drv_m_gps_lat'] = np.nan df.loc[masterdatas, 'drv_m_gps_lon'] = np.nan try: # Interpolate the filled in 'x' and 'y' y_interp, x_interp = interpolate_gps( masked_epoch(df.t), df.drv_m_gps_lat, df.drv_m_gps_lon ) except (ValueError, IndexError): L.warning("Raw GPS values not found!") y_interp = np.empty(df.drv_m_gps_lat.size) * np.nan x_interp = np.empty(df.drv_m_gps_lon.size) * np.nan df['y'] = y_interp df['x'] = x_interp """ ---- Option 1: Always calculate Z from pressure ---- It's really a matter of data provider preference and varies from one provider to another. That being said, typically the sci_water_pressure or m_water_pressure variables, if present in the raw data files, will typically have more non-NaN values than m_depth. For example, all MARACOOS gliders typically have both m_depth and sci_water_pressure contained in them. However, m_depth is typically heavily decimated while sci_water_pressure contains a more complete pressure record. So, while we transmit both m_depth and sci_water_pressure, I calculate depth from pressure & (interpolated) latitude and use that as my NetCDF depth variable. - Kerfoot """ # Search for a 'pressure' column for p in self.PRESSURE_SENSORS: if p in df.columns: # Convert bar to dbar here df['pressure'] = df[p].copy() * 10 # Calculate depth from pressure and latitude # Negate the results so that increasing values note increasing depths df['z'] = -z_from_p(df.pressure, df.y) break if 'z' not in df and 'pressure' not in df: # Search for a 'z' column for p in self.DEPTH_SENSORS: if p in df.columns: df['z'] = df[p].copy() # Calculate pressure from depth and latitude # Negate the results so that increasing values note increasing depth df['pressure'] = -p_from_z(df.z, df.y) break # End Option 1 """ ---- Option 2: Use raw pressure/depth data that was sent across ---- # Standardize to the 'pressure' column for p in self.PRESSURE_SENSORS: if p in df.columns: # Convert bar to dbar here df['pressure'] = df[p].copy() * 10 break # Standardize to the 'z' column for p in self.DEPTH_SENSORS: if p in df.columns: df['z'] = df[p].copy() break # Don't calculate Z from pressure if a metered depth column exists already if 'pressure' in df and 'z' not in df: # Calculate depth from pressure and latitude # Negate the results so that increasing values note increasing depths df['z'] = -z_from_p(df.pressure, df.y) if 'z' in df and 'pressure' not in df: # Calculate pressure from depth and latitude # Negate the results so that increasing values note increasing depth df['pressure'] = -p_from_z(df.z, df.y) # End Option 2 """ rename_columns = { 'm_water_vx': 'u_orig', 'm_water_vy': 'v_orig', } # These need to be standardize so we can compute salinity and density! for vname in self.TEMPERATURE_SENSORS: if vname in df.columns: rename_columns[vname] = 'temperature' break for vname in self.CONDUCTIVITY_SENSORS: if vname in df.columns: rename_columns[vname] = 'conductivity' break # Standardize columns df = df.rename(columns=rename_columns) # Compute additional columns df = self.compute(df) return df def compute(self, df): try: # Compute salinity df['salinity'] = calculate_practical_salinity( conductivity=df.conductivity.values, temperature=df.temperature.values, pressure=df.pressure.values, ) except (ValueError, AttributeError) as e: L.error("Could not compute salinity for {}: {}".format(self.ascii_file, e)) try: # Compute density df['density'] = calculate_density( temperature=df.temperature.values, pressure=df.pressure.values, salinity=df.salinity.values, latitude=df.y, longitude=df.x, ) except (ValueError, AttributeError) as e: L.error("Could not compute density for {}: {}".format(self.ascii_file, e)) return df class SlocumMerger(object): """ Merges flight and science data files into an ASCII file. Copies files matching the regex in source_directory to their own temporary directory before processing since the Rutgers supported script only takes foldesr as input Returns a list of flight/science files that were processed into ASCII files """ def __init__(self, source_directory, destination_directory, cache_directory=None, globs=None): globs = globs or ['*'] self.tmpdir = mkdtemp(prefix='gutils_convert_') self.matched_files = [] self.cache_directory = cache_directory or source_directory self.destination_directory = destination_directory self.source_directory = source_directory mf = set() for g in globs: mf.update( glob( os.path.join( source_directory, g ) ) ) def slocum_binary_sorter(x): """ Sort slocum binary files correctly, using leading zeros.leading """ 'usf-bass-2014-048-2-1.tbd -> 2014_048_00000002_000000001' x, ext = os.path.splitext(os.path.basename(x)) if ext not in ALL_EXTENSIONS: return x z = [ int(a) for a in x.split('-')[-4:] ] return '{0[0]:04d}_{0[1]:03d}_{0[2]:08d}_{0[3]:08d}'.format(z) self.matched_files = sorted(list(mf), key=slocum_binary_sorter) def __del__(self): # Remove tmpdir try: shutil.rmtree(self.tmpdir) except FileNotFoundError: pass def convert(self): # Copy to tempdir for f in self.matched_files: fname = os.path.basename(f) tmpf = os.path.join(self.tmpdir, fname) shutil.copy2(f, tmpf) safe_makedirs(self.destination_directory) # Run conversion script convert_binary_path = os.path.join( os.path.dirname(__file__), 'bin', 'convertDbds.sh' ) pargs = [ convert_binary_path, '-q', '-p', '-c', self.cache_directory ] pargs.append(self.tmpdir) pargs.append(self.destination_directory) command_output, return_code = generate_stream(pargs) # Return processed = [] output_files = command_output.read().split('\n') # iterate and every time we hit a .dat file we return the cache binary_files = [] for x in output_files: if x.startswith('Error'): L.error(x) continue if x.startswith('Skipping'): continue fname = os.path.basename(x) _, suff = os.path.splitext(fname) if suff == '.dat': ascii_file = os.path.join(self.destination_directory, fname) if os.path.isfile(ascii_file): processed.append({ 'ascii': ascii_file, 'binary': sorted(binary_files) }) L.info("Converted {} to {}".format( ','.join([ os.path.basename(x) for x in sorted(binary_files) ]), fname )) else: L.warning("{} not an output file".format(x)) binary_files = [] else: bf = os.path.join(self.source_directory, fname) if os.path.isfile(x): binary_files.append(bf) return processed
import re import string import sys import subprocess import gzip import os # Extract scenario re_filename = re.compile("^(\w+)\.(\d+)\.(\d+)\.([a-zA-Z0-9_\-\.\:\,]+)\.log\.gz$") re_notdigit = re.compile("^[0-9]") re_scenario_kv = re.compile("^([^-]*)-(.*)$") # Parsing re_scenario = re.compile("====> Scenario (.*)=(.*)$") re_timedrun = re.compile("mkdir.*timedrun") re_err = re.compile('NullPointerException|JikesRVM: WARNING: Virtual processor has ignored timer interrupt|hardware trap|-- Stack --|code: -1|OutOfMemory|ArrayIndexOutOfBoundsException|FileNotFoundException|FAILED warmup|Validation FAILED|caught alarm') re_tabulate = re.compile("============================ Tabulate Statistics ============================") re_mmtkstats = re.compile("============================ MMTk Statistics Totals ============================") re_nonwhitespace = re.compile("\S+") re_whitespace = re.compile("\s+") re_digit = re.compile("\d+") re_starting = re.compile("=====(==|) .* (S|s)tarting") re_passed = re.compile("PASSED in (\d+) msec") re_warmup = re.compile("completed warmup \d* *in (\d+) msec") re_finished = re.compile("Finished in (\S+) secs") re_998 = re.compile("_997_|_998_") # parser states class states(object): NOTHING = 0 IN_INVOCATION = 1 IN_TABULATE_STATS_HEADER = 10 IN_TABULATE_STATS_DATA = 11 IN_MMTK_STATS_HEADER = 20 IN_MMTK_STATS_DATA = 21 IN_ERROR = 30 # a "Result" is a single iteration of a benchmark invocation class Result(object): def __init__(self, scenario, value): self.scenario = scenario self.value = value def extract_scenario(scenario, entry): """ Extract scenario variables from a log filename """ entry = entry.replace(',',':'); m = re_filename.match(entry) scenario["benchmark"] = m.group(1) scenario["hfac"] = m.group(2) scenario["heap"] = m.group(3) scenario["buildstring"] = m.group(4) buildparams = scenario["buildstring"].split(".") scenario["build"] = buildparams[0] for p in buildparams[1::]: if not re_notdigit.match(p): m = re_scenario_kv.match(p) if m: scenario[m.group(1)] = m.group(2) else: scenario[p] = 1 def parse_csv(logpath, filename): """ Parse a single logfile. We assume the logfile is gzipped. """ # Results results = list() # Initialise parsing state state = states.NOTHING iteration = 0 scenario = dict() value = [] invocation_results = list() # results for this invocation (n iterations in a single invocation) legacy_mode = True legacy_invocation = 0 legacy_scenario = {} tabulate_stats_headers = list() mmtk_stats_headers = list() n = 0 # lines # Open the file for reading f = gzip.open(os.path.join(logpath, filename), "r") # Read one line at a time for l in f: n += 1 if state == states.IN_INVOCATION: # Is this line some sort of data output? if l[0] == '=': m = re_scenario.match(l) if m: legacy_mode = False scenario[m.group(1)] = m.group(2) elif re_starting.match(l): # It's the start of a new iteration, wrap up the last # if we've gathered data if len(value) > 0: # r = DataRow() if legacy_mode: if not legacy_scenario: extract_scenario(legacy_scenario, filename) scenario.update(legacy_scenario) scenario['invocation'] = legacy_invocation r = Result(scenario, value) invocation_results.append(r) iteration = iteration + 1 scenario = dict(scenario) scenario["iteration"] = iteration value = [] elif re_tabulate.match(l): state = states.IN_TABULATE_STATS_HEADER elif re_mmtkstats.match(l): state = states.IN_MMTK_STATS_HEADER else: m = re_passed.search(l) if m: # it's a PASSED result line value.append(("bmtime", m.group(1))) continue m = re_warmup.search(l) if m: # it's a warmup pass value.append(("bmtime", m.group(1))) continue m = re_finished.search(l) if m and not re_998.search(l): msec = float(m.group(1)) * 1000.0 value.append(("bmtime", str(msec))) continue # Now check for errors if re_err.search(l): state = states.IN_ERROR # Have we finished an invocation? elif re_timedrun.match(l): # Start of a new invocation, finalise this one (wrap up the # last iteration if necessary) if len(value) > 0: if legacy_mode: if not legacy_scenario: extract_scenario(legacy_scenario, filename) scenario.update(legacy_scenario) scenario['invocation'] = legacy_invocation r = Result(scenario, value) invocation_results.append(r) results.extend(invocation_results) invocation_results = list() scenario = dict() value = [] iteration = 0 scenario['iteration'] = iteration legacy_invocation += 1 # Or is this line an error? elif re_err.search(l): state = states.IN_ERROR elif state == states.IN_ERROR: # skip until next re_timedrun if re_timedrun.match(l): invocation_results = list() scenario = dict() value = [] iteration = 0 scenario['iteration'] = iteration legacy_invocation += 1 # Make sure the invocation count is right state = states.IN_INVOCATION elif state == states.IN_TABULATE_STATS_HEADER: # next line should be a list of headers; check it's valid if re_nonwhitespace.match(l): tabulate_stats_headers = map(string.strip, re_whitespace.split(l)) state = states.IN_TABULATE_STATS_DATA else: # not valid state = states.IN_ERROR elif state == states.IN_TABULATE_STATS_DATA: # next line should be a list of data if re_digit.match(l): vals = re_whitespace.split(l) if len(vals) != len(tabulate_stats_headers): state = states.IN_ERROR continue for k, v in zip(tabulate_stats_headers, vals): if k == '': continue value.append((k, v)) state = states.IN_INVOCATION else: state = states.IN_ERROR elif state == states.IN_MMTK_STATS_HEADER: # next line should be a list of headers; check it's valid if re_nonwhitespace.match(l): tabulate_stats_headers = map(string.strip, re_whitespace.split(l)) state = states.IN_MMTK_STATS_DATA else: # not valid state = states.IN_ERROR elif state == states.IN_MMTK_STATS_DATA: # next line should be a list of data if re_digit.match(l): vals = re_whitespace.split(l) if len(vals) != len(tabulate_stats_headers): state = states.IN_ERROR continue totaltime = 0.0 for k, v in zip(tabulate_stats_headers, vals): if k == '': continue if k == 'time.mu' or k == 'time.gc': totaltime += float(v) value.append((k,v)) value.append(("time", str(totaltime))) state = states.IN_INVOCATION else: state = states.IN_ERROR elif state == states.NOTHING: # Find an invocation if re_timedrun.match(l): # Found an invocation state = states.IN_INVOCATION scenario['iteration'] = iteration # end of state switch # end of line loop # Write the last set of results, if we didn't finish with an error if state == states.IN_INVOCATION: if len(value) > 0: if legacy_mode: if not legacy_scenario: extract_scenario(legacy_scenario, filename) scenario.update(legacy_scenario) scenario['invocation'] = legacy_invocation r = Result(scenario, value) invocation_results.append(r) results.extend(invocation_results) f.close() return results def tabulate_log_folder(logpath, outfile, write_status=None): files = [f for f in os.listdir(logpath) if f[-7:] == '.log.gz'] if write_status: progress = 0 pid = str(os.getpid()) status_path = os.path.join(write_status, pid + ".status") status_file = open(status_path, 'w') status_file.write("%d\r\n" % (len(files)+1)) status_file.flush() results = [] for filename in files: r = parse_csv(logpath, filename) results.extend(r) if write_status: progress += 1 status_file.write("%d\r\n" % progress) status_file.flush() # Sort the scenario headers scenario_headers = set() for r in results: for k in r.scenario.keys(): if k not in scenario_headers: scenario_headers.add(k) scenario_headers_sorted = list(scenario_headers) scenario_headers_sorted.sort() # Open the output file csv_file = open(outfile, 'w') gzip_process = subprocess.Popen(['gzip'], stdin=subprocess.PIPE, stdout=csv_file, bufsize=-1) csv_out = gzip_process.stdin # Print the header row for k in scenario_headers_sorted: csv_out.write(k) csv_out.write(",") csv_out.write("key,value\n") # Print each result (note: one Result object is more than one CSV line) for r in results: scenario_str = "" for k in scenario_headers_sorted: if k in r.scenario: scenario_str += str(r.scenario[k]) else: scenario_str += "null" scenario_str += "," for key, val in r.value: csv_out.write(scenario_str) csv_out.write(key + "," + val) csv_out.write("\n") csv_out.close() gzip_process.wait() csv_file.close() # Now signal that we're finished if write_status: progress += 1 status_file.write("%d\r\n" % progress) status_file.close() if __name__ == "__main__": if len(sys.argv) < 3 or len(sys.argv) > 4: print "Usage: python LogParser.py log-folder csv-file [status-dir]" sys.exit(1) print "Parsing %s to %s (pid %d)" % (sys.argv[1], sys.argv[2], os.getpid()) if len(sys.argv) == 3: tabulate_log_folder(sys.argv[1], sys.argv[2]) else: tabulate_log_folder(sys.argv[1], sys.argv[2], sys.argv[3])
import{d as x,s as _,r as p,o as b,b as v,X as i,a5 as e,w as d,W as h,a9 as a,c as V,bc as f}from"./vendor.dce3d09c.js";const y=a("Option 1"),E=a("Option 2"),B=a("Option 1"),z=a("Option 2"),$=a("Option 1"),A=a("Option 2"),O=a("Option 1"),U=a("Option 2"),k=x({setup(g){const s=_("1"),r=_("1"),n=_("1");return(m,l)=>{const t=p("fz-radio");return b(),v(h,null,[i("div",null,[e(t,{modelValue:s.value,"onUpdate:modelValue":l[0]||(l[0]=o=>s.value=o),label:"1",size:"large"},{default:d(()=>[y]),_:1},8,["modelValue"]),e(t,{modelValue:s.value,"onUpdate:modelValue":l[1]||(l[1]=o=>s.value=o),label:"2",size:"large"},{default:d(()=>[E]),_:1},8,["modelValue"])]),i("div",null,[e(t,{modelValue:r.value,"onUpdate:modelValue":l[2]||(l[2]=o=>r.value=o),label:"1"},{default:d(()=>[B]),_:1},8,["modelValue"]),e(t,{modelValue:r.value,"onUpdate:modelValue":l[3]||(l[3]=o=>r.value=o),label:"2"},{default:d(()=>[z]),_:1},8,["modelValue"])]),i("div",null,[e(t,{modelValue:n.value,"onUpdate:modelValue":l[4]||(l[4]=o=>n.value=o),label:"1",size:"small"},{default:d(()=>[$]),_:1},8,["modelValue"]),e(t,{modelValue:n.value,"onUpdate:modelValue":l[5]||(l[5]=o=>n.value=o),label:"2",size:"small"},{default:d(()=>[A]),_:1},8,["modelValue"])]),i("div",null,[e(t,{modelValue:n.value,"onUpdate:modelValue":l[6]||(l[6]=o=>n.value=o),label:"1",size:"small",disabled:""},{default:d(()=>[O]),_:1},8,["modelValue"]),e(t,{modelValue:n.value,"onUpdate:modelValue":l[7]||(l[7]=o=>n.value=o),label:"2",size:"small",disabled:""},{default:d(()=>[U]),_:1},8,["modelValue"])])],64)}}}),w=a("Option A"),N=a("Option B"),C=a("Option C"),Y=x({setup(g){const s=_(3);return(r,n)=>{const m=p("fz-radio"),l=p("fz-radio-group");return b(),V(l,{modelValue:s.value,"onUpdate:modelValue":n[0]||(n[0]=t=>s.value=t)},{default:d(()=>[e(m,{label:3},{default:d(()=>[w]),_:1}),e(m,{label:6},{default:d(()=>[N]),_:1}),e(m,{label:9},{default:d(()=>[C]),_:1})]),_:1},8,["modelValue"])}}}),F={style:{"margin-top":"20px"}},R={style:{"margin-top":"20px"}},W=x({setup(g){const s=_("New York"),r=_("New York"),n=_("New York");return(m,l)=>{const t=p("fz-radio-button"),o=p("fz-radio-group");return b(),v(h,null,[i("div",null,[e(o,{modelValue:s.value,"onUpdate:modelValue":l[0]||(l[0]=c=>s.value=c),size:"large"},{default:d(()=>[e(t,{label:"New York"}),e(t,{label:"Washington"}),e(t,{label:"Los Angeles"}),e(t,{label:"Chicago"})]),_:1},8,["modelValue"])]),i("div",F,[e(o,{modelValue:r.value,"onUpdate:modelValue":l[1]||(l[1]=c=>r.value=c)},{default:d(()=>[e(t,{label:"New York"}),e(t,{label:"Washington"}),e(t,{label:"Los Angeles"}),e(t,{label:"Chicago"})]),_:1},8,["modelValue"])]),i("div",R,[e(o,{modelValue:n.value,"onUpdate:modelValue":l[2]||(l[2]=c=>n.value=c),size:"small"},{default:d(()=>[e(t,{label:"New York"}),e(t,{label:"Washington",disabled:""}),e(t,{label:"Los Angeles"}),e(t,{label:"Chicago"})]),_:1},8,["modelValue"])])],64)}}}),D=a("Option A"),L=a("Option B"),j={style:{"margin-top":"20px"}},S=a("Option A"),T=a("Option B"),X={style:{"margin-top":"20px"}},q=a("Option A"),G=a("Option B"),H={style:{"margin-top":"20px"}},I=a("Option A"),J=a("Option B"),K=x({setup(g){const s=_("1"),r=_("1"),n=_("1"),m=_("1");return(l,t)=>{const o=p("fz-radio"),c=p("fz-radio-group");return b(),v(h,null,[i("div",null,[e(o,{modelValue:s.value,"onUpdate:modelValue":t[0]||(t[0]=u=>s.value=u),label:"1",size:"large",border:""},{default:d(()=>[D]),_:1},8,["modelValue"]),e(o,{modelValue:s.value,"onUpdate:modelValue":t[1]||(t[1]=u=>s.value=u),label:"2",size:"large",border:""},{default:d(()=>[L]),_:1},8,["modelValue"])]),i("div",j,[e(o,{modelValue:r.value,"onUpdate:modelValue":t[2]||(t[2]=u=>r.value=u),label:"1",border:""},{default:d(()=>[S]),_:1},8,["modelValue"]),e(o,{modelValue:r.value,"onUpdate:modelValue":t[3]||(t[3]=u=>r.value=u),label:"2",border:""},{default:d(()=>[T]),_:1},8,["modelValue"])]),i("div",X,[e(c,{modelValue:n.value,"onUpdate:modelValue":t[4]||(t[4]=u=>n.value=u),size:"small"},{default:d(()=>[e(o,{label:"1",border:""},{default:d(()=>[q]),_:1}),e(o,{label:"2",border:"",disabled:""},{default:d(()=>[G]),_:1})]),_:1},8,["modelValue"])]),i("div",H,[e(c,{modelValue:m.value,"onUpdate:modelValue":t[5]||(t[5]=u=>m.value=u),size:"small",disabled:""},{default:d(()=>[e(o,{label:"1",border:""},{default:d(()=>[I]),_:1}),e(o,{label:"2",border:""},{default:d(()=>[J]),_:1})]),_:1},8,["modelValue"])])],64)}}}),M={class:"markdown-body"},P=i("h1",{id:"%E5%8D%95%E9%80%89%E6%A1%86",tabindex:"-1"},"\u5355\u9009\u6846",-1),Q=i("p",null,"\u5728\u4E00\u7EC4\u5907\u9009\u9879\u4E2D\u8FDB\u884C\u5355\u9009",-1),Z=i("h2",{id:"%E5%9F%BA%E7%A1%80%E7%94%A8%E6%B3%95",tabindex:"-1"},"\u57FA\u7840\u7528\u6CD5",-1),ee=i("h2",{id:"%E5%8D%95%E9%80%89%E6%A1%86%E7%BB%84",tabindex:"-1"},"\u5355\u9009\u6846\u7EC4",-1),te=i("h2",{id:"%E6%8C%89%E9%92%AE%E6%A0%B7%E5%BC%8F",tabindex:"-1"},"\u6309\u94AE\u6837\u5F0F",-1),le=i("h2",{id:"%E5%B8%A6%E8%BE%B9%E6%A1%86",tabindex:"-1"},"\u5E26\u8FB9\u6846",-1),de=f('<h2 id="%E5%B1%9E%E6%80%A7" tabindex="-1">\u5C5E\u6027</h2><div class="doc-table"><table><thead><tr><th style="text-align:center;">\u53C2\u6570</th><th style="text-align:center;">\u8BF4\u660E</th><th style="text-align:center;">\u7C7B\u578B</th><th style="text-align:center;">\u53EF\u9009\u503C</th><th style="text-align:center;">\u9ED8\u8BA4\u503C</th><th style="text-align:center;">\u662F\u5426\u5FC5\u586B</th></tr></thead><tbody><tr><td style="text-align:center;"><code>arg1</code></td><td style="text-align:center;">\u7B2C\u4E00\u4E2A\u53C2\u6570</td><td style="text-align:center;">string</td><td style="text-align:center;">-</td><td style="text-align:center;"><code>default</code></td><td style="text-align:center;">\u5426</td></tr><tr><td style="text-align:center;"><code>arg2</code></td><td style="text-align:center;">\u7B2C\u4E8C\u4E2A\u53C2\u6570</td><td style="text-align:center;">string</td><td style="text-align:center;">-</td><td style="text-align:center;"><code>default</code></td><td style="text-align:center;">\u5426</td></tr></tbody></table></div><h2 id="%E4%BA%8B%E4%BB%B6" tabindex="-1">\u4E8B\u4EF6</h2><div class="doc-table"><table><thead><tr><th style="text-align:center;">\u4E8B\u4EF6\u540D</th><th style="text-align:center;">\u8BF4\u660E</th><th style="text-align:center;">\u53C2\u6570\u5217\u8868</th><th style="text-align:center;">\u53C2\u6570\u8BF4\u660E</th></tr></thead><tbody><tr><td style="text-align:center;"><code>click</code></td><td style="text-align:center;">\u70B9\u51FB\u4E8B\u4EF6</td><td style="text-align:center;">$event</td><td style="text-align:center;">\u539F\u751F\u7684 dom event</td></tr><tr><td style="text-align:center;"><code>customEvent</code></td><td style="text-align:center;">\u81EA\u5B9A\u4E49\u4E8B\u4EF6</td><td style="text-align:center;">[a, b, c]</td><td style="text-align:center;">a\uFF1A\u53C2\u6570\u4E00\uFF1Bb\uFF1A\u53C2\u6570\u4E8C\uFF1Bc\uFF1A\u53C2\u6570\u4E09</td></tr></tbody></table></div><h2 id="%E6%96%B9%E6%B3%95" tabindex="-1">\u65B9\u6CD5</h2><div class="doc-table"><table><thead><tr><th style="text-align:center;">\u65B9\u6CD5\u540D</th><th style="text-align:center;">\u8BF4\u660E</th><th style="text-align:center;">\u53C2\u6570\u5217\u8868</th><th style="text-align:center;">\u53C2\u6570\u8BF4\u660E</th></tr></thead><tbody><tr><td style="text-align:center;"><code>update</code></td><td style="text-align:center;">\u624B\u52A8\u66F4\u65B0</td><td style="text-align:center;">-</td><td style="text-align:center;">-</td></tr></tbody></table></div><h2 id="%E6%8F%92%E6%A7%BD" tabindex="-1">\u63D2\u69FD</h2><div class="doc-table"><table><thead><tr><th style="text-align:center;">\u63D2\u69FD\u540D</th><th style="text-align:center;">\u8BF4\u660E</th></tr></thead><tbody><tr><td style="text-align:center;"><code>default</code></td><td style="text-align:center;">\u81EA\u5B9A\u4E49\u9ED8\u8BA4\u5185\u5BB9</td></tr></tbody></table></div>',8),ae={setup(g,{expose:s}){return s({frontmatter:{}}),(n,m)=>{const l=p("demo-preview");return b(),v("div",M,[P,Q,Z,e(l,{"comp-name":"Radio","demo-name":"demo"},{default:d(()=>[e(k)]),_:1}),ee,e(l,{"comp-name":"Radio","demo-name":"demo2"},{default:d(()=>[e(Y)]),_:1}),te,e(l,{"comp-name":"Radio","demo-name":"demo3"},{default:d(()=>[e(W)]),_:1}),le,e(l,{"comp-name":"Radio","demo-name":"demo4"},{default:d(()=>[e(K)]),_:1}),de])}}};export{ae as default};
from pydavid import pydavid from pydavid import valid_valuesi
export const errorLoading = err => console.error('Dynamic page loading failed', err) export const loadRoute = module => module.default
const escape = require('shell-quote').quote /** * Need this to fix a bug where we can't commit this: * * `pages/examples/[example].tsx`. * * because of the square brackets `[` and `]`. * * <https://github.com/okonet/lint-staged/issues/676#issuecomment-574764713> * * NOTE: * * We can remove this entire file if/when we upgrade to Prettier 2+ where this * is no longer necessary according to the `lint-staged` issue shown above. * * Currently, the same configuration without the escaping of the filename * still exists in `package.json` but this takes precedence over that. * * Once this file is removed, `package.json` configuration will be used. */ module.exports = { '*.{ts,tsx,js,jsx,json,css,md}': filenames => [ ...filenames.map(filename => `prettier --write "${escape([filename])}"`), ...filenames.map(filename => `git add "${filename}"`), ], '*.{ts,tsx,js,jsx,json,css,md}': ['eslint --fix'], }
"""Quantities tracked during training.""" from cockpit.quantities.alpha import Alpha from cockpit.quantities.cabs import CABS from cockpit.quantities.distance import Distance from cockpit.quantities.early_stopping import EarlyStopping from cockpit.quantities.grad_hist import GradHist1d, GradHist2d from cockpit.quantities.grad_norm import GradNorm from cockpit.quantities.hess_max_ev import HessMaxEV from cockpit.quantities.hess_trace import HessTrace from cockpit.quantities.inner_test import InnerTest from cockpit.quantities.loss import Loss from cockpit.quantities.mean_gsnr import MeanGSNR from cockpit.quantities.norm_test import NormTest from cockpit.quantities.ortho_test import OrthoTest from cockpit.quantities.parameters import Parameters from cockpit.quantities.tic import TICDiag, TICTrace from cockpit.quantities.time import Time from cockpit.quantities.update_size import UpdateSize __all__ = [ "Loss", "Parameters", "Distance", "UpdateSize", "GradNorm", "Time", "Alpha", "CABS", "EarlyStopping", "GradHist1d", "GradHist2d", "NormTest", "InnerTest", "OrthoTest", "HessMaxEV", "HessTrace", "TICDiag", "TICTrace", "MeanGSNR", ]
// DEV: This is actually testing our DNS and not a server but meh. var expect = require('chai').expect; var httpUtils = require('../utils/http'); describe('twolfsn.com (http)', function () { httpUtils.save({ url: 'http://twolfsn.com', followRedirect: false, expectedStatusCode: 301 }); it('redirects to twolfson.com', function () { expect(this.res.headers).to.have.property('location', 'http://twolfson.com/'); }); }); // TODO: This is non-functional =( describe.skip('twolfsn.com (https)', function () { httpUtils.save({ url: 'https://twolfsn.com', followRedirect: false, expectedStatusCode: 301 }); it('redirects to twolfson.com', function () { expect(this.res.headers).to.have.property('location', 'https://twolfson.com/'); }); });
import svelte from "rollup-plugin-svelte"; import resolve from "rollup-plugin-node-resolve"; import commonjs from "rollup-plugin-commonjs"; import livereload from "rollup-plugin-livereload"; import postcss from 'rollup-plugin-postcss'; import { terser } from "rollup-plugin-terser"; const svelteConfig = require("./svelte.config"); const production = !process.env.ROLLUP_WATCH; export default { input: "src/main.js", output: { sourcemap: true, format: "iife", name: "app", file: "public/build/bundle.js", }, plugins: [ svelte({ // enable run-time checks when not in production dev: !production, ...svelteConfig, }), // If you have external dependencies installed from // npm, you'll most likely need these plugins. In // some cases you'll need additional configuration  // consult the documentation for details: // https://github.com/rollup/rollup-plugin-commonjs resolve({ browser: true, dedupe: (importee) => importee === "svelte" || importee.startsWith("svelte/"), }), commonjs(), postcss({ extract: true, minimize: true, use: [ [ "sass", { includePaths: ["./theme", "./node_modules"], }, ], ], }), // In dev mode, call `npm run start` once // the bundle has been generated !production && serve(), // Watch the `public` directory and refresh the // browser on changes when not in production !production && livereload("public"), // If we're building for production (npm run build // instead of npm run dev), minify production && terser(), ], watch: { clearScreen: false, }, }; function serve() { let started = false; return { writeBundle() { if (!started) { started = true; require("child_process").spawn("npm", ["run", "start", "--", "--dev"], { stdio: ["ignore", "inherit", "inherit"], shell: true, }); } }, }; }
"""These are utilities designed for carefully handling communication between processes while multithreading. The code for ``pool_imap_unordered`` is copied nearly wholesale from GrantJ's `Stack Overflow answer here <https://stackoverflow.com/questions/5318936/python-multiprocessing-pool-lazy-iteration?noredirect=1&lq=1>`_. It allows for a lazy imap over an iterable and the return of very large objects """ from multiprocessing import Process, Queue, cpu_count try: from Queue import Full as QueueFull from Queue import Empty as QueueEmpty except ImportError: # python3 from queue import Full as QueueFull from queue import Empty as QueueEmpty __all__ = ["pool_imap_unordered"] def worker(func, recvq, sendq): for args in iter(recvq.get, None): # The args are training_data, scoring_data, var_idx # Thus, we want to return the var_idx and then # send those args to the abstract runner. result = (args[-1], func(*args)) sendq.put(result) def pool_imap_unordered(func, iterable, procs=cpu_count()): """Lazily imaps in an unordered manner over an iterable in parallel as a generator :Author: Grant Jenks <https://stackoverflow.com/users/232571/grantj> :param func: function to perform on each iterable :param iterable: iterable which has items to map over :param procs: number of workers in the pool. Defaults to the cpu count :yields: the results of the mapping """ # Create queues for sending/receiving items from iterable. sendq = Queue(procs) recvq = Queue() # Start worker processes. for rpt in range(procs): Process(target=worker, args=(func, sendq, recvq)).start() # Iterate iterable and communicate with worker processes. send_len = 0 recv_len = 0 itr = iter(iterable) try: value = next(itr) while True: try: sendq.put(value, True, 0.1) send_len += 1 value = next(itr) except QueueFull: while True: try: result = recvq.get(False) recv_len += 1 yield result except QueueEmpty: break except StopIteration: pass # Collect all remaining results. while recv_len < send_len: result = recvq.get() recv_len += 1 yield result # Terminate worker processes. for rpt in range(procs): sendq.put(None)
import merge from 'lodash/merge'; import VueApollo from 'vue-apollo'; import { within } from '@testing-library/dom'; import { createLocalVue, mount, shallowMount } from '@vue/test-utils'; import { createMockClient } from 'mock-apollo-client'; import { GlLoadingIcon } from '@gitlab/ui'; import waitForPromises from 'jest/helpers/wait_for_promises'; import DastSiteValidation from 'ee/dast_site_profiles_form/components/dast_site_validation.vue'; import dastSiteValidationCreateMutation from 'ee/dast_site_profiles_form/graphql/dast_site_validation_create.mutation.graphql'; import dastSiteValidationQuery from 'ee/dast_site_profiles_form/graphql/dast_site_validation.query.graphql'; import * as responses from 'ee_jest/dast_site_profiles_form/mock_data/apollo_mock'; import download from '~/lib/utils/downloader'; jest.mock('~/lib/utils/downloader'); const localVue = createLocalVue(); localVue.use(VueApollo); const fullPath = 'group/project'; const targetUrl = 'https://example.com/'; const token = 'validation-token-123'; const defaultProps = { fullPath, targetUrl, token, }; const defaultRequestHandlers = { dastSiteValidation: jest.fn().mockResolvedValue(responses.dastSiteValidation()), dastSiteValidationCreate: jest.fn().mockResolvedValue(responses.dastSiteValidationCreate()), }; describe('DastSiteValidation', () => { let wrapper; let apolloProvider; let requestHandlers; const mockClientFactory = handlers => { const mockClient = createMockClient(); requestHandlers = { ...defaultRequestHandlers, ...handlers, }; mockClient.setRequestHandler(dastSiteValidationQuery, requestHandlers.dastSiteValidation); mockClient.setRequestHandler( dastSiteValidationCreateMutation, requestHandlers.dastSiteValidationCreate, ); return mockClient; }; const respondWith = handlers => { apolloProvider.defaultClient = mockClientFactory(handlers); }; const componentFactory = (mountFn = shallowMount) => options => { apolloProvider = new VueApollo({ defaultClient: mockClientFactory(), }); wrapper = mountFn( DastSiteValidation, merge( {}, { propsData: defaultProps, }, options, { localVue, apolloProvider, }, ), ); }; const createComponent = componentFactory(); const createFullComponent = componentFactory(mount); const withinComponent = () => within(wrapper.element); const findDownloadButton = () => wrapper.find('[data-testid="download-dast-text-file-validation-button"]'); const findValidateButton = () => wrapper.find('[data-testid="validate-dast-site-button"]'); const findLoadingIcon = () => wrapper.find(GlLoadingIcon); const findErrorMessage = () => withinComponent().queryByText( /validation failed, please make sure that you follow the steps above with the choosen method./i, ); afterEach(() => { wrapper.destroy(); }); describe('rendering', () => { beforeEach(() => { createFullComponent(); }); it('renders properly', () => { expect(wrapper.html()).not.toBe(''); }); it('renders a download button containing the token', () => { const downloadButton = withinComponent().getByRole('button', { name: 'Download validation text file', }); expect(downloadButton).not.toBeNull(); }); it('renders an input group with the target URL prepended', () => { const inputGroup = withinComponent().getByRole('group', { name: 'Step 3 - Confirm text file location and validate', }); expect(inputGroup).not.toBeNull(); expect(inputGroup.textContent).toContain(targetUrl); }); }); describe('text file validation', () => { beforeEach(() => { createComponent(); }); it('clicking on the download button triggers a download of a text file containing the token', () => { findDownloadButton().vm.$emit('click'); expect(download).toHaveBeenCalledWith({ fileName: `GitLab-DAST-Site-Validation-${token}.txt`, fileData: btoa(token), }); }); }); describe('validation', () => { beforeEach(() => { createComponent(); }); describe('success', () => { beforeEach(() => { findValidateButton().vm.$emit('click'); }); it('while validating, shows a loading state', () => { expect(findLoadingIcon().exists()).toBe(true); expect(wrapper.text()).toContain('Validating...'); }); it('on success, emits success event', async () => { await waitForPromises(); expect(wrapper.emitted('success')).toHaveLength(1); }); }); describe.each` errorKind | errorResponse ${'top level error'} | ${() => Promise.reject(new Error('GraphQL Network Error'))} ${'errors as data'} | ${() => Promise.resolve(responses.dastSiteValidationCreate(['error#1', 'error#2']))} `('$errorKind', ({ errorResponse }) => { beforeEach(() => { respondWith({ dastSiteValidationCreate: errorResponse, }); }); it('on error, shows error state', async () => { expect(findErrorMessage()).toBe(null); findValidateButton().vm.$emit('click'); await waitForPromises(); expect(findErrorMessage()).not.toBe(null); }); }); }); });
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.4.4.5_A1.1_T1; * @section: 15.4.4.5; * @assertion: If length is zero, return the empty string; * @description: Checking this use new Array() and []; */ //CHECK#1 var x = new Array(); if (x.join() !== "") { $ERROR('#1: x = new Array(); x.join() === "". Actual: ' + (x.join())); } //CHECK#2 x = []; x[0] = 1; x.length = 0; if (x.join() !== "") { $ERROR('#2: x = []; x[0] = 1; x.length = 0; x.join() === "". Actual: ' + (x.join())); }
const bcrypt = require('bcryptjs'); const Users = require('../users/users-model'); module.exports = function restricted(req, res, next) { const { username, password } = req.headers; if (username && password) { Users.findBy({ username }) .first() .then(user => { if (user && bcrypt.compareSync(password, user.password)) { res.status(200).json({ message: `Welcome ${user.username}!` }); } else { res.status(401).json({ message: 'You Shall Not Pass!!!' }); } }) .catch(error => { res.status(500).json(error); }); } else { res.status(404).json({ message: 'Please provide valid credentials' }) } }
import discord from discord.ext import commands import random import requests import json import os import keep_alive from gifs import Gif_fetcher
export default class Validate { static Validate = null; x = null; constructor() { this.x = { message: "", code: "", data: "" }; } setStatusIncorrect(err) { this.setMessage(err); this.setCode(400); return { code: this.x.code, message: this.x.message } } setStatusCorrectLong(message = "Operación Correcta", data = "", code = 201) { this.setMessage(message); this.setCode(code); this.setData(data); return { message: this.x.message, data: this.x.data }; } setStatusCorrectShort(message = "Operación Correcta") { this.setMessage(message); return { message: this.x.message }; } setMessage(err) { this.x.message = err; } setCode(code) { this.x.code = code; } setData(dat) { this.x.data = dat; } }
const fs = require('fs'); const path = require('path'); const validator = require('xsd-schema-validator'); const chalk = require('chalk'); const glob = require('glob-promise'); const xml2js = require('xml2js-es6-promise'); const _ = require('lodash'); const cliprogress = require('cli-progress'); const readdir = require('recursive-readdir'); const moment = require('moment'); const { timeout, TimeoutError } = require('promise-timeout'); const PromisePool = require('es6-promise-pool'); const yargs = require('yargs') const { log } = console; let options = { projectpath: 'cartridges/app_project/cartridge', sfrapath: 'exports/storefront-reference-architecture/cartridges/app_storefront_base/cartridge', timeout: 5000 }; async function xsdfy () { let files = await findXmlFiles(); let xsdmap = buildXsdMapping(); for (let j = 0; j < files.length; j++) { let xml = files[j]; let xmllocal = path.relative(process.cwd(), xml); let xmlcontent = fs.readFileSync(xml, 'UTF-8'); let ns = getNamespace(xmlcontent); let schemaLocation = getSchemaLocation(xmlcontent); if (schemaLocation) { log(chalk.green(`File ${xmllocal} already mapped to ${schemaLocation}`)); } else { let xsdfile = xsdmap.get(ns); if (xsdfile) { let xsdrelative = path.relative(xml, xsdfile); log(chalk.yellow(`Adding xsd to ${xml} -> ${xsdrelative}`)); xmlcontent = xmlcontent.replace(`${ns}"`, `${ns}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="${ns} ${xsdrelative}"`); fs.writeFileSync(xml, xmlcontent); } else { log(chalk.yellow(`Unmapped: ${xml}`)); } } } } async function validate (failsonerror) { let files = await findXmlFiles(); let xsdmap = buildXsdMapping(); let results = []; let message = `Validating ${files.length} xml files using sfcc schemas`; const progress = new cliprogress.Bar({ format: `${chalk.green(message)} [${chalk.cyan('{bar}')}] {percentage}% | {value}/{total}` }, cliprogress.Presets.rect); progress.start(files.length, 0); let count = 0; let promisecount = 0; let pool = new PromisePool(() => { if (promisecount < files.length) { let xml = files[promisecount]; promisecount++ return new Promise(async (resolve) => { let xmlcontent = fs.readFileSync(xml, 'UTF-8'); let filename = path.basename(xml); progress.update(++count); let ns = getNamespace(xmlcontent); if (!ns) { chalk.red(`Namespace not found for ${filename}`); } let xsd = xsdmap.get(ns); if (!xsd) { if (ns !== 'http://www.demandware.com/xml/impex/accessrole/2007-09-05') { // exclude known missing ns log(chalk.yellow(`No xsd found for namespace ${ns}`)); } resolve(); } else { let res = {}; try { // console.log(chalk.yellow(`Applying timeout to ${xml}`)); res = await timeout(validateXml(xml, xsd), options.timeout); } catch (err) { if (err instanceof TimeoutError) { // console.error(`Timeout validating ${xml}`); res = { xml: xml, valid: false, processerror: 'true', messages: [`Validation timeout after ${options.timeout}ms`] }; } } // console.log(chalk.green(`Done with ${xml}`)); results.push(res); resolve(); } }) } return null; }, 20); await pool.start(); progress.stop(); let successcount = results.filter(i => i.valid).length; let errorcount = results.filter(i => !i.valid && !i.processerror).length; let notvalidated = results.filter(i => i.processerror).length; if (errorcount > 0) { log(chalk`Validated ${results.length} files: {green ${successcount} valid} and {red ${errorcount} with errors}\n`); } else { log(chalk`Validated ${results.length} files: {green all good} 🍺\n`); } if (notvalidated > 0) { log(chalk.yellow(`${notvalidated} files cannot be validated (environment problems or timeout)\n`)); } results.forEach((result) => { if (!result.valid) { log(chalk.redBright(`File ${result.xml} invalid:`)); result.messages.forEach(i => { let msg = i; if (msg && msg.indexOf && msg.indexOf('cvc-complex-type') > -1 && msg.indexOf(': ') > -1) { msg = msg.substr(msg.indexOf(': ') + 2); } log(chalk.redBright(`● ${msg}`)); }); if (result.messages.length === 0) { log(chalk.redBright(`● ${JSON.stringify(result)}`)); } log('\n'); } }); if (failsonerror && errorcount > 0) { log(chalk.redBright(`${errorcount} xml files failed validation\n`)); process.exit(2); // fail build; throw new Error(`${errorcount} xml files failed validation`); } } async function findXmlFiles () { return glob(`${path.join(process.cwd(), 'sites')}/**/*.xml`); } function buildXsdMapping () { let xsdfolder = path.join(process.cwd(), 'node_modules/sfcc-schemas/xsd/'); let xsdmap = new Map(); fs.readdirSync(xsdfolder).forEach((file) => { let fullpath = path.join(xsdfolder, file); let ns = getNamespace(fs.readFileSync(fullpath, 'utf-8')); if (ns) { xsdmap.set(ns, fullpath); } else { chalk.red(`Namespace not found in xsd ${fullpath}`); } }); return xsdmap; } function getNamespace (xmlcontent) { let match = xmlcontent.match(new RegExp('xmlns(?::loc)? *= *"([a-z0-9/:.-]*)"')); if (match) { return match[1]; } return null; } function getSchemaLocation (xmlcontent) { let match = xmlcontent.match(/xsi:schemaLocation="(.*)"/); // let match = xmlcontent.match(new RegExp('xsi:schemaLocation="([.|\n]*)"')); if (match) { return match[1]; } return null; } async function validateXml (xml, xsd) { return new Promise((resolve) => { // process.stdout.write('.'); validator.validateXML({ file: xml }, xsd, (err, result) => { if (err) { if (result) { if (!result.messages || result.messages.length === 0) { result.messages.push(err); result.processerror = true; } } else { log(chalk.red(err)); return {}; } } result.xml = xml; result.xsd = xsd; resolve(result); }); }); } async function parseMeta (source) { let exts = await xml2js(fs.readFileSync(source, 'utf-8'), { trim: true, normalizeTags: true, mergeAttrs: true, explicitArray: false, attrNameProcessors: [function (name) { return _.replace(name, /-/g, ''); }], tagNameProcessors: [function (name) { return _.replace(name, /-/g, ''); }] }); if (exts.metadata && exts.metadata.typeextension) { ensureArray(exts.metadata, 'typeextension'); exts = exts.metadata.typeextension.map(i => cleanupEntry(i)).filter(i => i.attributedefinitions); } else if (exts.metadata && exts.metadata.customtype) { ensureArray(exts.metadata, 'customtype'); exts = exts.metadata.customtype.map(i => cleanupEntry(i)); } ensureArray(exts.urlrules, 'pipelinealiases'); cleanI18n(exts); fs.writeFileSync(path.join(process.cwd(), 'output/config/', `${path.basename(source)}.json`), JSON.stringify(exts, null, 2)); // date parsing utils exts.moment = moment; return exts; } function ensureArray (object, field) { if (object && object[field] && !object[field].length) { object[field] = [object[field]]; } } function cleanupEntry (i) { let res = i; // normalize if (res.customattributedefinitions) { res.attributedefinitions = res.customattributedefinitions; delete res.customattributedefinitions; } delete res.systemattributedefinitions; // cleanup single attributes without array if (res.attributedefinitions && res.attributedefinitions.attributedefinition && res.attributedefinitions.attributedefinition.attributeid) { res.attributedefinitions.attributedefinition = [res.attributedefinitions.attributedefinition]; } return res; } function cleanI18n (obj) { Object .entries(obj) .forEach(entry => { let [k, v] = entry; if (v !== null && typeof v === 'object' && !v.escape) { if (v._ && v['xml:lang'] && Object.keys(v).length === 2) { obj[k] = v._; // log(`-> replaced ${obj[k]}`); } cleanI18n(v); } }); } async function entrypoints () { const regex = /server\.(get|post)\(['" \n]*([a-zA-Z0-9]*)['" ]*/gm; let inputpath = path.join(process.cwd(), 'output/code'); if (!fs.existsSync(inputpath)) { return; } let files = await readdir(inputpath, [(i, stats) => !stats.isDirectory() && path.basename(path.dirname(i)) !== 'controllers' && path.extname(i) !== 'js']); let mapping = {}; for (let j = 0; j < files.length; j++) { let file = files[j]; let controllername = path.basename(file); controllername = controllername.substr(0, controllername.lastIndexOf('.')); let dirname = path.basename(path.dirname(path.dirname(path.dirname(file)))); let filecontent = fs.readFileSync(file); let m; // eslint-disable-next-line no-cond-assign while ((m = regex.exec(filecontent)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } let pipeline = `${controllername}-${m[2]}`; let method = _.upperCase(m[1]); if (mapping[pipeline]) { mapping[pipeline].cartridges.push(dirname); } else { mapping[pipeline] = { pipeline: pipeline, method: method, controller: controllername, cartridges: [dirname] }; } } } return mapping; } async function listcontrollers () { let projectbase = path.join(process.cwd(), options.projectpath); if (!fs.existsSync(projectbase)) { log(`Skipping controller docs, folder ${projectbase} not available`); return; } let files = await readdir(path.join(projectbase, 'controllers')); files = files.map(i => path.relative(projectbase, i)); let sfrabase = path.join(process.cwd(), options.projectpath); sfrabase = path.join(process.cwd(), options.sfrapath); let sfrafiles = await readdir(path.join(sfrabase, 'controllers')); sfrafiles = sfrafiles.map(i => path.relative(sfrabase, i)); let controllers = files.map(i => ({ name: i, project: true, sfra: sfrafiles.includes(i) })); let sfracontrollers = sfrafiles.filter(i => !files.includes(i)).map(i => ({ name: i, project: false, sfra: true })); controllers = controllers.concat(sfracontrollers); let templates = await readdir(path.join(projectbase, 'templates/default')); templates = templates.map(i => path.relative(projectbase, i)); let sfratemplates = await readdir(path.join(sfrabase, 'templates/default')); sfratemplates = sfratemplates.map(i => path.relative(sfrabase, i)); let templatesprj = templates.map(i => ({ name: i, project: true, sfra: sfratemplates.includes(i) })); let context = { controllers: controllers, templates: templatesprj }; let output = path.join(process.cwd(), 'output/config/', 'controllers.html'); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/controllers.html`), 'utf-8'))(context)); log(chalk.green(`Generated documentation at ${output}`)); } async function metacheatsheet () { const argv = yargs.argv; options.projectpath = argv.projectpath || options.projectpath; options.sfrapath = argv.sfrapath || options.sfrapath; await buildMeta(); await buildFromXml('sites/site_template/services.xml', 'services.html'); await buildFromXml('sites/site_template/jobs.xml', 'jobs.html'); await buildSeo('url-rules.xml', 'seo.html'); await buildFromXml('sites/site_template/pagemetatag.xml', 'pagemetatag.html'); await listcontrollers(); await buildAssetDoc(); } async function buildMeta () { let definitionspath = path.join(process.cwd(), 'sites/site_template/meta/custom-objecttype-definitions.xml'); let extensionspath = path.join(process.cwd(), 'sites/site_template/meta/system-objecttype-extensions.xml'); let exts = await parseMeta(extensionspath); let defs = await parseMeta(definitionspath); let context = { extensions: exts, definitions: defs }; let output = path.join(process.cwd(), 'output/config/', 'metacheatsheet.html'); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/meta.html`), 'utf-8'))(context)); log(chalk.green(`Generated documentation at ${output}`)); } async function buildFromXml (input, html) { let inputpath = path.join(process.cwd(), input); if (!fs.existsSync(inputpath)) { return; } let output = path.join(process.cwd(), 'output/config/', html); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(await parseMeta(inputpath))); log(chalk.green(`Generated documentation at ${output}`)); } async function buildSeo (xml, html) { let mappings = await entrypoints(); let context = await parseXmlSites(xml, 'seo.html'); if (!context) { return; } context.sites.forEach(site => { let siteentrypoints = JSON.parse(JSON.stringify(mappings)); if (site.urlrules && site.urlrules.pipelinealiases && site.urlrules.pipelinealiases[0]) { site.urlrules.pipelinealiases[0].pipelinealias.forEach(alias => { if (siteentrypoints[alias.pipeline]) { siteentrypoints[alias.pipeline].alias = alias._; } else { // console.log(`Not existing remapping: ${alias._}=${alias.pipeline}`); siteentrypoints[alias.pipeline] = { alias: alias._, pipeline: alias.pipeline, controller: alias.pipeline.substr(0, alias.pipeline.indexOf('-')), cartridges: [] } }; }); } let entrypointsarray = Object.keys(siteentrypoints).map(i => siteentrypoints[i]).sort((a, b) => a.pipeline.localeCompare(b.pipeline)); site.entrypoints = entrypointsarray; }) let output = path.join(process.cwd(), 'output/config/', html); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(context)); log(chalk.green(`Generated documentation at ${output}`)); } async function isml() { let inputpath = path.join(process.cwd(), `${options.projectpath}/templates/default`); if (!fs.existsSync(inputpath)) { return; } let sfrapath = path.join(process.cwd(), `${options.sfrapath}/templates/default`); let sfrafiles = await readdir(sfrapath); let mapping = sfrafiles.filter(i => path.extname(i) === '.isml').map(i => ({ path: i, template: path.relative(sfrapath, i), type: 'sfra' }) ); let files = await readdir(inputpath); let projectmapping = files.filter(i => path.extname(i) === '.isml').map(i => ({ path: i, template: path.relative(inputpath, i), type: 'project' }) ); projectmapping.forEach(i => { let idx = mapping.findIndex(p => p.template === i.template); if (idx) { mapping.splice(idx, 1); } }); return mapping.concat(projectmapping).sort((a, b) => a.template.localeCompare(b.template)); } async function buildAssetDoc() { let html = 'assets.html'; let ismls = await isml(); if (!ismls) { return; } const assetsregexp = /iscontentasset['" a-zA-Z0-9-/\n]* aid="([a-zA-Z0-9-_/]*)/gm; const slotregexp = /isslot['" a-zA-Z0-9-/\n]* id="([a-zA-Z0-9-_/]*)/gm; const includesregexp = /isinclude['" a-zA-Z0-9-/\n]* template="([a-zA-Z0-9-_/]*)/gm; ismls.forEach(i => { let filecontent = fs.readFileSync(i.path); i.assets = regexpmatch(assetsregexp, filecontent); i.slots = regexpmatch(slotregexp, filecontent); i.includes = regexpmatch(includesregexp, filecontent); }); ismls = ismls.filter(i => i.assets.length !== 0 || i.slots.length !== 0 || i.includes.length !== 0); // log('isml:', JSON.stringify(ismls, null, 2)); let contentonly = ismls.filter(i => i.assets.length !== 0 || i.slots.length !== 0); let output = path.join(process.cwd(), 'output/config/', html); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))({ templates: ismls , content: contentonly })); log(chalk.green(`Generated documentation at ${output}`)); } function regexpmatch(regex, filecontent) { let matches = []; let m; // eslint-disable-next-line no-cond-assign while ((m = regex.exec(filecontent)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } matches.push(m[1]); } return matches; } async function parseXmlSites (filename, html) { let files = await readdir(path.join(process.cwd(), 'sites/site_template/sites/'), [(i, stats) => !stats.isDirectory() && path.basename(i) !== "url-rules.xml"]); if (!files || files.length === 0) { return; } let context = { sites: [] }; for (let j = 0; j < files.length; j++) { let single = await parseMeta(files[j]); single.id = path.basename(path.dirname(files[j])); context.sites.push(single); } return context; } // eslint-disable-next-line no-unused-vars async function buildFromXmlSites (filename, html) { let context = await parseXmlSites(filename, html); let output = path.join(process.cwd(), 'output/config/', html); fs.writeFileSync(output, _.template(fs.readFileSync(path.resolve(__dirname, `templates/${html}`), 'utf-8'))(context)); log(chalk.green(`Generated documentation at ${output}`)); } module.exports = { validate, xsdfy, metacheatsheet };
#!/usr/bin/env python # -*- coding: utf-8 -*- """Update encrypted deploy password in Travis config file """ from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.primitives.serialization import load_pem_public_key from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15 try: from urllib import urlopen except: from urllib.request import urlopen GITHUB_REPO = 'chinab91/pysheets' TRAVIS_CONFIG_FILE = os.path.join( os.path.dirname(os.path.abspath(__file__)), '.travis.yml') def load_key(pubkey): """Load public RSA key, with work-around for keys using incorrect header/footer format. Read more about RSA encryption with cryptography: https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/ """ try: return load_pem_public_key(pubkey.encode(), default_backend()) except ValueError: # workaround for https://github.com/travis-ci/travis-api/issues/196 pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END') return load_pem_public_key(pubkey.encode(), default_backend()) def encrypt(pubkey, password): """Encrypt password using given RSA public key and encode it with base64. The encrypted password can only be decrypted by someone with the private key (in this case, only Travis). """ key = load_key(pubkey) encrypted_password = key.encrypt(password, PKCS1v15()) return base64.b64encode(encrypted_password) def fetch_public_key(repo): """Download RSA public key Travis will use for this repo. Travis API docs: http://docs.travis-ci.com/api/#repository-keys """ keyurl = 'https://api.travis-ci.org/repos/{0}/key'.format(repo) data = json.loads(urlopen(keyurl).read().decode()) if 'key' not in data: errmsg = "Could not find public key for repo: {}.\n".format(repo) errmsg += "Have you already added your GitHub repo to Travis?" raise ValueError(errmsg) return data['key'] def prepend_line(filepath, line): """Rewrite a file adding a line to its beginning. """ with open(filepath) as f: lines = f.readlines() lines.insert(0, line) with open(filepath, 'w') as f: f.writelines(lines) def load_yaml_config(filepath): with open(filepath) as f: return yaml.load(f) def save_yaml_config(filepath, config): with open(filepath, 'w') as f: yaml.dump(config, f, default_flow_style=False) def update_travis_deploy_password(encrypted_password): """Update the deploy section of the .travis.yml file to use the given encrypted password. """ config = load_yaml_config(TRAVIS_CONFIG_FILE) config['deploy']['password'] = dict(secure=encrypted_password) save_yaml_config(TRAVIS_CONFIG_FILE, config) line = ('# This file was autogenerated and will overwrite' ' each time you run travis_pypi_setup.py\n') prepend_line(TRAVIS_CONFIG_FILE, line) def main(args): public_key = fetch_public_key(args.repo) password = args.password or getpass('PyPI password: ') update_travis_deploy_password(encrypt(public_key, password.encode())) print("Wrote encrypted password to .travis.yml -- you're ready to deploy") if '__main__' == __name__: import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo', default=GITHUB_REPO, help='GitHub repo (default: %s)' % GITHUB_REPO) parser.add_argument('--password', help='PyPI password (will prompt if not provided)') args = parser.parse_args() main(args)
/* IE7/IE8/IE9.js - copyright 2004-2010, Dean Edwards http://code.google.com/p/ie7-js/ http://www.opensource.org/licenses/mit-license.php */ ;(function(L,r){var h=L.IE7={version:"2.1(beta4)",toString:bJ("[IE7]")};h.compat=8;var s=h.appVersion=navigator.appVersion.match(/MSIE (\d\.\d)/)[1]-0;if(/ie7_off/.test(top.location.search)||s<5.5||s>=h.compat)return;var C=s<6,bh=bJ(),bt=r.documentElement,A,w,ci="!",X=":link{ie7-link:link}:visited{ie7-link:visited}",cj=/^[\w\.]+[^:]*$/;function bi(b,a){if(cj.test(b))b=(a||"")+b;return b};function bu(b,a){b=bi(b,a);return b.slice(0,b.lastIndexOf("/")+1)};var bK=r.scripts[r.scripts.length-1],ck=bu(bK.src);try{var Q=new ActiveXObject("Microsoft.XMLHTTP")}catch(ex){}var bj={};function cl(b,a){try{b=bi(b,a);if(!bj[b]){Q.open("GET",b,false);Q.send();if(Q.status==0||Q.status==200){bj[b]=Q.responseText}}}catch(ex){}return bj[b]||""};var dl=Array.prototype.slice,dm=/%([1-9])/g,cm=/^\s\s*/,cn=/\s\s*$/,co=/([\/()[\]{}|*+-.,^$?\\])/g,bL=/\bbase\b/,bM=["constructor","toString"],bk;function D(){};D.extend=function(f,d){bk=true;var c=new this;Y(c,f);bk=false;var b=c.constructor;function a(){if(!bk)b.apply(this,arguments)};c.constructor=a;a.extend=arguments.callee;Y(a,d);a.prototype=c;return a};D.prototype.extend=function(a){return Y(this,a)};var M="#",N="#",Z=".",bl="/",dn=/\\(\d+)/g,cp=/\[(\\.|[^\]\\])+\]|\\.|\(\?/g,cq=/\(/g,cr=/\$(\d+)/,cs=/^\$\d+$/,ct=/(\[(\\.|[^\]\\])+\]|\\.|\(\?)|\(/g,cu=/^<#\w+>$/,cv=/<#(\w+)>/g,E=D.extend({constructor:function(a){this[Z]=[];this[N]={};this.merge(a)},add:function(b,a){delete this[bl];if(b instanceof RegExp){b=b.source}if(!this[M+b])this[Z].push(String(b));return this[N][M+b]=new E.Item(b,a,this)},compile:function(a){if(a||!this[bl]){this[bl]=new RegExp(this,this.ignoreCase?"gi":"g")}return this[bl]},merge:function(b){for(var a in b)this.add(a,b[a])},exec:function(n){var j=this,k=j[Z],l=j[N],i,g=this.compile(true).exec(n);if(g){var f=0,d=1;while((i=l[M+k[f++]])){var c=d+i.length+1;if(g[d]){if(i.replacement===0){return j.exec(n)}else{var b=g.slice(d,c),a=b.length;while(--a)b[a]=b[a]||"";b[0]={match:b[0],item:i};return b}}d=c}}return null},parse:function(n){n+="";var j=this,k=j[Z],l=j[N];return n.replace(this.compile(),function(i){var g=[],f,d=1,c=arguments.length;while(--c)g[c]=arguments[c]||"";while((f=l[M+k[c++]])){var b=d+f.length+1;if(g[d]){var a=f.replacement;switch(typeof a){case"function":return a.apply(j,g.slice(d,b));case"number":return g[d+a];default:return a}}d=b}return i})},toString:function(){var f=[],d=this[Z],c=this[N],b;for(var a=0;b=c[M+d[a]];a++){f[a]=b.source}return"("+f.join(")|(")+")"}},{IGNORE:null,Item:D.extend({constructor:function(j,k,l){var i=j.indexOf("(")===-1?0:E.count(j),g=l.dictionary;if(g&&j.indexOf("<#")!==-1){if(cu.test(j)){var f=g[N][M+j.slice(2,-1)];j=f.replacement;i=f._4}else{j=g.parse(j)}}if(typeof k=="number")k=String(k);else if(k==null)k=0;if(typeof k=="string"&&cr.test(k)){if(cs.test(k)){var d=k.slice(1)-0;if(d&&d<=i)k=d}else{var c=k,b;k=function(a){if(!b){b=new RegExp(j,"g"+(this.ignoreCase?"i":""))}return a.replace(b,c)}}}this.length=i;this.source=String(j);this.replacement=k}}),count:function(a){return(String(a).replace(cp,"").match(cq)||"").length}}),cw=E.extend({parse:function(d){var c=this[N];return d.replace(cv,function(b,a){a=c[M+a];return a?a._5:b})},add:function(f,d){if(d instanceof RegExp){d=d.source}var c=d.replace(ct,cx);if(d.indexOf("(")!==-1){var b=E.count(d)}if(d.indexOf("<#")!==-1){d=this.parse(d);c=this.parse(c)}var a=this.base(f,d);a._5=c;a._4=b||a.length;return a},toString:function(){return"(<#"+this[PATTERNS].join(">)|(<#")+">)"}});function cx(b,a){return a||"(?:"};function Y(g,f){if(g&&f){var d=(typeof f=="function"?Function:Object).prototype;var c=bM.length,b;if(bk)while(b=bM[--c]){var a=f[b];if(a!=d[b]){if(bL.test(a)){bN(g,b,a)}else{g[b]=a}}}for(b in f)if(typeof d[b]=="undefined"){var a=f[b];if(g[b]&&typeof a=="function"&&bL.test(a)){bN(g,b,a)}else{g[b]=a}}}return g};function bN(g,f,d){var c=g[f];g[f]=function(){var b=this.base;this.base=c;var a=d.apply(this,arguments);this.base=b;return a}};function cy(d,c){if(!c)c=d;var b={};for(var a in d)b[a]=c[a];return b};function F(f){var d=arguments,c=new RegExp("%([1-"+arguments.length+"])","g");return String(f).replace(c,function(b,a){return a<d.length?d[a]:b})};function bm(b,a){return String(b).match(a)||[]};function bO(a){return String(a).replace(co,"\\$1")};function bP(a){return String(a).replace(cm,"").replace(cn,"")};function bJ(a){return function(){return a}};var bQ=E.extend({ignoreCase:true}),cz=/'/g,bR=/'(\d+)'/g,o0=/\\/g,bv=/\\([nrtf'"])/g,R=[],bS=new bQ({"<!\\-\\-|\\-\\->":"","\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/":"","@(namespace|import)[^;\\n]+[;\\n]":"","'(\\\\.|[^'\\\\])*'":bT,'"(\\\\.|[^"\\\\])*"':bT,"\\s+":" "});function cA(a){return bS.parse(a).replace(bv,"$1")};function ba(a){return a.replace(bR,cB)};function bT(b){var a=R.length;R[a]=b.slice(1,-1).replace(bv,"$1").replace(cz,"\\'");return"'"+a+"'"};function cB(c,b){var a=R[b];if(a==null)return c;return"'"+R[b]+"'"};function bn(a){return a.indexOf("'")===0?R[a.slice(1,-1)]:a};var cC=new E({Width:"Height",width:"height",Left:"Top",left:"top",Right:"Bottom",right:"bottom",onX:"onY"});function bU(a){return cC.parse(a)};var bV=[];function bw(a){cD(a);x(L,"onresize",a)};function x(c,b,a){c.attachEvent(b,a);bV.push(arguments)};function cE(c,b,a){try{c.detachEvent(b,a)}catch(ex){}};x(L,"onunload",function(){var a;while(a=bV.pop()){cE(a[0],a[1],a[2])}});function bb(c,b,a){if(!c.elements)c.elements={};if(a)c.elements[b.uniqueID]=b;else delete c.elements[b.uniqueID];return a};x(L,"onbeforeprint",function(){if(!h.CSS.print)new bW("print");h.CSS.print.recalc()});var bX=/^\d+(px)?$/i,S=/^\d+%$/,B=function(d,c){if(bX.test(c))return parseInt(c);var b=d.style.left,a=d.runtimeStyle.left;d.runtimeStyle.left=d.currentStyle.left;d.style.left=c||0;c=d.style.pixelLeft;d.style.left=b;d.runtimeStyle.left=a;return c},bx="ie7-",bY=D.extend({constructor:function(){this.fixes=[];this.recalcs=[]},init:bh}),by=[];function cD(a){by.push(a)};h.recalc=function(){h.HTML.recalc();h.CSS.recalc();for(var a=0;a<by.length;a++)by[a]()};function bo(a){return a.currentStyle["ie7-position"]=="fixed"};function bz(b,a){return b.currentStyle[bx+a]||b.currentStyle[a]};function T(c,b,a){if(c.currentStyle[bx+b]==null){c.runtimeStyle[bx+b]=c.currentStyle[b]}c.runtimeStyle[b]=a};function bZ(b){var a=r.createElement(b||"object");a.style.cssText="position:absolute;padding:0;display:block;border:none;clip:rect(0 0 0 0);left:-9999";a.ie7_anon=true;return a};var cF="(e.nextSibling&&IE7._1(e,'next'))",cG=cF.replace(/next/g,"previous"),ca="e.nodeName>'@'",cb="if("+ca+"){",cH="(e.nodeName==='FORM'?IE7._0(e,'id'):e.id)",cI=/a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i,cJ=/(.*)(:first-(line|letter))/,cK=/\s/,cL=/((?:\\.|[^{\\])+)\{((?:\\.|[^}\\])+)\}/g,cM=/(?:\\.|[^,\\])+/g,G=r.styleSheets,bA=[];h.CSS=new(bY.extend({parser:new bQ,screen:"",print:"",styles:[],rules:[],pseudoClasses:s<7?"first\\-child":"",dynamicPseudoClasses:{toString:function(){var b=[];for(var a in this)b.push(a);return b.join("|")}},init:function(){var i="^\x01$",g="\\[class=?[^\\]]*\\]",f=[];if(this.pseudoClasses)f.push(this.pseudoClasses);var d=this.dynamicPseudoClasses.toString();if(d)f.push(d);f=f.join("|");var c=s<7?["[>+~\\[(]|([:.])[\\w-]+\\1"]:[g];if(f)c.push(":("+f+")");this.UNKNOWN=new RegExp(c.join("|")||i,"i");var b=s<7?["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"]:[g],a=b.concat();if(f)a.push(":("+f+")");t.COMPLEX=new RegExp(a.join("|")||i,"ig");if(this.pseudoClasses)b.push(":("+this.pseudoClasses+")");bc.COMPLEX=new RegExp(b.join("|")||i,"i");d="not\\(:"+d.split("|").join("\\)|not\\(:")+"\\)|"+d;bc.MATCH=new RegExp(d?"(.*?):("+d+")(.*)":i,"i");this.createStyleSheet();this.refresh()},addEventHandler:function(){x.apply(null,arguments)},addFix:function(b,a){this.parser.add(b,a)},addRecalc:function(g,f,d,c){g=g.source||g;f=new RegExp("([{;\\s])"+g+"\\s*:\\s*"+f+"[^;}]*");var b=this.recalcs.length;if(typeof c=="string")c=g+":"+c;this.addFix(f,function(a){if(typeof c=="function")c=c(a);return(c?c:a)+";ie7-"+a.slice(1)+";ie7_recalc"+b+":1"});this.recalcs.push(arguments);return b},apply:function(){this.getInlineCSS();new bW("screen");this.trash()},createStyleSheet:function(){r.getElementsByTagName("head")[0].appendChild(r.createElement("style"));this.styleSheet=G[G.length-1];this.styleSheet.ie7=true;this.styleSheet.owningElement.ie7=true;this.styleSheet.cssText=X},getInlineCSS:function(){var c=r.getElementsByTagName("style"),b;for(var a=c.length-1;b=c[a];a--){if(!b.disabled&&!b.ie7){b._6=b.innerHTML}}},getText:function(c,b){try{var a=c.cssText}catch(e){a=""}if(Q)a=cl(c.href,b)||a;return a},recalc:function(){this.screen.recalc();var o=/ie7_recalc\d+/g,m=X.match(/[{,]/g).length,n=this.styleSheet.rules,j,k,l,i,g,f,d,c,b;for(f=m;j=n[f];f++){var a=j.style.cssText;if(k=a.match(o)){i=H(j.selectorText);if(i.length)for(d=0;d<k.length;d++){b=k[d];l=h.CSS.recalcs[b.slice(10)][2];for(c=0;(g=i[c]);c++){if(g.currentStyle[b])l(g,a)}}}}},refresh:function(){this.styleSheet.cssText=X+this.screen+this.print},trash:function(){for(var b=0;b<G.length;b++){if(!G[b].ie7){try{var a=G[b].cssText}catch(e){a=""}if(a)G[b].cssText=""}}}}));var bW=D.extend({constructor:function(a){this.media=a;this.load();h.CSS[a]=this;h.CSS.refresh()},createRule:function(c,b){var a;if(O&&(a=c.match(O.MATCH))){return new O(a[1],a[2],b)}else if(a=c.match(bc.MATCH)){if(!cI.test(a[0])||bc.COMPLEX.test(a[0])){return new bc(c,a[1],a[2],a[3],b)}}else{return new t(c,b)}return c+" {"+b+"}"},getText:function(){var u=/@media\s+([^{]+?)\s*\{([^@]+\})\s*\}/gi,U=/@import[^;\n]+/gi,P=/@import\s+url\s*\(\s*["']?|["']?\s*\)\s*/gi,V=/(url\s*\(\s*['"]?)([\w\.]+[^:\)]*['"]?\))/gi,I=this,J={};function y(j,k,l,i){var g="";if(!i){l=o(j.media);i=0}if(l==="none"){j.disabled=true;return""}if(l==="all"||l===I.media){try{var f=!!j.cssText}catch(exe){}if(i<3&&f){var d=j.cssText.match(U);for(var c=0,b;c<j.imports.length;c++){var b=j.imports[c];var a=j._2||j.href;b._2=d[c].replace(P,"");g+=y(b,bu(a,k),l,i+1)}}g+=cA(j.href?m(j,k):j.owningElement._6);g=z(g,I.media)}return g};for(var v=0;v<G.length;v++){var p=G[v];if(!p.disabled&&!p.ie7)this.cssText+=y(p)}function z(b,a){q.value=a;return b.replace(u,q)};function q(c,b,a){b=o(b);switch(b){case"screen":case"print":if(b!==q.value)return"";case"all":return a}return""};function o(c){if(!c)return"all";var b=c.toLowerCase().split(/\s*,\s*/);c="none";for(var a=0;a<b.length;a++){if(b[a]==="all")return"all";if(b[a]==="screen"){if(c==="print")return"all";c="screen"}else if(b[a]==="print"){if(c==="screen")return"all";c="print"}}return c};function m(d,c){var b=d._2||d.href,a=bi(b,c);if(J[a])return"";J[a]=d.disabled?"":n(h.CSS.getText(d,c),bu(b,c));return J[a]};function n(b,a){return b.replace(V,"$1"+a.slice(0,a.lastIndexOf("/")+1)+"$2")}},load:function(){this.cssText="";this.getText();this.parse();if(bA.length){this.cssText=cN(this.cssText)}this.cssText=ba(this.cssText);bj={}},parse:function(){var i=h.CSS.parser.parse(this.cssText),n="";this.cssText=i.replace(/@charset[^;]+;|@font\-face[^\}]+\}/g,function(a){n+=a+"\n";return""});this.declarations=ba(n);var j=h.CSS.rules.length,k=[],l;while((l=cL.exec(this.cssText))){var i=l[2];if(i){var g=s<7&&i.indexOf("AlphaImageLoader")!==-1;var f=l[1].match(cM),d;for(var c=0;d=f[c];c++){d=bP(d);var b=h.CSS.UNKNOWN.test(d);f[c]=b?this.createRule(d,i):d+"{"+i+"}";if(g)f[c]+=this.createRule(d+">*","position:relative")}k.push(f.join("\n"))}}this.cssText=k.join("\n");this.rules=h.CSS.rules.slice(j)},recalc:function(){var b,a;for(a=0;(b=this.rules[a]);a++)b.recalc()},toString:function(){return this.declarations+"@media "+this.media+"{"+this.cssText+"}"}}),O,t=h.Rule=D.extend({constructor:function(c,b){this.id=h.CSS.rules.length;this.className=t.PREFIX+this.id;var a=c.match(cJ);this.selector=(a?a[1]:c)||"*";this.selectorText=this.parse(this.selector)+(a?a[2]:"");this.cssText=b;this.MATCH=new RegExp("\\s"+this.className+"(\\s|$)","g");h.CSS.rules.push(this);this.init()},init:bh,add:function(a){a.className+=" "+this.className},recalc:function(){var b=H(this.selector);for(var a=0;a<b.length;a++)this.add(b[a])},parse:function(f){var d=f.replace(t.CHILD," ").replace(t.COMPLEX,"");if(s<7)d=d.replace(t.MULTI,"");var c=bm(d,t.TAGS).length-bm(f,t.TAGS).length,b=bm(d,t.CLASSES).length-bm(f,t.CLASSES).length+1;while(b>0&&t.CLASS.test(d)){d=d.replace(t.CLASS,"");b--}while(c>0&&t.TAG.test(d)){d=d.replace(t.TAG,"$1*");c--}d+="."+this.className;b=Math.min(b,2);c=Math.min(c,2);var a=-10*b-c;if(a>0){d=d+","+t.MAP[a]+" "+d}return d},remove:function(a){a.className=a.className.replace(this.MATCH,"$1")},toString:function(){return F("%1 {%2}",this.selectorText,this.cssText)}},{CHILD:/>/g,CLASS:/\.[\w-]+/,CLASSES:/[.:\[]/g,MULTI:/(\.[\w-]+)+/g,PREFIX:"ie7_class",TAG:/^\w+|([\s>+~])\w+/,TAGS:/^\w|[\s>+~]\w/g,MAP:{"1":"html","2":"html body","10":".ie7_html","11":"html.ie7_html","12":"html.ie7_html body","20":".ie7_html .ie7_body","21":"html.ie7_html .ie7_body","22":"html.ie7_html body.ie7_body"}}),bc=t.extend({constructor:function(f,d,c,b,a){this.negated=c.indexOf("not")===0;if(this.negated)c=c.slice(5,-1);this.attach=d||"*";this.dynamicPseudoClass=h.CSS.dynamicPseudoClasses[c];this.target=b;this.base(f,a)},recalc:function(){var d=H(this.attach),c;for(var b=0;c=d[b];b++){var a=this.target?H(this.target,c):[c];if(a.length)this.dynamicPseudoClass.apply(c,a,this)}}}),bB=D.extend({constructor:function(b,a){this.name=b;this.apply=a;this.instances={};h.CSS.dynamicPseudoClasses[b]=this},register:function(f,d){var c=f[2];if(!d&&c.negated){this.unregister(f,true)}else{f.id=c.id+f[0].uniqueID;if(!this.instances[f.id]){var b=f[1],a;for(a=0;a<b.length;a++)c.add(b[a]);this.instances[f.id]=f}}},unregister:function(f,d){var c=f[2];if(!d&&c.negated){this.register(f,true)}else{if(this.instances[f.id]){var b=f[1],a;for(a=0;a<b.length;a++)c.remove(b[a]);delete this.instances[f.id]}}}}),bp=new bB("hover",function(b){var a=arguments;h.CSS.addEventHandler(b,"onmouseenter",function(){bp.register(a)});h.CSS.addEventHandler(b,"onmouseleave",function(){bp.unregister(a)})});x(r,"onmouseup",function(){var b=bp.instances;for(var a in b)if(!b[a][0].contains(event.srcElement))bp.unregister(b[a])});var cc={"=":"%1==='%2'","~=":"(' '+%1+' ').indexOf(' %2 ')!==-1","|=":"%1==='%2'||%1.indexOf('%2-')===0","^=":"%1.indexOf('%2')===0","$=":"%1.slice(-'%2'.length)==='%2'","*=":"%1.indexOf('%2')!==-1"};cc[""]="%1!=null";var bd={"<#attr>":function(f,d,c,b){var a="IE7._0(e,'"+d+"')";b=bn(b);if(c.length>1){if(!b||c==="~="&&cK.test(b)){return"false&&"}a="("+a+"||'')"}return"("+F(cc[c],a,b)+")&&"},"<#id>":cH+"==='$1'&&","<#class>":"e.className&&(' '+e.className+' ').indexOf(' $1 ')!==-1&&",":first-child":"!"+cG+"&&",":link":"e.currentStyle['ie7-link']=='link'&&",":visited":"e.currentStyle['ie7-link']=='visited'&&"};h.HTML=new(bY.extend({fixed:{},init:bh,addFix:function(){this.fixes.push(arguments)},apply:function(){for(var d=0;d<this.fixes.length;d++){var c=H(this.fixes[d][0]);var b=this.fixes[d][1];for(var a=0;a<c.length;a++)b(c[a])}},addRecalc:function(){this.recalcs.push(arguments)},recalc:function(){for(var i=0;i<this.recalcs.length;i++){var g=H(this.recalcs[i][0]);var f=this.recalcs[i][1],d;var c=Math.pow(2,i);for(var b=0;(d=g[b]);b++){var a=d.uniqueID;if((this.fixed[a]&c)===0){d=f(d)||d;this.fixed[a]|=c}}}}}));if(s<7){r.createElement("abbr");h.HTML.addRecalc("label",function(b){if(!b.htmlFor){var a=H("input,textarea",b,true);if(a){x(b,"onclick",function(){a.click()})}}})}var be="[.\\d]";(function(){var u=h.Layout={};X+="*{boxSizing:content-box}";u.boxSizing=function(a){if(!a.currentStyle.hasLayout){a.style.height="0cm";if(a.currentStyle.verticalAlign==="auto")a.runtimeStyle.verticalAlign="top";U(a)}};function U(a){if(a!=w&&a.currentStyle.position!=="absolute"){P(a,"marginTop");P(a,"marginBottom")}};function P(f,d){if(!f.runtimeStyle[d]){var c=f.parentElement;var b=d==="marginTop";if(c&&c.currentStyle.hasLayout&&!h._1(f,b?"previous":"next"))return;var a=f[b?"firstChild":"lastChild"];if(a&&a.nodeName<"@")a=h._1(a,b?"next":"previous");if(a&&a.currentStyle.styleFloat==="none"&&a.currentStyle.hasLayout){P(a,d);margin=V(f,f.currentStyle[d]);childMargin=V(a,a.currentStyle[d]);if(margin<0||childMargin<0){f.runtimeStyle[d]=margin+childMargin}else{f.runtimeStyle[d]=Math.max(childMargin,margin)}a.runtimeStyle[d]="0px"}}};function V(b,a){return a==="auto"?0:B(b,a)};var I=/^[.\d][\w]*$/,J=/^(auto|0cm)$/,y={};u.borderBox=function(a){y.Width(a);y.Height(a)};var v=function(p){y.Width=function(a){if(!S.test(a.currentStyle.width))z(a);if(p)U(a)};function z(b,a){if(!b.runtimeStyle.fixedWidth){if(!a)a=b.currentStyle.width;b.runtimeStyle.fixedWidth=I.test(a)?Math.max(0,m(b,a))+"px":a;T(b,"width",b.runtimeStyle.fixedWidth)}};function q(b){if(!bo(b)){var a=b.offsetParent;while(a&&!a.currentStyle.hasLayout)a=a.offsetParent}return(a||w).clientWidth};function o(b,a){if(S.test(a))return parseInt(parseFloat(a)/100*q(b));return B(b,a)};var m=function(d,c){var b=d.currentStyle["ie7-box-sizing"]==="border-box",a=0;if(C&&!b)a+=n(d)+j(d,"padding");else if(!C&&b)a-=n(d)+j(d,"padding");return o(d,c)+a};function n(a){return a.offsetWidth-a.clientWidth};function j(b,a){return o(b,b.currentStyle[a+"Left"])+o(b,b.currentStyle[a+"Right"])};X+="*{minWidth:none;maxWidth:none;min-width:none;max-width:none}";u.minWidth=function(a){if(a.currentStyle["min-width"]!=null){a.style.minWidth=a.currentStyle["min-width"]}if(bb(arguments.callee,a,a.currentStyle.minWidth!=="none")){u.boxSizing(a);z(a);k(a)}};eval("IE7.Layout.maxWidth="+String(u.minWidth).replace(/min/g,"max"));function k(c){if(c==r.body){var b=c.clientWidth}else{var a=c.getBoundingClientRect();b=a.right-a.left}if(c.currentStyle.minWidth!=="none"&&b<m(c,c.currentStyle.minWidth)){c.runtimeStyle.width=c.currentStyle.minWidth}else if(c.currentStyle.maxWidth!=="none"&&b>=m(c,c.currentStyle.maxWidth)){c.runtimeStyle.width=c.currentStyle.maxWidth}else{c.runtimeStyle.width=c.runtimeStyle.fixedWidth}};function l(a){if(bb(l,a,/^(fixed|absolute)$/.test(a.currentStyle.position)&&bz(a,"left")!=="auto"&&bz(a,"right")!=="auto"&&J.test(bz(a,"width")))){i(a);u.boxSizing(a)}};u.fixRight=l;function i(c){var b=o(c,c.runtimeStyle._3||c.currentStyle.left),a=q(c)-o(c,c.currentStyle.right)-b-j(c,"margin");if(parseInt(c.runtimeStyle.width)===a)return;c.runtimeStyle.width="";if(bo(c)||p||c.offsetWidth<a){if(!C)a-=n(c)+j(c,"padding");if(a<0)a=0;c.runtimeStyle.fixedWidth=a;T(c,"width",a)}};var g=0;bw(function(){if(!w)return;var f,d=(g<w.clientWidth);g=w.clientWidth;var c=u.minWidth.elements;for(f in c){var b=c[f];var a=(parseInt(b.runtimeStyle.width)===m(b,b.currentStyle.minWidth));if(d&&a)b.runtimeStyle.width="";if(d==a)k(b)}var c=u.maxWidth.elements;for(f in c){var b=c[f];var a=(parseInt(b.runtimeStyle.width)===m(b,b.currentStyle.maxWidth));if(!d&&a)b.runtimeStyle.width="";if(d!==a)k(b)}for(f in l.elements)i(l.elements[f])});if(C){h.CSS.addRecalc("width",be,y.Width)}if(s<7){h.CSS.addRecalc("max-width",be,u.maxWidth);h.CSS.addRecalc("right",be,l)}else if(s==7){if(p)h.CSS.addRecalc("height","[\\d.]+%",function(element){element.runtimeStyle.pixelHeight=parseInt(q(element)*element.currentStyle["ie7-height"].slice(0,-1)/100)})}};eval("var _7="+bU(v));v();_7(true);if(s<7){h.CSS.addRecalc("min-width",be,u.minWidth);h.CSS.addFix(/\bmin-height\s*/,"height")}})();var bC=bi("blank.gif",ck),bD="DXImageTransform.Microsoft.AlphaImageLoader",cd="progid:"+bD+"(src='%1',sizingMethod='%2')",bf,bg=[];function ce(b){if(bf.test(b.src)){var a=new Image(b.width,b.height);a.onload=function(){b.width=a.width;b.height=a.height;a=null};a.src=b.src;b.pngSrc=b.src;bq(b)}};if(s<7){h.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/,function(f,d,c,b,a){b=bn(b);return bf.test(b)?"filter:"+F(cd,b,a.indexOf("no-repeat")===-1?"scale":"crop")+";zoom:1;background"+(d||"")+":"+(c||"")+"none"+(a||""):f});h.CSS.addRecalc(/list\-style(\-image)?/,"[^};]*url",function(d){var c=d.currentStyle.listStyleImage.slice(5,-2);if(bf.test(c)){if(d.nodeName==="LI"){cf(d,c)}else if(d.nodeName==="UL"){for(var b=0,a;a=d.childNodes[b];b++){if(a.nodeName==="LI")cf(a,c)}}}});function cf(g,f){var d=g.runtimeStyle,c=g.offsetHeight,b=new Image;b.onload=function(){var a=g.currentStyle.paddingLeft;a=a==="0px"?0:B(g,a);d.paddingLeft=(a+this.width)+"px";d.marginLeft=-this.width+"px";d.listStyleType="none";d.listStyleImage="none";d.paddingTop=Math.max(c-g.offsetHeight,0)+"px";bq(g,"crop",f);g.style.zoom="100%"};b.src=f};h.HTML.addRecalc("img,input",function(a){if(a.nodeName==="INPUT"&&a.type!=="image")return;ce(a);x(a,"onpropertychange",function(){if(!bE&&event.propertyName==="src"&&a.src.indexOf(bC)===-1)ce(a)})});var bE=false;x(L,"onbeforeprint",function(){bE=true;for(var a=0;a<bg.length;a++)cO(bg[a])});x(L,"onafterprint",function(){for(var a=0;a<bg.length;a++)bq(bg[a]);bE=false})}function bq(d,c,b){var a=d.filters[bD];if(a){a.src=b||d.src;a.enabled=true}else{d.runtimeStyle.filter=F(cd,b||d.src,c||"scale");bg.push(d)}d.src=bC};function cO(a){a.src=a.pngSrc;a.filters[bD].enabled=false};(function(){if(s>=7)return;h.CSS.addRecalc("position","fixed",n,"absolute");h.CSS.addRecalc("background(-attachment)?","[^};]*fixed",o);var y=C?"body":"documentElement";function v(){if(A.currentStyle.backgroundAttachment!=="fixed"){if(A.currentStyle.backgroundImage==="none"){A.runtimeStyle.backgroundRepeat="no-repeat";A.runtimeStyle.backgroundImage="url("+bC+")"}A.runtimeStyle.backgroundAttachment="fixed"}v=bh};var p=bZ("img");function z(a){return a?bo(a)||z(a.parentElement):false};function q(c,b,a){setTimeout("document.all."+c.uniqueID+".runtimeStyle.setExpression('"+b+"','"+a+"')",0)};function o(a){if(bb(o,a,a.currentStyle.backgroundAttachment==="fixed"&&!a.contains(A))){v();i.bgLeft(a);i.bgTop(a);m(a)}};function m(b){p.src=b.currentStyle.backgroundImage.slice(5,-2);var a=b.canHaveChildren?b:b.parentElement;a.appendChild(p);i.setOffsetLeft(b);i.setOffsetTop(b);a.removeChild(p)};function n(a){if(bb(n,a,bo(a))){T(a,"position","absolute");T(a,"left",a.currentStyle.left);T(a,"top",a.currentStyle.top);v();h.Layout.fixRight(a);j(a)}};function j(c,b){r.body.getBoundingClientRect();i.positionTop(c,b);i.positionLeft(c,b,true);if(!c.runtimeStyle.autoLeft&&c.currentStyle.marginLeft==="auto"&&c.currentStyle.right!=="auto"){var a=w.clientWidth-i.getPixelWidth(c,c.currentStyle.right)-i.getPixelWidth(c,c.runtimeStyle._3)-c.clientWidth;if(c.currentStyle.marginRight==="auto")a=parseInt(a/2);if(z(c.offsetParent))c.runtimeStyle.pixelLeft+=a;else c.runtimeStyle.shiftLeft=a}if(!c.runtimeStyle.fixedWidth)i.clipWidth(c);if(!c.runtimeStyle.fixedHeight)i.clipHeight(c)};function k(){var b=o.elements;for(var a in b)m(b[a]);b=n.elements;for(a in b){j(b[a],true);j(b[a],true)}l=0};var l;bw(function(){if(!l)l=setTimeout(k,100)});var i={},g=function(f){f.bgLeft=function(a){a.style.backgroundPositionX=a.currentStyle.backgroundPositionX;if(!z(a)){q(a,"backgroundPositionX","(parseInt(runtimeStyle.offsetLeft)+document."+y+".scrollLeft)||0")}};f.setOffsetLeft=function(b){var a=z(b)?"backgroundPositionX":"offsetLeft";b.runtimeStyle[a]=f.getOffsetLeft(b,b.style.backgroundPositionX)-b.getBoundingClientRect().left-b.clientLeft+2};f.getOffsetLeft=function(b,a){switch(a){case"left":case"top":return 0;case"right":case"bottom":return w.clientWidth-p.offsetWidth;case"center":return(w.clientWidth-p.offsetWidth)/2;default:if(S.test(a)){return parseInt((w.clientWidth-p.offsetWidth)*parseFloat(a)/100)}p.style.left=a;return p.offsetLeft}};f.clipWidth=function(d){var c=d.runtimeStyle.fixWidth;d.runtimeStyle.borderRightWidth="";d.runtimeStyle.width=c?f.getPixelWidth(d,c)+"px":"";if(d.currentStyle.width!=="auto"){var b=d.getBoundingClientRect();var a=d.offsetWidth-w.clientWidth+b.left-2;if(a>=0){d.runtimeStyle.borderRightWidth="0px";a=Math.max(B(d,d.currentStyle.width)-a,0);T(d,"width",a);return a}}};f.positionLeft=function(b,a){if(!a&&S.test(b.currentStyle.width)){b.runtimeStyle.fixWidth=b.currentStyle.width}if(b.runtimeStyle.fixWidth){b.runtimeStyle.width=f.getPixelWidth(b,b.runtimeStyle.fixWidth)}b.runtimeStyle.shiftLeft=0;b.runtimeStyle._3=b.currentStyle.left;b.runtimeStyle.autoLeft=b.currentStyle.right!=="auto"&&b.currentStyle.left==="auto";b.runtimeStyle.left="";b.runtimeStyle.screenLeft=f.getScreenLeft(b);b.runtimeStyle.pixelLeft=b.runtimeStyle.screenLeft;if(!a&&!z(b.offsetParent)){q(b,"pixelLeft","runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document."+y+".scrollLeft")}};f.getScreenLeft=function(c){var b=c.offsetLeft,a=1;if(c.runtimeStyle.autoLeft){b=w.clientWidth-c.offsetWidth-f.getPixelWidth(c,c.currentStyle.right)}if(c.currentStyle.marginLeft!=="auto"){b-=f.getPixelWidth(c,c.currentStyle.marginLeft)}while(c=c.offsetParent){if(c.currentStyle.position!=="static")a=-1;b+=c.offsetLeft*a}return b};f.getPixelWidth=function(b,a){return S.test(a)?parseInt(parseFloat(a)/100*w.clientWidth):B(b,a)}};eval("var _8="+bU(g));g(i);_8(i)})();if(s<7){var bF={backgroundColor:"transparent",backgroundImage:"none",backgroundPositionX:null,backgroundPositionY:null,backgroundRepeat:null,borderTopWidth:0,borderRightWidth:0,borderBottomWidth:0,borderLeftStyle:"none",borderTopStyle:"none",borderRightStyle:"none",borderBottomStyle:"none",borderLeftWidth:0,borderLeftColor:"#000",borderTopColor:"#000",borderRightColor:"#000",borderBottomColor:"#000",height:null,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,width:"100%"};h.CSS.addRecalc("overflow","visible",function(c){if(c.currentStyle.position==="absolute")return;if(c.parentNode.ie7_wrapped)return;if(h.Layout&&c.currentStyle["max-height"]!=="auto"){h.Layout.maxHeight(c)}if(c.currentStyle.marginLeft==="auto")c.style.marginLeft=0;if(c.currentStyle.marginRight==="auto")c.style.marginRight=0;var b=r.createElement(ci);b.ie7_wrapped=c;for(var a in bF){b.style[a]=c.currentStyle[a];if(bF[a]!=null){c.runtimeStyle[a]=bF[a]}}b.style.display="block";b.style.position="relative";c.runtimeStyle.position="absolute";c.parentNode.insertBefore(b,c);b.appendChild(c)})}function cP(){var q="xx-small,x-small,small,medium,large,x-large,xx-large".split(",");for(var o=0;o<q.length;o++){q[q[o]]=q[o-1]||"0.67em"}h.CSS.addFix(/(font(-size)?\s*:\s*)([\w.-]+)/,function(d,c,b,a){return c+(q[a]||a)});var m=/^\-/,n=/(em|ex)$/i,j=/em$/i,k=/ex$/i;B=function(c,b){if(bX.test(b))return parseInt(b)||0;var a=m.test(b)?-1:1;if(n.test(b))a*=i(c);l.style.width=a<0?b.slice(1):b;A.appendChild(l);b=a*l.offsetWidth;l.removeNode();return parseInt(b)};var l=bZ();function i(c){var b=1;l.style.fontFamily=c.currentStyle.fontFamily;l.style.lineHeight=c.currentStyle.lineHeight;while(c!=A){var a=c.currentStyle["ie7-font-size"];if(a){if(j.test(a))b*=parseFloat(a);else if(S.test(a))b*=(parseFloat(a)/100);else if(k.test(a))b*=(parseFloat(a)/2);else{l.style.fontSize=a;return 1}}c=c.parentElement}return b};h.CSS.addFix(/cursor\s*:\s*pointer/,"cursor:hand");h.CSS.addFix(/display\s*:\s*list-item/,"display:block");function g(d){var c=d.parentElement,b=c.offsetWidth-d.offsetWidth-f(c),a=(d.currentStyle["ie7-margin"]&&d.currentStyle.marginRight==="auto")||d.currentStyle["ie7-margin-right"]==="auto";switch(c.currentStyle.textAlign){case"right":b=a?parseInt(b/2):0;d.runtimeStyle.marginRight=b+"px";break;case"center":if(a)b=0;default:if(a)b/=2;d.runtimeStyle.marginLeft=parseInt(b)+"px"}};function f(a){return B(a,a.currentStyle.paddingLeft)+B(a,a.currentStyle.paddingRight)};h.CSS.addRecalc("margin(-left|-right)?","[^};]*auto",function(a){if(bb(g,a,a.parentElement&&a.currentStyle.display==="block"&&a.currentStyle.marginLeft==="auto"&&a.currentStyle.position!=="absolute")){g(a)}});bw(function(){for(var b in g.elements){var a=g.elements[b];a.runtimeStyle.marginLeft=a.runtimeStyle.marginRight="";g(a)}})};var cQ="\\([^)]+\\)";bS.add(/::(before|after)/,":$1");if(s<8){if(h.CSS.pseudoClasses)h.CSS.pseudoClasses+="|";h.CSS.pseudoClasses+="before|after|lang"+cQ;function cN(a){return a.replace(new RegExp("([{;\\s])("+bA.join("|")+")\\s*:\\s*([^;}]+)","g"),"$1$2:$3;ie7-$2:$3")};var cR=/[\w-]+\s*:\s*inherit/g;var cS=/ie7\-|\s*:\s*inherit/g;var cT=/\-([a-z])/g;function cU(b,a){return a.toUpperCase()};h.CSS.addRecalc("[\\w-]+","inherit",function(f,d){if(f.parentElement){var c=d.match(cR);for(var b=0;b<c.length;b++){var a=c[b].replace(cS,"");if(f.currentStyle["ie7-"+a]==="inherit"){a=a.replace(cT,cU);f.runtimeStyle[a]=f.parentElement.currentStyle[a]}}}},function(a){bA.push(bO(a.slice(1).split(":")[0]));return a});var br=new bB("focus",function(b){var a=arguments;h.CSS.addEventHandler(b,"onfocus",function(){br.unregister(a);br.register(a)});h.CSS.addEventHandler(b,"onblur",function(){br.unregister(a)});if(b==r.activeElement){br.register(a)}});var bG=new bB("active",function(b){var a=arguments;h.CSS.addEventHandler(b,"onmousedown",function(){bG.register(a)})});x(r,"onmouseup",function(){var b=bG.instances;for(var a in b)bG.unregister(b[a])});var cV=/^url\s*\(\s*([^)]*)\)$/;var cW={before0:"beforeBegin",before1:"afterBegin",after0:"afterEnd",after1:"beforeEnd"};var O=h.PseudoElement=t.extend({constructor:function(i,g,f){this.position=g;var d=f.match(O.CONTENT),c,b;if(d){d=d[1];c=d.split(/\s+/);for(var a=0;(b=c[a]);a++){c[a]=/^attr/.test(b)?{attr:b.slice(5,-1)}:b.charAt(0)==="'"?bn(b):ba(b)}d=c}this.content=d;this.base(i,ba(f))},init:function(){this.match=H(this.selector);for(var b=0;b<this.match.length;b++){var a=this.match[b].runtimeStyle;if(!a[this.position])a[this.position]={cssText:""};a[this.position].cssText+=";"+this.cssText;if(this.content!=null)a[this.position].content=this.content}},create:function(m){var n=m.runtimeStyle[this.position];if(n){var j=[].concat(n.content||"");for(var k=0;k<j.length;k++){if(typeof j[k]=="object"){j[k]=m.getAttribute(j[k].attr)}}j=j.join("");var l=j.match(cV);var i="overflow:hidden;"+n.cssText.replace(/'/g,'"');var g=cW[this.position+Number(m.canHaveChildren)];var f='ie7_pseudo'+O.count++;m.insertAdjacentHTML(g,F(O.ANON,this.className,f,i,l?"":j));if(l){var d=bn(l[1]);var c=r.getElementById(f);c.src=d;bq(c,"crop");var b=m.currentStyle.styleFloat!=="none";if(c.currentStyle.display==="inline"||b){if(s<7&&b&&m.canHaveChildren){m.runtimeStyle.display="inline";m.runtimeStyle.position="relative";c.runtimeStyle.position="absolute"}c.style.display="inline-block";if(m.currentStyle.styleFloat!=="none"){c.style.pixelWidth=m.offsetWidth}var a=new Image;a.onload=function(){c.style.pixelWidth=this.width;c.style.pixelHeight=Math.max(this.height,c.offsetHeight)};a.src=d}}m.runtimeStyle[this.position]=null}},recalc:function(){if(this.content==null)return;for(var a=0;a<this.match.length;a++){this.create(this.match[a])}},toString:function(){return"."+this.className+"{display:inline}"}},{CONTENT:/content\s*:\s*([^;]*)(;|$)/,ANON:"<ie7:! class='ie7_anon %1' id=%2 style='%3'>%4</ie7:!>",MATCH:/(.*):(before|after).*/,count:0});h._getLang=function(b){var a="";while(b&&b.nodeType===1){a=b.lang||b.getAttribute("lang")||"";if(a)break;b=b.parentNode}return a};bd=Y(bd,{":lang\\(([^)]+)\\)":"((ii=IE7._getLang(e))==='$1'||ii.indexOf('$1-')===0)&&"})}var cX=/^(submit|reset|button)$/;h.HTML.addRecalc("button,input",function(b){if(b.nodeName==="BUTTON"){var a=b.outerHTML.match(/ value="([^"]*)"/i);b.runtimeStyle.value=a?a[1]:""}if(b.type==="submit"){x(b,"onclick",function(){b.runtimeStyle.clicked=true;setTimeout("document.all."+b.uniqueID+".runtimeStyle.clicked=false",1)})}});h.HTML.addRecalc("form",function(c){x(c,"onsubmit",function(){for(var b,a=0;b=c[a];a++){if(cX.test(b.type)&&!b.disabled&&!b.runtimeStyle.clicked){b.disabled=true;setTimeout("document.all."+b.uniqueID+".disabled=false",1)}else if(b.nodeName==="BUTTON"&&b.type==="submit"){setTimeout("document.all."+b.uniqueID+".value='"+b.value+"'",1);b.value=b.runtimeStyle.value}}})});h.HTML.addRecalc("img",function(a){if(a.alt&&!a.title)a.title=""});if(s<8){h.CSS.addRecalc("border-spacing",be,function(a){if(a.currentStyle.borderCollapse!=="collapse"){a.cellSpacing=B(a,a.currentStyle["ie7-border-spacing"].split(" ")[0])}});h.CSS.addRecalc("box-sizing","content-box",h.Layout.boxSizing);h.CSS.addRecalc("box-sizing","border-box",h.Layout.borderBox)}if(s<8){var cY=/^image/i;h.HTML.addRecalc("object",function(a){if(cY.test(a.type)){a.body.style.cssText="margin:0;padding:0;border:none;overflow:hidden";return a}})}var K,H=(function(){var cZ=/^[>+~]/,bs=false;function da(d,c,b){d=bP(d);if(!c)c=r;var a=c;bs=cZ.test(d);if(bs){c=c.parentNode;d="*"+d}try{return m.create(d,bs)(c,b?null:[],a)}catch(ex){return b?null:[]}};var db=/^(\\.|[' >+~#.\[\]:*(),\w-\^|$=]|[^\x00-\xa0])+$/,dp=/^(href|src)$/,cg={"class":"className","for":"htmlFor"},dq=/\sie7_\w+/g,dc=/^(action|cite|codebase|data|dynsrc|href|longdesc|lowsrc|src|usemap|url)$/i;h._0=function(d,c){if(d.getAttributeNode){var b=d.getAttributeNode(c)}c=cg[c.toLowerCase()]||c;if(!b)b=d.attributes[c];var a=b&&b.specified;if(d[c]&&typeof d[c]=="boolean")return c.toLowerCase();if((a&&dc.test(c))||(!b&&C)||c==="value"||c==="type"){return d.getAttribute(c,2)}if(c==="style")return d.style.cssText.toLowerCase()||null;return a?String(b.nodeValue):null};var ch="colSpan,rowSpan,vAlign,dateTime,accessKey,tabIndex,encType,maxLength,readOnly,longDesc";Y(cg,cy(ch.toLowerCase().split(","),ch.split(",")));h._1=function(b,a){a+="Sibling";do{b=b[a];if(b&&b.nodeName>"@")break}while(b);return b};var dd=/(^|[, >+~])([#.:\[])/g,dr=/\)\{/g,de=/,/,ds=/^['"]/,df=/\\([\da-f]{2,2})/gi,dt=/last/i;h._9=function(d,c){var b=d.all[c]||null;if(!b||(b.nodeType&&h._0(b,"id")===c))return b;for(var a=0;a<b.length;a++){if(h._0(b[a],"id")===c)return b[a]}return null};var W=E.extend({dictionary:new cw({ident:/\-?(\\.|[_a-z]|[^\x00-\xa0])(\\.|[\w-]|[^\x00-\xa0])*/,combinator:/[\s>+~]/,operator:/[\^~|$*]?=/,nth_arg:/[+-]?\d+|[+-]?\d*n(?:\s*[+-]\s*\d+)?|even|odd/,tag:/\*|<#ident>/,id:/#(<#ident>)/,'class':/\.(<#ident>)/,pseudo:/\:([\w-]+)(?:\(([^)]+)\))?/,attr:/\[(<#ident>)(?:(<#operator>)((?:\\.|[^\[\]#.:])+))?\]/,negation:/:not\((<#tag>|<#id>|<#class>|<#attr>|<#pseudo>)\)/,sequence:/(\\.|[~*]=|\+\d|\+?\d*n\s*\+\s*\d|[^\s>+~,\*])+/,filter:/[#.:\[]<#sequence>/,selector:/[^>+~](\\.|[^,])*?/,grammar:/^(<#selector>)((,<#selector>)*)$/}),ignoreCase:true}),dg=new W({"\\\\.|[~*]\\s+=|\\+\\s+\\d":E.IGNORE,"\\[\\s+":"[","\\(\\s+":"(","\\s+\\)":")","\\s+\\]":"]","\\s*([,>+~]|<#operator>)\\s*":"$1","\\s+$":"","\\s+":" "});function dh(a){a=dg.parse(a.replace(df,"\\x$1")).replace(bv,"$1").replace(dd,"$1*$2");if(!db.test(a))bH();return a};function du(a){return a.replace(bR,di)};function di(b,a){return R[a]};var dj=/\{/g,dk=/\\{/g;function bI(a){return Array((a.replace(dk,"").match(dj)||"").length+1).join("}")};bd=new W(bd);var u=/:target/i,U=/:root/i;function P(b){var a="";if(U.test(b))a+=",R=d.documentElement";if(u.test(b))a+=",H=d.location;H=H&&H.hash.replace('#','')";if(a||b.indexOf("#")!==-1){a=",t=c.nodeType,d=t===9?c:c.ownerDocument||(c.document||c).parentWindow.document"+a}return"var ii"+a+";"};var V={" ":";while(e!=s&&(e=e.parentNode)&&e.nodeType===1){",">":".parentElement;if(e){","+":";while((e=e.previousSibling)&&!("+ca+"))continue;if(e){","~":";while((e=e.previousSibling)){"+cb},I=/\be\b/g;K=new W({"(?:(<#selector>)(<#combinator>))?(<#tag>)(<#filter>)?$":function(i,g,f,d,c){var b="";if(d!=="*"){var a=d.toUpperCase();b+="if(e.nodeName==='"+a+(a===d?"":"'||e.nodeName==='"+d)+"'){"}if(c){b+="if("+bd.parse(c).slice(0,-2)+"){"}b=b.replace(I,"e"+this.index);if(f){b+="var e=e"+(this.index++)+V[f];b=b.replace(I,"e"+this.index)}if(g){b+=this.parse(g)}return b}});var J="e0=IE7._9(d,'%1');if(e0){",y="var n=c.getElementsByTagName('%1');",v="if(r==null)return e0;r[k++]=e0;",p=1,z=new W({"^((?:<#selector>)?(?:<#combinator>))(<#tag>)(<#filter>)?$":true}),q={},o=new W({"^(<#tag>)#(<#ident>)(<#filter>)?( [^,]*)?$":function(i,g,f,d,c){var b=F(J,f),a="}";if(d){b+=K.parse(g+d);a=bI(b)}if(c){b+="s=c=e0;"+m.parse("*"+c)}else{b+=v}return b+a},"^([^#,]+)#(<#ident>)(<#filter>)?$":function(f,d,c,b){var a=F(J,c);if(d==="*"){a+=v}else{a+=K.parse(d+b)+v+"break"}return a+bI(a)},"^.*$":""}),m=new W({"<#grammar>":function(j,k,l){if(!this.groups)this.groups=[];var i=z.exec(" "+k);if(!i)bH();this.groups.push(i.slice(1));if(l){return this.parse(l.replace(de,""))}var g=this.groups,f=g[0][p];for(var b=1;i=g[b];b++){if(f!==i[p]){f="*";break}}var d="",c=v+"continue filtering;";for(var b=0;i=g[b];b++){K.index=0;if(f!=="*")i[p]="*";i=i.join("");if(i===" *"){d=c;break}else{i=K.parse(i);if(bs)i+="if(e"+K.index+"==s){";d+=i+c+bI(i)}}var a=f==="*";return(a?"var n=c.all;":F(y,f))+"filtering:while((e0=n[i++]))"+(a?cb.replace(I,"e0"):"{")+d+"}"},"^.*$":bH}),n=/\&\&(e\d+)\.nodeType===1(\)\{\s*if\(\1\.nodeName=)/g;m.create=function(c){if(!q[c]){c=dh(c);this.groups=null;K.index=0;var b=this.parse(c);this.groups=null;K.index=0;if(c.indexOf("#")!==-1){var a=o.parse(c);if(a){b="if(t===1||t===11|!c.getElementById){"+b+"}else{"+a+"}"}}b=b.replace(n,"$2");b=P(c)+ba(b);q[c]=new Function("return function(c,r,s){var i=0,k=0,e0;"+b+"return r}")()}return q[c]};return da})();function bH(){throw new SyntaxError("Invalid selector.");};h.loaded=true;(function(){try{if(!r.body)throw"continue";bt.doScroll("left")}catch(ex){setTimeout(arguments.callee,1);return}try{eval(bK.innerHTML)}catch(ex){}if(typeof IE7_PNG_SUFFIX=="object"){bf=IE7_PNG_SUFFIX}else{bf=new RegExp(bO(L.IE7_PNG_SUFFIX||"-trans.png")+"(\\?.*)?$","i")}A=r.body;w=C?A:bt;A.className+=" ie7_body";bt.className+=" ie7_html";if(C)cP();h.CSS.init();h.HTML.init();h.HTML.apply();h.CSS.apply();h.recalc()})()})(this,document);
import React, { useEffect } from 'react' import { PropTypes } from 'prop-types' import { connect } from 'react-redux' import { BrowserRouter as Router, Route } from 'react-router-dom' import { setToken, setUser } from 'src/reducers/loginReducer' import { Container } from 'semantic-ui-react' import LoginNav from 'src/components/presentational/LoginNav' import HomePage from 'src/components/pages/HomePage' // const { default: LoggedInContent } = await import(/* webpackPreload: true */'Containers/LoggedInContent') // const { default: Notification } = await import(/* webpackPreload: true */'Presentationals/Notification') // const { default: LoginPage } = await import(/* webpackPrefetch: true */'Pages/LoginPage') // const { default: SignupPage } = await import(/* webpackPrefetch: true */'Pages/SignupPage') import LoggedInContent from 'src/components/container/LoggedInContent' import Notification from 'src/components/presentational/Notification' import LoginPage from 'src/components/pages/LoginPage' import SignupPage from 'src/components/pages/SignupPage' const App = (props) => { const { setToken, setUser, login, } = props useEffect( () => { const loggedUserJSON = window.localStorage.getItem('loggedBlogAppUser') if (loggedUserJSON) { const user = JSON.parse(loggedUserJSON) setToken(user.token) setUser(user) } }, []) if (login.token === '') { return ( <Container aria-haspopup="dialog" > <Router> <Notification /> <section className="inert-on-modal"> <LoginNav /> <header> <h1>Favorite Blogs</h1> </header> <Route exact path='/' render={() => <> <main> <HomePage /> </main> <footer> <a href="https://www.freepik.com/vectors/business" className="credits"> Business vector created by pch.vector - www.freepik.com </a> </footer> </> }> </Route> <Route exact path='/login' render={() => <main> <LoginPage /> </main> }> </Route> <Route path='/signup' render={() => <main> <SignupPage /> </main> }> </Route> </section> </Router> </Container> ) } return ( <Container > <LoggedInContent /> </Container> ) } const mapStateToProps = (state) => { return { login: state.login, } } const mapDispatchToProps = { setToken, setUser, } App.propsTypes = { setToken: PropTypes.func.isRequired, setUser: PropTypes.func.isRequired, login: PropTypes.object.isRequired, } export default connect( mapStateToProps, mapDispatchToProps )(App)
module.exports = { assets: ['./assets/fonts/'] };
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); require("jasmine"); const HammerStick_1 = __importDefault(require("../../../patterns/bullish/HammerStick")); describe("HammerStick (bullish)", () => { it("default", () => { const input = [ { open: 26.13, high: 30.1, close: 30.1, low: 10.06 } ]; expect(HammerStick_1.default(input)).toBeTrue(); }); }); //# sourceMappingURL=HammerStickSpec.js.map
import memberDefined from './member-defined'; export default function memberDefinedAndNotNull(obj, member) { return memberDefined(obj, member) && obj[member] !== null; }
import firebase from 'firebase'; import * as React from 'react'; class FirebaseRecaptchaVerifierModal extends React.Component { verifier = null; setRef = (ref) => { if (ref) { if (this.props.appVerificationDisabledForTesting !== undefined) { firebase.auth().settings.appVerificationDisabledForTesting = !!this.props .appVerificationDisabledForTesting; } if (this.props.languageCode) { firebase.auth().languageCode = this.props.languageCode; } this.verifier = new firebase.auth.RecaptchaVerifier(ref, { size: this.props.attemptInvisibleVerification ? 'invisible' : 'normal', }); } else { this.verifier = null; } if (this.props.innerRef) { this.props.innerRef.current = this.verifier; } }; shouldComponentUpdate(nextProps) { return (this.props.appVerificationDisabledForTesting !== nextProps.appVerificationDisabledForTesting || this.props.attemptInvisibleVerification !== nextProps.attemptInvisibleVerification || this.props.languageCode !== nextProps.languageCode); } componentDidUpdate(prevProps) { if (this.props.innerRef !== prevProps.innerRef) { if (this.props.innerRef) { this.props.innerRef.current = this.verifier; } } } render() { const { attemptInvisibleVerification, appVerificationDisabledForTesting, languageCode, } = this.props; return (React.createElement("div", { style: styles.container, key: `${attemptInvisibleVerification ? 'invisible' : 'visible'}-${appVerificationDisabledForTesting ? 'testing' : 'regular'}-${languageCode ?? ''}`, id: "recaptcha-container", ref: this.setRef, dangerouslySetInnerHTML: { __html: '' } })); } } export default React.forwardRef((props, ref) => (React.createElement(FirebaseRecaptchaVerifierModal, { ...props, innerRef: ref }))); const styles = { // Ensure the reCAPTCHA badge is in front or other elements container: { zIndex: 1000 }, }; //# sourceMappingURL=FirebaseRecaptchaVerifierModal.web.js.map
#!/usr/bin/python # # Copyright 2010 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Unit tests to cover TrafficEstimator.""" __author__ = '[email protected] (Stan Grinberg)' import os import sys sys.path.insert(0, os.path.join('..', '..', '..')) import unittest from tests.adspygoogle.adwords import HTTP_PROXY from tests.adspygoogle.adwords import SERVER_V201109 from tests.adspygoogle.adwords import TEST_VERSION_V201109 from tests.adspygoogle.adwords import VERSION_V201109 from tests.adspygoogle.adwords import client class TrafficEstimatorServiceTestV201109(unittest.TestCase): """Unittest suite for TrafficEstimatorService using v201109.""" SERVER = SERVER_V201109 VERSION = VERSION_V201109 client.debug = False service = None def setUp(self): """Prepare unittest.""" print self.id() if not self.__class__.service: self.__class__.service = client.GetTrafficEstimatorService( self.__class__.SERVER, self.__class__.VERSION, HTTP_PROXY) def testKeywordTrafficEstimates(self): """Test whether we can estimate keyword traffic.""" selector = { 'campaignEstimateRequests': [{ 'adGroupEstimateRequests': [{ 'keywordEstimateRequests': [ { 'keyword': { 'xsi_type': 'Keyword', 'matchType': 'BROAD', 'text': 'mars cruise' }, 'maxCpc': { 'xsi_type': 'Money', 'microAmount': '1000000' } }, { 'keyword': { 'xsi_type': 'Keyword', 'matchType': 'PHRASE', 'text': 'cheap cruise' }, 'maxCpc': { 'xsi_type': 'Money', 'microAmount': '1000000' } }, { 'keyword': { 'xsi_type': 'Keyword', 'matchType': 'EXACT', 'text': 'cruise' }, 'maxCpc': { 'xsi_type': 'Money', 'microAmount': '1000000' } } ], 'maxCpc': { 'xsi_type': 'Money', 'microAmount': '1000000' } }], 'criteria': [ { 'xsi_type': 'Location', 'id': '2044' }, { 'xsi_type': 'Language', 'id': '1000' } ] }] } self.assert_(isinstance(self.__class__.service.Get(selector), tuple)) def makeTestSuiteV201109(): """Set up test suite using v201109. Returns: TestSuite test suite using v201109. """ suite = unittest.TestSuite() suite.addTests(unittest.makeSuite(TrafficEstimatorServiceTestV201109)) return suite if __name__ == '__main__': suites = [] if TEST_VERSION_V201109: suites.append(makeTestSuiteV201109()) if suites: alltests = unittest.TestSuite(suites) unittest.main(defaultTest='alltests')
module.exports = { future: { // removeDeprecatedGapUtilities: true, // purgeLayersByDefault: true, // defaultLineHeights: true, // standardFontWeights: true }, purge: [], theme: { extend: {}, spinner: (theme) => ({ default: { color: '#dae1e7', // color you want to make the spinner size: '1em', // size of the spinner (used for both width and height) border: '2px', // border-width of the spinner (shouldn't be bigger than half the spinner's size) speed: '500ms', // the speed at which the spinner should rotate }, }), }, variants: {}, plugins: [ require('tailwindcss-spinner')({ className: 'spinner', themeKey: 'spinner' }), ] }
'use strict' import Vue from 'vue' import axios from 'axios' import { Message } from 'element-ui' import store from '@/store' import { getToken } from '@/utils/auth' // create an axios instance const service = axios.create({ timeout: 5000 // request timeout }) service.interceptors.request.use(config => { // Do something before request is sent if (store.getters.token) { config.headers['Authorization'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改 } return config }, error => { // Do something with request error console.log(error) // for debug Promise.reject(error) }) // respone interceptor service.interceptors.response.use( (response) => { debugger; /** * 下面的注释为通过response自定义code来标示请求状态,当code返回如下情况为权限有问题,登出并返回到登录页 * 如通过xmlhttprequest 状态码标识 逻辑可写在下面error中 */ const res = response.data; if (res.code !== 1) { Message({ message: res.msg, type: 'error', duration: 5 * 1000 }); // 101:非法的token; 102:token为空; 100:Token 过期了; debugger; if (res.code === 100 || res.code === 101 || res.code === 102) { Vue.$confirm('你已被登出,可以取消继续留在该页面,或者重新登录', '确定登出', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => { store.dispatch('FedLogOut').then(() => { location.reload();// 为了重新实例化vue-router对象 避免bug }); }) } return Promise.reject('error'); } else { return response; } }, error => { console.log('err' + error)// for debug Message({ message: error.message, type: 'error', duration: 5 * 1000 }) return Promise.reject(error) }) const suffix = ''; // 后缀 const ajax = function (obj) { const _suffix = obj.suffix || suffix; let url = obj.url + _suffix; let type = obj.type ? obj.type.toUpperCase() : 'GET'; let headers = { headers: { "Content-Type": "application/json" }}; let params = obj.params || {}; switch (type) { case 'GET': return service.get(url, { params: params }); break; case 'POST': return service.post(url, params, headers); break; case 'PUT': return service.put(url, params, headers); break; case 'DELETE': return service.delete(url, params, headers); break; default: break; } } export default ajax;
from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_superuser( email="[email protected]", password="pass234" ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email="[email protected]", password="pass234", name="Test User" ) def test_users_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) def test_user_change_page(self): """Test that the user edit page works""" url = reverse("admin:core_user_change", args=[self.user.id]) res = self.client.get(url) self.assertEqual(res.status_code, 200) def test_create_user_page(self): """Test that the create user page works""" url = reverse("admin:core_user_add") res = self.client.get(url) self.assertEqual(res.status_code, 200)
import React, { PureComponent } from 'react'; import Person from './Person/Person'; class Persons extends PureComponent { constructor(props) { super(props); console.log('[Persons.js] Inside constructor()'); this.state = { persons: [ { id: '1', name: "Léo", age: 35 }, { id: '2', name: "Fabi", age: 32 }, { id: '3', name: "Guel", age: 18 } ], showPersons: false }; } componentWillMount() { console.log('[Persons.js] Inside componentWillMount()') } componentDidMount() { console.log('[Persons.js] Inside componentDidMount()') } componentWillReceiveProps(nextProps) { console.log('[UPDATE Persons.js] Inside componentWillReceiveProps()', nextProps); } render() { console.log('[Persons.js] Inside render()') return this.props.persons.map((person, index) => { return <Person click={() => this.props.clicked(index)} key={person.id} name={person.name} age={person.age} changed={(event) => this.props.changed(event, person.id)} /> }); } } export default Persons;
/** * Generate the docs ;-) * * @author Vojta Jina <[email protected]> */ var path = require('path'); var q = require('q'); var fs = require('q-io/fs'); var namp = require('namp'); var pug = require('pug'); var semver = require('semver'); module.exports = function(grunt) { // Helper Methods var urlFromFilename = function(fileName) { return fileName.replace(/^\d*-/, '').replace(/md$/, 'html'); }; var menuTitleFromFilename = function(fileName) { return fileName.replace(/^\d*-/, '').replace(/\.md$/, '').split(/[\s_-]/).map(function(word) { return word.charAt(0).toUpperCase() + word.substr(1); }).join(' '); }; var pageTitleFromFilename = menuTitleFromFilename; var editUrlFromFilenameAndSection = function(fileName, section) { return 'https://github.com/madeye/shadowsocks-org/edit/master/docs/' + section + '/' + fileName; }; var filterOnlyFiles = function(path, stat) { // ignore dot files like .DS_Store var filename = path.split('/').pop(); return stat.isFile() && !filename.match(/^\./); }; var sortByVersion = function(a, b) { return semver.lt(a + '.0', b + '.0'); }; // Register Grunt Task grunt.registerMultiTask('static', 'Generate a static homepage', function() { // Async Task var done = this.async(); var options = this.options({}); var template = options.template; grunt.verbose.writeflags(options, 'Options'); // Compile Jade templates and cache them. var tplCache = Object.create(null); var getJadeTpl = function(name) { if (!tplCache[name]) { var tplFileName = path.join(template, name + '.pug'); tplCache[name] = fs.read(tplFileName).then(function(content) { return pug.compile(content, {filename: tplFileName, cache: true, pretty: true}); }); } return tplCache[name]; }; this.files.forEach(function(f) { // Options var source = f.src[0]; var destination = f.dest[0]; grunt.log.writeln('Building files from \"' + source + '\" to \"' + destination + '\".'); // Read all the markdown files fs.listTree(source, filterOnlyFiles).then(function(files) { return q.all(files.sort().filter(function(filePath) { var parts = filePath.substr(source.length).replace(/^\//, '').split('/'); var fileName = parts.pop(); var re = /^Home.md$/i; return fileName.match(re) == null; }).map(function(filePath) { return fs.read(filePath).then(function(content) { var parts = filePath.substr(source.length).replace(/^\//, '').split('/'); var fileName = parts.pop(); var version = parts[0]; var section = parts[1] || null; var basePath = parts.join('/') + '/'; var string = new TextDecoder("utf-8").decode(content); var parsed = namp(string); return { url: basePath + urlFromFilename(fileName), editUrl: editUrlFromFilenameAndSection(fileName, section), layout: parsed.metadata.layout || 'layout', content: parsed.html, version: version, section: section, menuTitle: parsed.metadata.menuTitle || menuTitleFromFilename(fileName), showInMenu: parsed.metadata.showInMenu !== 'false', pageTitle: parsed.metadata.pageTitle || pageTitleFromFilename(fileName), editButton: parsed.metadata.editButton !== 'false' }; }); })); }).then(function(files) { // construct the menu tree var menu = Object.create(null); files.forEach(function(file) { if (!file.showInMenu) return; menu[file.version] = menu[file.version] || Object.create(null); menu[file.version][file.section] = menu[file.version][file.section] || []; menu[file.version][file.section].push(file); }); // generate and write all the html files var versions = Object.keys(menu).sort(sortByVersion); return q.all(files.map(function(file) { var fileUrl = path.join(destination, file.url); return q.all([getJadeTpl(file.layout), fs.makeTree(path.dirname(fileUrl))]).then(function(args) { var pugTpl = args[0]; return fs.write(fileUrl, pugTpl({ versions: versions, menu: menu[file.version], self: file })); }); })); }).then(function() { done(); }, function(e) { grunt.fail.fatal(e.stack); done(e); }); }); }); };
import React from 'react'; import PropTypes from 'prop-types'; import NotesContainer from '../Note/NoteContainer'; import Edit from '../../components/Edit'; import styles from './Lane.css'; class Lane extends React.Component { render(){ const { connectDropTarget, lane, laneNotes, updateLane, addNote, deleteLane, editLane } = this.props; const laneId = lane.id; return connectDropTarget( <div className={styles.laneContainer}> <div> <div> <button onClick={() => addNote({task: 'New Note'}, laneId)}>Add Note</button> </div> <Edit editing={lane.editing} value={lane.name} onValueClick={() => editLane(lane.id)} onUpdate={name => updateLane({ ...lane, name, editing: false })} /> <div> <button onClick={() => deleteLane(lane)}>Remove Lane</button> </div> </div> <NotesContainer notes={laneNotes} laneId={laneId} /> </div> ); } }; Lane.propTypes = { lane: PropTypes.object, laneNotes: PropTypes.array, addNote: PropTypes.func, updateLane: PropTypes.func, deleteLane: PropTypes.func, editLane: PropTypes.func, }; export default Lane;
""" NumPy ===== Provides 1. An array object of arbitrary homogeneous items 2. Fast mathematical operations over arrays 3. Linear Algebra, Fourier Transforms, Random Number Generation How to use the documentation ---------------------------- Documentation is available in two forms: docstrings provided with the code, and a loose standing reference guide, available from `the NumPy homepage <https://www.scipy.org>`_. We recommend exploring the docstrings using `IPython <https://ipython.org>`_, an advanced Python shell with TAB-completion and introspection capabilities. See below for further instructions. The docstring examples assume that `numpy` has been imported as `np`:: >>> import numpy as np Code snippets are indicated by three greater-than signs:: >>> x = 42 >>> x = x + 1 Use the built-in ``help`` function to view a function's docstring:: >>> help(np.sort) ... # doctest: +SKIP For some objects, ``np.info(obj)`` may provide additional help. This is particularly true if you see the line "Help on ufunc object:" at the top of the help() page. Ufuncs are implemented in C, not Python, for speed. The native Python help() does not know how to view their help, but our np.info() function does. To search for documents containing a keyword, do:: >>> np.lookfor('keyword') ... # doctest: +SKIP General-purpose documents like a glossary and help on the basic concepts of numpy are available under the ``doc`` sub-module:: >>> from numpy import doc >>> help(doc) ... # doctest: +SKIP Available subpackages --------------------- doc Topical documentation on broadcasting, indexing, etc. lib Basic functions used by several sub-packages. random Core Random Tools linalg Core Linear Algebra Tools fft Core FFT routines polynomial Polynomial tools testing NumPy testing tools f2py Fortran to Python Interface Generator. distutils Enhancements to distutils with support for Fortran compilers support and more. Utilities --------- test Run numpy unittests show_config Show numpy build configuration dual Overwrite certain functions with high-performance Scipy tools matlib Make everything matrices. __version__ NumPy version string Viewing documentation using IPython ----------------------------------- Start IPython with the NumPy profile (``ipython -p numpy``), which will import `numpy` under the alias `np`. Then, use the ``cpaste`` command to paste examples into the shell. To see which functions are available in `numpy`, type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow down the list. To view the docstring for a function, use ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view the source code). Copies vs. in-place operation ----------------------------- Most of the functions in `numpy` return a copy of the array argument (e.g., `np.sort`). In-place versions of these functions are often available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``. Exceptions to this rule are documented. """ import sys import warnings from ._globals import ModuleDeprecationWarning, VisibleDeprecationWarning from ._globals import _NoValue # We first need to detect if we're being called as part of the numpy setup # procedure itself in a reliable manner. try: __NUMPY_SETUP__ except NameError: __NUMPY_SETUP__ = False if __NUMPY_SETUP__: sys.stderr.write('Running from numpy source directory.\n') else: try: from numpy.__config__ import show as show_config except ImportError: msg = """Error importing numpy: you should not try to import numpy from its source directory; please exit the numpy source tree, and relaunch your python interpreter from there.""" raise ImportError(msg) from .version import git_revision as __git_revision__ from .version import version as __version__ __all__ = ['ModuleDeprecationWarning', 'VisibleDeprecationWarning'] # Allow distributors to run custom init code from . import _distributor_init from . import core from .core import * from . import compat from . import lib # NOTE: to be revisited following future namespace cleanup. # See gh-14454 and gh-15672 for discussion. from .lib import * from . import linalg from . import fft from . import polynomial from . import random from . import ctypeslib from . import ma from . import matrixlib as _mat from .matrixlib import * # Make these accessible from numpy name-space # but not imported in from numpy import * # TODO[gh-6103]: Deprecate these from builtins import bool, int, float, complex, object, str from .compat import long, unicode from .core import round, abs, max, min # now that numpy modules are imported, can initialize limits core.getlimits._register_known_types() __all__.extend(['__version__', 'show_config']) __all__.extend(core.__all__) __all__.extend(_mat.__all__) __all__.extend(lib.__all__) __all__.extend(['linalg', 'fft', 'random', 'ctypeslib', 'ma']) # These are added by `from .core import *` and `core.__all__`, but we # overwrite them above with builtins we do _not_ want to export. __all__.remove('long') __all__.remove('unicode') # Remove things that are in the numpy.lib but not in the numpy namespace # Note that there is a test (numpy/tests/test_public_api.py:test_numpy_namespace) # that prevents adding more things to the main namespace by accident. # The list below will grow until the `from .lib import *` fixme above is # taken care of __all__.remove('Arrayterator') del Arrayterator # Filter out Cython harmless warnings warnings.filterwarnings("ignore", message="numpy.dtype size changed") warnings.filterwarnings("ignore", message="numpy.ufunc size changed") warnings.filterwarnings("ignore", message="numpy.ndarray size changed") # oldnumeric and numarray were removed in 1.9. In case some packages import # but do not use them, we define them here for backward compatibility. oldnumeric = 'removed' numarray = 'removed' if sys.version_info[:2] >= (3, 7): # Importing Tester requires importing all of UnitTest which is not a # cheap import Since it is mainly used in test suits, we lazy import it # here to save on the order of 10 ms of import time for most users # # The previous way Tester was imported also had a side effect of adding # the full `numpy.testing` namespace # # module level getattr is only supported in 3.7 onwards # https://www.python.org/dev/peps/pep-0562/ def __getattr__(attr): if attr == 'testing': import numpy.testing as testing return testing elif attr == 'Tester': from .testing import Tester return Tester else: raise AttributeError("module {!r} has no attribute " "{!r}".format(__name__, attr)) def __dir__(): return list(globals().keys() | {'Tester', 'testing'}) else: # We don't actually use this ourselves anymore, but I'm not 100% sure that # no-one else in the world is using it (though I hope not) from .testing import Tester # Pytest testing from numpy._pytesttester import PytestTester test = PytestTester(__name__) del PytestTester def _sanity_check(): """ Quick sanity checks for common bugs caused by environment. There are some cases e.g. with wrong BLAS ABI that cause wrong results under specific runtime conditions that are not necessarily achieved during test suite runs, and it is useful to catch those early. See https://github.com/numpy/numpy/issues/8577 and other similar bug reports. """ try: x = ones(2, dtype=float32) if not abs(x.dot(x) - 2.0) < 1e-5: raise AssertionError() except AssertionError: msg = ("The current Numpy installation ({!r}) fails to " "pass simple sanity checks. This can be caused for example " "by incorrect BLAS library being linked in, or by mixing " "package managers (pip, conda, apt, ...). Search closed " "numpy issues for similar problems.") raise RuntimeError(msg.format(__file__)) _sanity_check() del _sanity_check def _mac_os_check(): """ Quick Sanity check for Mac OS look for accelerate build bugs. Testing numpy polyfit calls init_dgelsd(LAPACK) """ try: c = array([3., 2., 1.]) x = linspace(0, 2, 5) y = polyval(c, x) _ = polyfit(x, y, 2, cov=True) except ValueError: pass import sys if sys.platform == "darwin": with warnings.catch_warnings(record=True) as w: _mac_os_check() # Throw runtime error, if the test failed Check for warning and error_message error_message = "" if len(w) > 0: error_message = "{}: {}".format(w[-1].category.__name__, str(w[-1].message)) msg = ( "Polyfit sanity test emitted a warning, most likely due " "to using a buggy Accelerate backend. " "If you compiled yourself, " "see site.cfg.example for information. " "Otherwise report this to the vendor " "that provided NumPy.\n{}\n".format( error_message)) raise RuntimeError(msg) del _mac_os_check # We usually use madvise hugepages support, but on some old kernels it # is slow and thus better avoided. # Specifically kernel version 4.6 had a bug fix which probably fixed this: # https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff import os use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None) if sys.platform == "linux" and use_hugepage is None: use_hugepage = 1 kernel_version = os.uname().release.split(".")[:2] kernel_version = tuple(int(v) for v in kernel_version) if kernel_version < (4, 6): use_hugepage = 0 elif use_hugepage is None: # This is not Linux, so it should not matter, just enable anyway use_hugepage = 1 else: use_hugepage = int(use_hugepage) # Note that this will currently only make a difference on Linux core.multiarray._set_madvise_hugepage(use_hugepage)
import React, { useMemo } from "react"; import PropTypes from "prop-types"; import clsx from "clsx"; import deprecatedPropType from "@material-ui/core/utils/deprecatedPropType"; import { withStyles, useTheme } from "@material-ui/core"; import { MoreOptionsVertical } from "@hv/uikit-react-icons"; import { getPrevNextFocus, isKeypress, KeyboardCodes, useControlled } from "../utils"; import { HvButton, HvList, HvPanel, HvBaseDropdown, setId } from ".."; import styles from "./styles"; import withId from "../withId"; /** * A drop-down menu is a graphical control element, similar to a list box, that allows the user to choose a value from a list. */ const DropDownMenu = ({ id, classes, className, icon, placement = "right", dataList, disablePortal = false, onToggle, onToggleOpen, onClick, keepOpened = true, disabled = false, expanded, defaultExpanded = false, // eslint-disable-next-line category, ...others }) => { const [open, setOpen] = useControlled(expanded, Boolean(defaultExpanded)); const theme = useTheme(); const focusNodes = getPrevNextFocus(setId(id, "icon-button")); const listId = setId(id, "list"); const handleClose = (event) => { // this will only run if uncontrolled setOpen(false); onToggleOpen?.(false); onToggle?.(event, false); }; // If the ESCAPE key is pressed inside the list, the close handler must be called. const handleKeyDown = (event) => { if (isKeypress(event, KeyboardCodes.Tab)) { const node = event.shiftKey ? focusNodes.prevFocus : focusNodes.nextFocus; if (node) setTimeout(() => node.focus(), 0); handleClose(event); } event.preventDefault(); }; const setFocusToContent = (containerRef) => { containerRef?.getElementsByTagName("li")[0]?.focus(); }; const headerComponent = ( <HvButton icon category={category} id={setId(id, "icon-button")} className={clsx(classes.icon, { [classes.iconSelected]: open, })} aria-expanded={open} disabled={disabled} aria-label="Dropdown menu" > {icon || <MoreOptionsVertical color={disabled ? "atmo5" : undefined} />} </HvButton> ); const condensed = useMemo(() => dataList.every((el) => !el.icon), [dataList]); const popperStyle = { style: { zIndex: theme.zIndex.tooltip, width: null }, }; return ( <HvBaseDropdown id={id} className={clsx(className, classes.container)} classes={{ root: classes.root, container: classes.baseContainer }} expanded={open && !disabled} component={headerComponent} aria-haspopup="menu" placement={placement} variableWidth disablePortal={disablePortal} onToggle={(e, s) => { // this will only run if uncontrolled setOpen(s); onToggleOpen?.(s); onToggle?.(e, s); }} disabled={disabled} onContainerCreation={setFocusToContent} popperProps={popperStyle} {...others} > <HvPanel> <HvList id={listId} values={dataList} selectable={false} condensed={condensed} onClick={(event, item) => { if (!keepOpened) handleClose(event); onClick?.(event, item); }} onKeyDown={handleKeyDown} classes={{ root: classes.menuList }} /> </HvPanel> </HvBaseDropdown> ); }; DropDownMenu.propTypes = { /** * Class names to be applied. */ className: PropTypes.string, /** * Id to be applied to the root node. */ id: PropTypes.string, /** * A Jss Object used to override or extend the styles applied. */ classes: PropTypes.shape({ /** * Styles applied to the root. */ root: PropTypes.string, /** * Styles applied to the container. */ container: PropTypes.string, /** * Styles applied to the BaseDropdown container. */ baseContainer: PropTypes.string, /** * Styles applied to the icon. */ icon: PropTypes.string, /** * Styles applied to the icon when selected. */ iconSelected: PropTypes.string, /** * Styles applied to the list. */ menuList: PropTypes.string, }).isRequired, /** * Icon. */ icon: PropTypes.element, /** * A list containing the elements to be rendered. * * - label: The label of the element to be rendered. * - selected: The selection state of the element. * - disabled: The disabled state of the element. * - icon: The icon node to be rendered on the left. * - showNavIcon: If true renders the navigation icon on the right. */ dataList: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.node.isRequired, selected: PropTypes.bool, disabled: PropTypes.bool, icon: PropTypes.oneOfType([PropTypes.func, PropTypes.node]), showNavIcon: PropTypes.bool, }) ).isRequired, /** * Placement of the dropdown. */ placement: PropTypes.oneOf(["left", "right"]), /** * Disable the portal behavior. The children stay within it's parent DOM hierarchy. */ disablePortal: PropTypes.bool, /** * Function executed on toggle of the dropdown. Should receive the open status. */ onToggleOpen: deprecatedPropType( PropTypes.func, "Instead use the onToggle prop which receives the event" ), /** * Function executed on toggle of the dropdown. Should receive the open status. */ onToggle: PropTypes.func, /** * Function executed in each onClick. Should received the clicked element. */ onClick: PropTypes.func, /** * Keep the Dropdown Menu opened after clicking one option */ keepOpened: PropTypes.bool, /** * Defines if the component is disabled. */ disabled: PropTypes.bool, /** * If true it should be displayed open. */ expanded: PropTypes.bool, /** * When uncontrolled, defines the initial expanded state. */ defaultExpanded: PropTypes.bool, }; export default withStyles(styles, { name: "HvDropDownMenu" })(withId(DropDownMenu));