text
stringlengths
3
1.05M
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://@sbaseurl@/jsapi/jsapi/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details. //>>built require({cache:{"url:themes/TabTheme/panels/TabPanel/TabWidgetFrame.html":'\x3cdiv\x3e\r\n \x3cdiv class\x3d"title" data-dojo-attach-point\x3d"titleNode"\x3e\r\n \x3cdiv class\x3d"title-label" data-dojo-attach-point\x3d"titleLabelNode" title\x3d"${label}"\x3e\r\n ${label}\r\n \x3c/div\x3e\r\n \x3cdiv class\x3d"title-angle"\x3e\x3c/div\x3e\r\n \x3c/div\x3e\r\n \x3cdiv class\x3d"jimu-container" data-dojo-attach-point\x3d"containerNode"\x3e\x3c/div\x3e\r\n\x3c/div\x3e'}}); define("dojo/_base/declare dijit/_TemplatedMixin dojo/query dojo/dom-geometry dojo/text!./TabWidgetFrame.html jimu/BaseWidgetFrame".split(" "),function(e,f,g,d,h,k){return e([k,f],{baseClass:"jimu-widget-frame tab-widget-frame",templateString:h,borderWidth:1,resize:function(){var b=d.getMarginBox(this.domNode).h-2*this.borderWidth,c=d.getMarginBox(this.titleNode).h,a=b-c;0>b&&(b=0);0>=c&&(c=0);a=0>=a?"100%":a+"px";g(this.containerNode).style({height:a});this.widget&&"closed"!==this.widget.state&& this.widget.resize()}})});
/*! * FileInput Spanish Translations * * This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or * any HTML markup tags in the messages must not be converted or translated. * * @see http://github.com/kartik-v/bootstrap-fileinput * * NOTE: this file must be saved in UTF-8 encoding. */ (function ($) { "use strict"; $.fn.fileinputLocales['es'] = { fileSingle: 'archivo', filePlural: 'archivos', browseLabel: 'Examinar &hellip;', removeLabel: 'Quitar', removeTitle: 'Quitar archivos seleccionados', cancelLabel: 'Cancelar', cancelTitle: 'Abortar la subida en curso', uploadLabel: 'Subir archivo', uploadTitle: 'Subir archivos seleccionados', msgNo: 'No', msgNoFilesSelected: '', msgCancelled: 'Cancelado', msgZoomModalHeading: 'Vista previa detallada', msgSizeTooSmall: 'El archivo "{name}" (<b>{size} KB</b>) es demasiado pequeño y debe ser mayor de <b>{minSize} KB</b>.', msgSizeTooLarge: 'El archivo "{name}" (<b>{size} KB</b>) excede el tamaño máximo permitido de <b>{maxSize} KB</b>.', msgFilesTooLess: 'Debe seleccionar al menos <b>{n}</b> {files} a cargar.', msgFilesTooMany: 'El número de archivos seleccionados a cargar <b>({n})</b> excede el límite máximo permitido de <b>{m}</b>.', msgFileNotFound: 'Archivo "{name}" no encontrado.', msgFileSecured: 'No es posible acceder al archivo "{name}" porque estará siendo usado por otra aplicación o no tengamos permisos de lectura.', msgFileNotReadable: 'No es posible acceder al archivo "{name}".', msgFilePreviewAborted: 'Previsualización del archivo "{name}" cancelada.', msgFilePreviewError: 'Ocurrió un error mientras se leía el archivo "{name}".', msgInvalidFileName: 'Caracteres no válidos o no soportados en el nombre de archivo "{name}".', msgInvalidFileType: 'Tipo de archivo no válido para "{name}". Sólo se permiten archivos de tipo "{types}".', msgInvalidFileExtension: 'Extensión de archivo no válido para "{name}". Sólo se permiten archivos "{extensions}".', msgFileTypes: { 'image': 'image', 'html': 'HTML', 'text': 'text', 'video': 'video', 'audio': 'audio', 'flash': 'flash', 'pdf': 'PDF', 'object': 'object' }, msgUploadAborted: 'La carga de archivos se ha cancelado', msgUploadThreshold: 'Procesando...', msgValidationError: 'Error de validación', msgLoading: 'Subiendo archivo {index} de {files} &hellip;', msgProgress: 'Subiendo archivo {index} de {files} - {name} - {percent}% completado.', msgSelected: '{n} {files} seleccionado(s)', msgFoldersNotAllowed: 'Arrastre y suelte únicamente archivos. Omitida(s) {n} carpeta(s).', msgImageWidthSmall: 'El ancho de la imagen "{name}" debe ser de al menos {size} px.', msgImageHeightSmall: 'La altura de la imagen "{name}" debe ser de al menos {size} px.', msgImageWidthLarge: 'El ancho de la imagen "{name}" no puede exceder de {size} px.', msgImageHeightLarge: 'La altura de la imagen "{name}" no puede exceder de {size} px.', msgImageResizeError: 'No se pudieron obtener las dimensiones de la imagen para cambiar el tamaño.', msgImageResizeException: 'Error al cambiar el tamaño de la imagen.<pre>{errors}</pre>', msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!', ajaxOperations: { deleteThumb: 'file delete', uploadThumb: 'single file upload', uploadBatch: 'batch file upload', uploadExtra: 'form data upload' }, dropZoneTitle: 'Arrastre y suelte aquí los archivos &hellip;', dropZoneClickTitle: '<br>(o haga clic para seleccionar {files})', fileActionSettings: { removeTitle: 'Eliminar archivo', uploadTitle: 'Subir archivo', zoomTitle: 'Ver detalles', dragTitle: 'Mover / Reordenar', indicatorNewTitle: 'No subido todavía', indicatorSuccessTitle: 'Subido', indicatorErrorTitle: 'Error al subir', indicatorLoadingTitle: 'Subiendo...' }, previewZoomButtonTitles: { prev: 'Ver archivo anterior', next: 'Ver archivo siguiente', toggleheader: 'Mostrar encabezado', fullscreen: 'Mostrar a pantalla completa', borderless: 'Activar el modo sin bordes', close: 'Cerrar vista detallada' } }; })(window.jQuery);
import Ember from 'ember'; export default Ember.Helper.helper(function([target, property, val]) { Ember.set(target, property, val); });
# -*- coding: utf-8 -*- # Copyright (c) 2020, Dirk Chang and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import throw, _ def valid_sync_auth_code(auth_code=None): auth_code = auth_code or frappe.get_request_header("AuthorizationCode") if not auth_code: throw(_("AuthorizationCode is required in HTTP Header!")) frappe.logger(__name__).debug(_("IOT Chan Child Node AuthorizationCode as {0}").format(auth_code)) node_name = frappe.get_value("IOT Chan Child Node", {"auth_code": auth_code}, "node_name") if not node_name: throw(_("Authorization Code {0} is incorrect!").format(auth_code)) # form dict keeping form_dict = frappe.local.form_dict frappe.set_user('Administrator') frappe.local.form_dict = form_dict return frappe.get_doc('IOT Chan Child Node', node_name) @frappe.whitelist(allow_guest=True) def get_basic_info(): node = valid_sync_auth_code() from iot_chan.iot_chan.doctype.iot_chan_child_node.iot_chan_child_node import get_basic_info as _get_basic_info return _get_basic_info(node.name) @frappe.whitelist(allow_guest=True) def get_app_versions(app, base_version=0): node = valid_sync_auth_code() from iot_chan.iot_chan.doctype.iot_chan_child_node.iot_chan_child_node import list_app_versions return list_app_versions(node.name, app, node.beta_version_enabled, base_version)
'use strict'; const periodic = require('periodicjs'); const Promisie = require('promisie'); // const utility = require('../utilities/index'); const utilities = require('../utilities'); const UAParser = require('ua-parser-js'); // console.log({ getParameterized }); // let components = utilities.controllerhelper.components; const appSettings = periodic.settings; // console.log('periodic', periodic); appSettings.theme = periodic.settings.container.name; appSettings.themename = periodic.settings.container.name; const extsettings = utilities.reactapp().settings; const versions = utilities.controllerhelper.versions; // const themeSettings = periodic.settings.themeSettings; // const appenvironment = appSettings.application.environment; // const CoreController = periodic.core.controller; // const CoreUtilities = periodic.core.utilities; const logger = periodic.logger; /** * index page for react admin, that serves admin app * @param {object} req express request * @param {object} res express reponse * @return {null} does not return a value */ function admin_index(req, res, next) { if (req.query.format !== 'json' && req.query.format !== 'json&') { let viewname = 'admin/index'; if (req.headers && req.headers['user-agent']) { const UserAgentParser = new UAParser(); UserAgentParser.setUA(req.headers['user-agent']); const parseUserAgent = UserAgentParser.getResult(); if (parseUserAgent.browser.name === 'Chrome' && parseInt(parseUserAgent.browser.version, 10) < 40) { viewname = 'admin/support'; } else if (parseUserAgent.browser.name === 'IE' && parseInt(parseUserAgent.browser.version, 10) < 11) { viewname = 'admin/support'; } else if (parseUserAgent.browser.name === 'Firefox' && parseInt(parseUserAgent.browser.version, 10) < 41) { viewname = 'admin/support'; } else if (parseUserAgent.browser.name === 'Android Browser' && parseInt(parseUserAgent.browser.version, 10) < 5) { viewname = 'admin/support'; } if (parseUserAgent.browser.name === 'IE') { res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate'); } } // UserAgentParser.setUA(uastring); // logger.silly('render reactapp, ssr', extsettings.server_side_react); // logger.silly('render reactapp, req.query.format',req.query.format); let viewtemplate = { viewname, extname: '@digifi-los/reactapp', }; let viewdata = { pagedata: { // title: 'React Admin', // toplink: '&raquo; Multi-Factor Authenticator', }, user: req.user, reactapp: utilities.reactapp(), theme_name: appSettings.themename, // adminPostRoute: adminPostRoute }; if (extsettings.server_side_react) { return utilities.controllerhelper.pullConfigurationSettings(false) .then(() => { // logger.silly('req._parsedOriginalUrl.pathname', req._parsedOriginalUrl.pathname); // logger.silly({ unauthenticatedManifestSettings }); if (utilities.controllerhelper.unauthenticatedManifestSettings && utilities.controllerhelper.unauthenticatedManifestSettings.containers && Object.keys(utilities.controllerhelper.unauthenticatedManifestSettings.containers).length) { let layoutPath = utilities.settings.findMatchingRoute(utilities.controllerhelper.unauthenticatedManifestSettings.containers, req._parsedOriginalUrl.pathname); let manifest = (layoutPath) ? utilities.controllerhelper.unauthenticatedManifestSettings.containers[layoutPath] : false; // console.log({ layoutPath, manifest }); return utilities.ssr_manifest({ layoutPath, manifest, req_url: req._parsedOriginalUrl.pathname, basename: extsettings.basename, }); } else { return Promise.resolve({}, {}); } }) .then((results) => { let { body, pagedata, } = results; // console.log({ body, pagedata }); viewdata = Object.assign({}, viewdata, { body, }, { pagedata, }); periodic.core.controller.render(req, res, viewtemplate, viewdata); }) .catch(next); } else { periodic.core.controller.render(req, res, viewtemplate, viewdata); } } else { // console.log('SKIPPING reactapp req._parsedOriginalUrl.pathname', req._parsedOriginalUrl.pathname); // console.log('SKIPPING reactapp: req._parsedOriginalUrl.pathname.indexOf(/extensiondata/) === -1', req._parsedOriginalUrl.pathname.indexOf('/extensiondata/') === -1); // console.log('SKIPPING reactapp req.query.format !== json',req.query.format !== 'json'); // console.log('SKIPPING reactapp req.query.format !== json&',req.query.format !== 'json&'); next(); } } /** * Loads manifest configuration data and sends response with settings * @param {Object} req express request * @param {Object} res express reponse * @param {Function} next express next function */ function loadManifest(req, res, next) { return utilities.controllerhelper.pullConfigurationSettings((req.query && req.query.refresh) ? 'manifest' : false) .then(() => { let manifest = Object.assign({}, utilities.controllerhelper.manifestSettings); if (req.query && req.query.refresh_log && req.query.refresh_log !== 'false') { logger.silly('reloaded manifest', { manifest, }); } if (extsettings && extsettings.includeCoreData && extsettings.includeCoreData.manifest) { utilities.controllerhelper.setCoreDataConfigurations(); if (utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.manifest) manifest.containers = Object.assign({}, utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.manifest, manifest.containers); } if (req.query && req.query.initial) manifest.containers = utilities.controllerhelper.filterInitialManifest(manifest.containers, req.query.location); manifest.containers = utilities.controllerhelper.recursivePrivilegesFilter(Object.assign( (req.session && req.session.userprivilegesdata)? req.session.userprivilegesdata : {} ), manifest.containers, true); if (res && typeof res.send === 'function') { res.status(200).send({ result: 'success', status: 200, data: { versions: (req.query && req.query.initial) ? undefined : utilities.controllerhelper.versions, settings: manifest, }, }); } else return manifest; }) .catch(e => (typeof next === 'function') ? next(e) : Promisie.reject(e)); } /** * Loads unauthenticated manifest configuration data and sends response with settings * @param {Object} req express request * @param {Object} res express reponse * @param {Function} next express next function */ function loadUnauthenticatedManifest(req, res, next) { return utilities.controllerhelper.pullConfigurationSettings((req.query && req.query.refresh) ? 'unauthenticated' : false) .then(() => { let unauthenticated_manifest = Object.assign({}, utilities.controllerhelper.unauthenticatedManifestSettings); // console.log({ unauthenticated_manifest }); if (req.query && req.query.refresh_log && req.query.refresh_log !== 'false') { logger.silly('reloaded unauthenticated manifest', { unauthenticated_manifest, }); } if (extsettings && extsettings.includeCoreData && extsettings.includeCoreData.unauthenticated_manifest) { utilities.controllerhelper.setCoreDataConfigurations(); if (utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.unauthenticated_manifest) unauthenticated_manifest.containers = Object.assign({}, utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.unauthenticated_manifest, unauthenticated_manifest.containers); } if (req.query && req.query.initial) unauthenticated_manifest.containers = utilities.controllerhelper.filterInitialManifest(unauthenticated_manifest.containers, req.query.location); if (res && typeof res.send === 'function') { res.status(200).send({ result: 'success', status: 200, data: { versions: (req.query && req.query.initial) ? undefined : utilities.controllerhelper.versions, settings: unauthenticated_manifest, }, }); } else return unauthenticated_manifest; }) .catch(e => (typeof next === 'function') ? next(e) : Promisie.reject(e)); } /** * Loads component configuration data and sends response with settings * @param {object} req express request * @param {object} res express reponse * @param {Function} next express next function */ function loadComponent(req, res, next) { utilities.controllerhelper.pullComponentSettings((req.query && req.query.refresh) ? req.params.component : false) .then(() => { let component = utilities.controllerhelper.components[req.params.component] || { status: 'undefined', }; if (req.query && req.query.refresh_log && req.query.refresh_log !== 'false') logger.silly(`reloaded component ${ req.params.component }`, { component, }); res.status(200).send({ result: 'success', status: 200, data: { versions, settings: utilities.controllerhelper.assignComponentStatus(component), }, }); }) .catch(next); } /** * Loads user preference data and sends response with settings * @param {object} req express request * @param {object} res express reponse */ function loadUserPreferences(req, res) { if (res && typeof res.send === 'function') { res.status(200).send({ result: 'success', status: 200, data: { versions, settings: (req.user && req.user.extensionattributes && req.user.extensionattributes.preferences) ? req.user.extensionattributes.preferences : {}, }, }); } else return (req.user && req.user.extensionattributes && req.user.extensionattributes.preferences) ? req.user.extensionattributes.preferences : {}; } /** * Loads navigation configuration data and sends response with settings * @param {object} req express request * @param {object} res express reponse * @param {Function} next express next function */ function loadNavigation(req, res, next) { return utilities.controllerhelper.pullConfigurationSettings((req.query && req.query.refresh) ? 'navigation' : false) .then(() => { let navigation = Object.assign({}, utilities.controllerhelper.navigationSettings); if (req.query && req.query.refresh_log && req.query.refresh_log !== 'false') { logger.silly('reloaded navigation', { navigation, }); } if (extsettings && extsettings.includeCoreData && extsettings.includeCoreData.navigation) { utilities.controllerhelper.setCoreDataConfigurations(); if (utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.navigation && utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.navigation.layout) { navigation.layout = Object.assign({}, navigation.layout); navigation.layout.children = Object.assign([], navigation.layout.children); navigation.layout.children = navigation.layout.children.concat(utilities.controllerhelper.CORE_DATA_CONFIGURATIONS.navigation.layout.children || []); } } navigation.wrapper = extsettings.navigationLayout.wrapper; navigation.container = extsettings.navigationLayout.container; // console.log({ navigation }, 'req.session.userprivilegesdata', req.session.userprivilegesdata); navigation.layout = utilities.controllerhelper.recursivePrivilegesFilter(Object.assign((req.session && req.session.userprivilegesdata)? req.session.userprivilegesdata : {}), [navigation.layout, ])[0]; if (res && typeof res.send === 'function') { res.status(200).send({ result: 'success', status: 200, data: { versions, settings: navigation, }, }); } else return navigation; }) .catch(e => (typeof next === 'function') ? next(e) : Promisie.reject(e)); } function loadConfigurations(req, res) { // console.log('loading configs'); return utilities.controllerhelper.pullConfigurationSettings((req.query && req.query.refresh) ? true : false) .then(() => { if (req.query) delete req.query.refresh; return Promisie.parallel({ navigation: loadNavigation.bind(null, req), manifest: loadManifest.bind(null, req), unauthenticated_manifest: loadUnauthenticatedManifest.bind(null, req), preferences: loadUserPreferences.bind(null, req), }); }) .then(settings => { res.status(200).send({ result: 'success', status: 200, data: { settings, versions, }, }); }) .catch(e => { logger.error(e); res.status(500).send({ result: 'error', status: 500, data: { error: e.message, }, }); }); } module.exports = { index: admin_index, loadManifest, loadComponent, loadUserPreferences, loadNavigation, loadConfigurations, loadUnauthenticatedManifest, };
import unittest from datetime import datetime from src.naming_utils import NamingUtils class TestNamingUtils(unittest.TestCase): def test_prepare_text(self): result = NamingUtils.prepare_text(" a##b:c;d\\e.. ") self.assertEqual(result, "a.b.c.d.e") result = NamingUtils.prepare_text("123456789", 3) self.assertEqual(result, "123") result = NamingUtils.prepare_text(" äÜß gghJ lk ") self.assertEqual(result, "aUss.gghJ.lk") def test_prepare_email(self): result = NamingUtils.prepare_email(" reply_to@mail.de ") self.assertEqual(result, "reply_to.mail.de") result = NamingUtils.prepare_email(("reply_to@mail.de", )) self.assertEqual(result, "reply_to.mail.de") result = NamingUtils.prepare_email(("reply_to@mail.de", "reply_to2@mail.de", )) self.assertEqual(result, "reply_to.mail.de") result = NamingUtils.prepare_email(()) self.assertEqual(result, "") def test_prepare_subject(self): result = NamingUtils.prepare_subject(" fw: Fwd: Re: Fwd: fwD: re: 123 ") self.assertEqual(result, "123") def test_extract_attributes(self): class DummyMail: def __init__(self): self.uid = 123 self.date = datetime(2020, 9, 10, 18, 7, 6) self.subject = " Fwd: Re: Fwd: fwD: re: 123 " self.to = ("to@dummy.de", "to2@dummy.de", ) self.from_ = "from@dummy.de" mail = DummyMail() result = NamingUtils.extract_attributes(mail) self.assertEqual(result, { "DAY": "10", "FROM": "from.dummy.de", "HOUR": "18", "MINUTE": "07", "MONTH": "09", "SUBJECT": "123", "TO1": "to.dummy.de", "UID": "123", "YEAR": "2020" }) def test_format_path(self): attributes = { "DAY": "10", "FROM": "from.dummy.de", "HOUR": "18", "MINUTE": "07", "MONTH": "09", "SUBJECT": "subject", "TO1": "to.dummy.de", "UID": "123", "YEAR": "2020" } result = NamingUtils.format_path( "./__work__/{YEAR}-{MONTH}/{YEAR}{MONTH}{DAY}-OUT-{FROM}-{TO1}-{SUBJECT}.eml", attributes ) self.assertEqual(result, "./__work__/2020-09/20200910-OUT-from.dummy.de-to.dummy.de-subject.eml") result = NamingUtils.format_path("./__work__/{YEAR}-{MONTH}/{YEAR}{MONTH}{DAY}-OUT-{SUBJECT}.eml", attributes) self.assertEqual(result, "./__work__/2020-09/20200910-OUT-subject.eml") def test_join_path(self): result = NamingUtils.join_path("/home/x/mb", "./2020/11/x.eml") self.assertEqual(result, "/home/x/mb/./2020/11/x.eml") result = NamingUtils.join_path("/home/x/mb", "2020/11/x.eml") self.assertEqual(result, "/home/x/mb/2020/11/x.eml") result = NamingUtils.join_path("/home/x/mb/", "2020/11/x.eml") self.assertEqual(result, "/home/x/mb/2020/11/x.eml") result = NamingUtils.join_path("/home/x/mb/", "/2020/11/x.eml") self.assertEqual(result, "/2020/11/x.eml") # absolute path!
import UserApi from './userAPI'; export function signUpUser(credentials, history, redirect) { return function(dispatch) { return UserApi.signup(credentials) .then(response => { if(response.jwt) { localStorage.setItem("jwt", response.jwt); localStorage.setItem("user", JSON.stringify({ id: response.id, email: response.email, name: response.name, })); history.push(redirect) dispatch({ type: 'SUCCESS', // response = {jwt: KEY, id: INT, email: STR, name: STR} payload: response, }) } else { dispatch({ type: 'FAILURE', // response = {"error":"Email has already been taken"} payload: response.error, //this.props.user.error }) } }) .catch(error => { throw(error); }) } } export function loginUser(credentials, history, redirect) { return function(dispatch) { return UserApi.signin(credentials) .then(response => { if(response.jwt) { localStorage.setItem("jwt", response.jwt); localStorage.setItem("user", JSON.stringify({ id: response.id, email: response.email, name: response.name, })); history.push(redirect) dispatch({ type: 'SUCCESS', // response = {jwt: KEY, id: INT, email: STR, name: STR} payload: response, }) } else { dispatch({ type: 'FAILURE', //response = {"error":"Invalid username or password"} payload: response.errors, //this.props.user.error }) } }) .catch(error => { throw(error); }) } } export function signOutUser() { localStorage.removeItem("jwt"); localStorage.removeItem("user"); return(dispatch) => { dispatch({ type: 'SIGN_OUT' }); } }
'use strict'; import EventEmitter from 'eventemitter2'; let Victor = require('victor'); export default class Ball extends EventEmitter{ constructor(x, y, active, socket, puckImg){ super(); //roept super van eventemitter op anders zal het niet werken this.socket = socket; this.radius = 20; this.topSpeed = 19; this.mass = 38; this.active = active; this.puckImg = puckImg; this.ctx=document.querySelector('#canvas').getContext('2d'); this.location = new Victor(x, y); this.velocity = new Victor(0, 0); this.friction = new Victor(0.990, 0.990); this.oldVelocity = 0; this.playFieldWidth = 320; this.playFieldHeight = 492; } update(){ this.limitSpeed(this.topSpeed); this.location.add(this.velocity); this.checkEdges(); } draw(){ this.ctx.drawImage(this.puckImg, this.location.x-this.radius, this.location.y-this.radius, this.radius*2, this.radius*2); this.velocity.multiply(this.friction); } setVelocity(x, y){ this.velocity.x = x; this.velocity.y = y; } setAcceleration(x, y){ this.acceleration.x = x; this.acceleration.y = y; } limitSpeed(limit){ if(this.velocity.x > limit){ this.oldVelocity = this.velocity.x; this.velocity.x = limit; if(this.velocity.y < 0){ this.velocity.y = this.velocity.y / this.oldVelocity * limit; }else{ this.velocity.y = this.velocity.y / this.oldVelocity * limit; } }else if(this.velocity.x < -limit){ this.oldVelocity = this.velocity.x; this.velocity.x = -limit; if(this.velocity.y < 0){ this.velocity.y = this.velocity.y / this.oldVelocity * -limit; }else{ this.velocity.y = this.velocity.y / this.oldVelocity * -limit; } } if(this.velocity.y > limit){ this.oldVelocity = this.velocity.y; this.velocity.y = limit; if(this.velocity.x < 0){ this.velocity.x = this.velocity.x / this.oldVelocity * limit; }else{ this.velocity.x = this.velocity.x / this.oldVelocity * limit; } }else if(this.velocity.y < -limit){ this.oldVelocity = this.velocity.y; this.velocity.y = -limit; if(this.velocity.x < 0){ this.velocity.x = this.velocity.x / this.oldVelocity * -limit; }else{ this.velocity.x = this.velocity.x / this.oldVelocity * -limit; } } } checkEdges(){ if (this.location.y >= this.playFieldHeight - this.radius) { if(this.location.x > 58 && this.location.x < this.playFieldWidth-58){ //binnen in goal if(!this.active)return; if(this.location.y >= 495) { this.socket.emit('goal', this.socket.id, this.socket.opponent); this.active = false; } }else{ //naast goal tegen onderkant if(!this.active)return; this.velocity.y = this.velocity.y * -1; this.location.y = this.playFieldHeight-this.radius; } }else if (this.location.y <= this.radius && this.velocity.y < 0){ //bovenaan scherm, pass ball if(this.active){ let data = { location: this.location, velocity: this.velocity, from: this.socket.id, to: this.socket.opponent }; this.socket.emit('passBall', data); this.active = false; }else{ if (this.location.y <= -this.radius && this.velocity.y < 0){ this.socket.emit('hideBall', this.socket.id); } } } //zijkanten if ((this.location.x >= this.playFieldWidth-this.radius) || (this.location.x <= this.radius)) { this.velocity.x = this.velocity.x * -1; if(this.location.x > this.playFieldWidth-this.radius) this.location.x = this.playFieldWidth-this.radius; if(this.location.x < this.radius) this.location.x = this.radius; } } overTheEdge(){ //zijkanten if ((this.location.x >= this.playFieldWidth-this.radius) || (this.location.x <= this.radius) || this.location.y >= this.playFieldHeight - this.radius) { if(this.location.y >= this.playFieldHeight-this.radius){ if(this.location.x > 58 && this.location.x < this.playFieldWidth-58){ return false; } return true; } return true; }else{ return false; } } }
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright SquirrelNetwork import requests from core import decorators from bs4 import BeautifulSoup from core.utilities.message import message @decorators.delete.init def init(update, context): r = requests.get("https://distrowatch.com/random.php") parsed_html = BeautifulSoup(r.text, features="html.parser") distro_long_name = parsed_html.title.string[17:].lower() distro_name = distro_long_name.split()[0] distro_url = f'https://distrowatch.com/table.php?distribution={distro_name}' distro_message = "Here is a random linux distribution: {}".format(distro_url) message(update,context,distro_message)
import pandas as pd import yfinance as yf import datetime now = datetime.datetime.now() tickers = pd.read_csv('CNDX_holdings.csv', skiprows=2).dropna() tickers = tickers['Ticker'] precios = {} for i in tickers: pr = yf.download(i, start='2018-01-01', end=now, interval='1d') pr = pr.drop(['Adj Close'], axis=1) pr = pr.reset_index() precios[i] = pr NASDAQ = yf.download('^IXIC', start='2018-01-01', end=now, interval='1d') NASDAQ = NASDAQ.drop(['Adj Close'], axis=1) NASDAQ = NASDAQ.reset_index() rf = 0.015
# Copyright 2013: Mirantis 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. import multiprocessing import random import re import string import uuid from ceilometerclient import exc as ceilometer_exc from glanceclient import exc import mock from neutronclient.common import exceptions as neutron_exceptions from novaclient import exceptions as nova_exceptions import six from swiftclient import exceptions as swift_exceptions from rally.common import objects from rally.common import utils as rally_utils from rally import consts from rally.task import context from rally.task import scenario def generate_uuid(): return str(uuid.uuid4()) def generate_name(prefix="", length=12, choices=string.ascii_lowercase): """Generate pseudo-random name. :param prefix: str, custom prefix for genertated name :param length: int, length of autogenerated part of result name :param choices: str, chars that accurs in generated name :returns: str, pseudo-random name """ return prefix + "".join(random.choice(choices) for i in range(length)) def generate_mac(): """Generate pseudo-random MAC address. :returns: str, MAC address """ rand_str = generate_name(choices="0123456789abcdef", length=12) return ":".join(re.findall("..", rand_str)) def setup_dict(data, required=None, defaults=None): """Setup and validate dict scenario_base. on mandatory keys and default data. This function reduces code that constructs dict objects with specific schema (e.g. for API data). :param data: dict, input data :param required: list, mandatory keys to check :param defaults: dict, default data :returns: dict, with all keys set :raises: IndexError, ValueError """ required = required or [] for i in set(required) - set(data): raise IndexError("Missed: %s" % i) defaults = defaults or {} for i in set(data) - set(required) - set(defaults): raise ValueError("Unexpected: %s" % i) defaults.update(data) return defaults class FakeResource(object): def __init__(self, manager=None, name=None, status="ACTIVE", items=None, deployment_uuid=None, id=None): self.name = name or generate_uuid() self.status = status self.manager = manager self.uuid = generate_uuid() self.id = id or self.uuid self.items = items or {} self.deployment_uuid = deployment_uuid or generate_uuid() def __getattr__(self, name): # NOTE(msdubov): e.g. server.delete() -> manager.delete(server) def manager_func(*args, **kwargs): return getattr(self.manager, name)(self, *args, **kwargs) return manager_func def __getitem__(self, key): return self.items[key] class FakeServer(FakeResource): def suspend(self): self.status = "SUSPENDED" def lock(self): setattr(self, "OS-EXT-STS:locked", True) def unlock(self): setattr(self, "OS-EXT-STS:locked", False) class FakeImage(FakeResource): def __init__(self, manager=None, id="image-id-0", min_ram=0, size=0, min_disk=0, name=None): super(FakeImage, self).__init__(manager, id=id, name=name) self.min_ram = min_ram self.size = size self.min_disk = min_disk self.update = mock.MagicMock() class FakeMurano(FakeResource): pass class FakeFloatingIP(FakeResource): pass class FakeFloatingIPPool(FakeResource): pass class FakeTenant(FakeResource): def __init__(self, manager, name): super(FakeTenant, self).__init__(manager, name=name) class FakeUser(FakeResource): pass class FakeService(FakeResource): pass class FakeNetwork(FakeResource): pass class FakeFlavor(FakeResource): def __init__(self, id="flavor-id-0", manager=None, ram=0, disk=0, name="flavor-name-0"): super(FakeFlavor, self).__init__(manager, id=id) self.ram = ram self.disk = disk self.name = name class FakeKeypair(FakeResource): pass class FakeStack(FakeResource): pass class FakeDomain(FakeResource): pass class FakeQuotas(FakeResource): pass class FakeSecurityGroup(FakeResource): def __init__(self, manager=None, rule_manager=None, id=None, name=None): super(FakeSecurityGroup, self).__init__(manager, id=id, name=name) self.rule_manager = rule_manager @property def rules(self): return [rule for rule in self.rule_manager.list() if rule.parent_group_id == self.id] class FakeSecurityGroupRule(FakeResource): def __init__(self, name, **kwargs): super(FakeSecurityGroupRule, self).__init__(name) if "cidr" in kwargs: kwargs["ip_range"] = {"cidr": kwargs["cidr"]} del kwargs["cidr"] for key, value in kwargs.items(): self.items[key] = value setattr(self, key, value) class FakeAlarm(FakeResource): def __init__(self, manager=None, **kwargs): super(FakeAlarm, self).__init__(manager) self.meter_name = kwargs.get("meter_name") self.threshold = kwargs.get("threshold") self.state = kwargs.get("state", "fake-alarm-state") self.alarm_id = kwargs.get("alarm_id", "fake-alarm-id") self.state = kwargs.get("state", "ok") self.optional_args = kwargs.get("optional_args", {}) class FakeSample(FakeResource): def __init__(self, manager=None, **kwargs): super(FakeSample, self).__init__(manager) self.counter_name = kwargs.get("counter_name", "fake-counter-name") self.counter_type = kwargs.get("counter_type", "fake-counter-type") self.counter_unit = kwargs.get("counter_unit", "fake-counter-unit") self.counter_volume = kwargs.get("counter_volume", 100) @property def resource_id(self): return "fake-resource-id" def to_dict(self): return {"counter_name": self.counter_name, "counter_type": self.counter_type, "counter_unit": self.counter_unit, "counter_volume": self.counter_volume, "resource_id": self.resource_id} class FakeVolume(FakeResource): @property def _info(self): return {"id": "uuid"} class FakeVolumeType(FakeResource): pass class FakeVolumeTransfer(FakeResource): pass class FakeVolumeSnapshot(FakeResource): pass class FakeVolumeBackup(FakeResource): pass class FakeRole(FakeResource): pass class FakeQueue(FakeResource): def __init__(self, manager=None, name="myqueue"): super(FakeQueue, self).__init__(manager, name) self.queue_name = name self.messages = FakeMessagesManager(name) def post(self, messages): for msg in messages: self.messages.create(**msg) def messages(self): return self.messages.list() class FakeDbInstance(FakeResource): pass class FakeMessage(FakeResource): def __init__(self, manager=None, **kwargs): super(FakeMessage, self).__init__(manager) self.body = kwargs.get("body", "fake-body") self.ttl = kwargs.get("ttl", 100) class FakeAvailabilityZone(FakeResource): def __init__(self, manager=None): super(FakeAvailabilityZone, self).__init__(manager) self.zoneName = mock.MagicMock() self.zoneState = mock.MagicMock() self.hosts = mock.MagicMock() class FakeWorkbook(FakeResource): def __init__(self, manager=None): super(FakeWorkbook, self).__init__(manager) self.workbook = mock.MagicMock() class FakeObject(FakeResource): pass class FakeManager(object): def __init__(self): super(FakeManager, self).__init__() self.cache = {} self.resources_order = [] def get(self, resource_uuid): return self.cache.get(resource_uuid, None) def delete(self, resource_uuid): cached = self.get(resource_uuid) if cached is not None: cached.status = "DELETED" del self.cache[resource_uuid] self.resources_order.remove(resource_uuid) def _cache(self, resource): self.resources_order.append(resource.uuid) self.cache[resource.uuid] = resource return resource def list(self, **kwargs): return [self.cache[key] for key in self.resources_order] def find(self, **kwargs): for resource in self.cache.values(): match = True for key, value in kwargs.items(): if getattr(resource, key, None) != value: match = False break if match: return resource class FakeServerManager(FakeManager): def __init__(self, image_mgr=None): super(FakeServerManager, self).__init__() self.images = image_mgr or FakeImageManager() def get(self, resource_uuid): server = self.cache.get(resource_uuid, None) if server is not None: return server raise nova_exceptions.NotFound("Server %s not found" % (resource_uuid)) def _create(self, server_class=FakeServer, name=None): server = self._cache(server_class(self)) if name is not None: server.name = name return server def create(self, name, image_id, flavor_id, **kwargs): return self._create(name=name) def create_image(self, server, name): image = self.images._create() return image.uuid def add_floating_ip(self, server, fip): pass def remove_floating_ip(self, server, fip): pass def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETED" del self.cache[resource] self.resources_order.remove(resource) class FakeImageManager(FakeManager): def __init__(self): super(FakeImageManager, self).__init__() def get(self, resource_uuid): image = self.cache.get(resource_uuid, None) if image is not None: return image raise exc.HTTPNotFound("Image %s not found" % (resource_uuid)) def _create(self, image_class=FakeImage, name=None, id=None): image = self._cache(image_class(self)) image.owner = "dummy" image.id = image.uuid if name is not None: image.name = name return image def create(self, name, copy_from, container_format, disk_format): return self._create(name=name) def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETED" del self.cache[resource] self.resources_order.remove(resource) class FakePackageManager(FakeManager): def create(self, package_descr, package_arch, package_class=FakeMurano): package = self._cache(package_class(self)) package.name = package_arch.keys()[0] return package class FakeFloatingIPsManager(FakeManager): def create(self): return FakeFloatingIP(self) class FakeFloatingIPPoolsManager(FakeManager): def create(self): return FakeFloatingIPPool(self) class FakeTenantsManager(FakeManager): def create(self, name): return self._cache(FakeTenant(self, name)) def update(self, tenant_id, name=None, description=None): tenant = self.get(tenant_id) name = name or (tenant.name + "_updated") desc = description or (tenant.name + "_description_updated") tenant.name = name tenant.description = desc return self._cache(tenant) class FakeNetworkManager(FakeManager): def create(self, net_id): net = FakeNetwork(self) net.id = net_id return self._cache(net) class FakeFlavorManager(FakeManager): def create(self): flv = FakeFlavor(self) return self._cache(flv) class FakeKeypairManager(FakeManager): def create(self, name, public_key=None): kp = FakeKeypair(self) kp.name = name or kp.name return self._cache(kp) def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETED" del self.cache[resource] self.resources_order.remove(resource) class FakeStackManager(FakeManager): def create(self, name): stack = FakeStack(self) stack.name = name or stack.name return self._cache(stack) def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETE_COMPLETE" del self.cache[resource] self.resources_order.remove(resource) class FakeDomainManager(FakeManager): def create(self, name): domain = FakeDomain(self) domain.name = name or domain.name return self._cache(domain) def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETE_COMPLETE" del self.cache[resource] self.resources_order.remove(resource) class FakeNovaQuotasManager(FakeManager): def update(self, tenant_id, **kwargs): fq = FakeQuotas(self) return self._cache(fq) def delete(self, tenant_id): pass class FakeCinderQuotasManager(FakeManager): def update(self, tenant_id, **kwargs): fq = FakeQuotas(self) return self._cache(fq) def delete(self, tenant_id): pass class FakeSecurityGroupManager(FakeManager): def __init__(self, rule_manager=None): super(FakeSecurityGroupManager, self).__init__() self.rule_manager = rule_manager self.create("default") def create(self, name, description=""): sg = FakeSecurityGroup( manager=self, rule_manager=self.rule_manager) sg.name = name or sg.name sg.description = description return self._cache(sg) def to_dict(self, obj): return {"id": obj.id, "name": obj.name} def find(self, name, **kwargs): kwargs["name"] = name for resource in self.cache.values(): match = True for key, value in kwargs.items(): if getattr(resource, key, None) != value: match = False break if match: return resource raise nova_exceptions.NotFound("Security Group not found") def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETED" del self.cache[resource] self.resources_order.remove(resource) class FakeSecurityGroupRuleManager(FakeManager): def __init__(self): super(FakeSecurityGroupRuleManager, self).__init__() def create(self, parent_group_id, **kwargs): kwargs["parent_group_id"] = parent_group_id sgr = FakeSecurityGroupRule(self, **kwargs) return self._cache(sgr) class FakeUsersManager(FakeManager): def create(self, username, password, email, tenant_id): user = FakeUser(manager=self, name=username) user.name = username or user.name return self._cache(user) class FakeServicesManager(FakeManager): def list(self): return [] class FakeVolumeManager(FakeManager): def __init__(self): super(FakeVolumeManager, self).__init__() self.__volumes = {} self.__tenant_id = generate_uuid() def create(self, size=None, **kwargs): volume = FakeVolume(self) volume.size = size or 1 volume.name = kwargs.get("display_name", volume.name) volume.status = "available" volume.tenant_id = self.__tenant_id self.__volumes[volume.id] = volume return self._cache(volume) def list(self): return self.__volumes.values() def delete(self, resource): super(FakeVolumeManager, self).delete(resource.id) del self.__volumes[resource.id] class FakeVolumeTypeManager(FakeManager): def create(self, name): vol_type = FakeVolumeType(self) vol_type.name = name or vol_type.name return self._cache(vol_type) class FakeVolumeTransferManager(FakeManager): def __init__(self): super(FakeVolumeTransferManager, self).__init__() self.__volume_transfers = {} def list(self): return self.__volume_transfers.values() def create(self, name): transfer = FakeVolumeTransfer(self) transfer.name = name or transfer.name self.__volume_transfers[transfer.id] = transfer return self._cache(transfer) def delete(self, resource): super(FakeVolumeTransferManager, self).delete(resource.id) del self.__volume_transfers[resource.id] class FakeVolumeSnapshotManager(FakeManager): def __init__(self): super(FakeVolumeSnapshotManager, self).__init__() self.__snapshots = {} self.__tenant_id = generate_uuid() def create(self, name, force=False, display_name=None): snapshot = FakeVolumeSnapshot(self) snapshot.name = name or snapshot.name snapshot.status = "available" snapshot.tenant_id = self.__tenant_id self.__snapshots[snapshot.id] = snapshot return self._cache(snapshot) def list(self): return self.__snapshots.values() def delete(self, resource): super(FakeVolumeSnapshotManager, self).delete(resource.id) del self.__snapshots[resource.id] class FakeVolumeBackupManager(FakeManager): def __init__(self): super(FakeVolumeBackupManager, self).__init__() self.__backups = {} self.__tenant_id = generate_uuid() def create(self, name): backup = FakeVolumeBackup(self) backup.name = name or backup.name self.__backups[backup.id] = backup return self._cache(backup) def list(self): return self.__backups.values() def delete(self, resource): super(FakeVolumeBackupManager, self).delete(resource.id) del self.__backups[resource.id] class FakeRolesManager(FakeManager): def create(self, role_id, name): role = FakeRole(self) role.name = name role.id = role_id return self._cache(role) def roles_for_user(self, user, tenant): role = FakeRole(self) role.name = "admin" return [role, ] def add_user_role(self, user, role, tenant): pass class FakeAlarmManager(FakeManager): def get(self, alarm_id): alarm = self.find(alarm_id=alarm_id) if alarm: return [alarm] raise ceilometer_exc.HTTPNotFound( "Alarm with %s not found" % (alarm_id)) def update(self, alarm_id, **fake_alarm_dict_diff): alarm = self.get(alarm_id)[0] for attr, value in six.iteritems(fake_alarm_dict_diff): setattr(alarm, attr, value) return alarm def create(self, **kwargs): alarm = FakeAlarm(self, **kwargs) return self._cache(alarm) def delete(self, alarm_id): alarm = self.find(alarm_id=alarm_id) if alarm is not None: alarm.status = "DELETED" del self.cache[alarm.id] self.resources_order.remove(alarm.id) def get_state(self, alarm_id): alarm = self.find(alarm_id=alarm_id) if alarm is not None: return getattr(alarm, "state", "fake-alarm-state") def get_history(self, alarm_id): return ["fake-alarm-history"] def set_state(self, alarm_id, state): alarm = self.find(alarm_id=alarm_id) if alarm is not None: return setattr(alarm, "state", state) class FakeSampleManager(FakeManager): def create(self, **kwargs): sample = FakeSample(self, **kwargs) return [self._cache(sample)] def list(self): return ["fake-samples"] class FakeMeterManager(FakeManager): def list(self): return ["fake-meter"] class FakeMetricsManager(FakeManager): def list(self): return ["fake-metric"] class FakeCeilometerResourceManager(FakeManager): def get(self, resource_id): return ["fake-resource-info"] def list(self): return ["fake-resource"] class FakeStatisticsManager(FakeManager): def list(self, meter): return ["%s-statistics" % meter] class FakeQueryManager(FakeManager): def query(self, filter, orderby, limit): return ["fake-query-result"] class FakeQueuesManager(FakeManager): def __init__(self): super(FakeQueuesManager, self).__init__() self.__queues = {} def create(self, name): queue = FakeQueue(self, name) self.__queues[queue.name] = queue return self._cache(queue) def list(self): return self.__queues.values() def delete(self, queue): super(FakeQueuesManager, self).delete(queue.name) del self.__queues[queue.name] class FakeDbInstanceManager(FakeManager): def __init__(self): super(FakeDbInstanceManager, self).__init__() self.__db_instances = {} def create(self, name, flavor_id, size): instance = FakeDbInstance(self) instance.name = name or instance.name instance.flavor_id = flavor_id instance.size = size return self._cache(instance) def list(self): return self.__db_instances.values() def delete(self, resource): if not isinstance(resource, six.string_types): resource = resource.id cached = self.get(resource) if cached is not None: cached.status = "DELETE_COMPLETE" del self.cache[resource] self.resources_order.remove(resource) class FakeMessagesManager(FakeManager): def __init__(self, queue="myqueue"): super(FakeMessagesManager, self).__init__() self.__queue = queue self.__messages = {} def create(self, **kwargs): message = FakeMessage(self, **kwargs) self.__messages[message.id] = message return self._cache(message) def list(self): return self.__messages.values() def delete(self, message): super(FakeMessagesManager, self).delete(message.id) del self.__messages[message.id] class FakeAvailabilityZonesManager(FakeManager): def __init__(self): super(FakeAvailabilityZonesManager, self).__init__() self.zones = FakeAvailabilityZone() def list(self): return [self.zones] class FakeWorkbookManager(FakeManager): def __init__(self): super(FakeWorkbookManager, self).__init__() self.workbook = FakeWorkbook() def list(self): return [self.workbook] class FakeObjectManager(FakeManager): def get_account(self, **kwargs): containers = self.list() return (mock.MagicMock(), [{"name": con.name} for con in containers]) def get_container(self, name, **kwargs): container = self.find(name=name) if container is None: raise swift_exceptions.ClientException("Container GET failed") return (mock.MagicMock(), [{"name": obj} for obj in container.items]) def put_container(self, name, **kwargs): if self.find(name=name): raise swift_exceptions.ClientException("Container PUT failed") self._cache(FakeObject(name=name)) def delete_container(self, name, **kwargs): container = self.find(name=name) if container is None or len(container.items.keys()) > 0: raise swift_exceptions.ClientException("Container DELETE failed") self.delete(container.uuid) def get_object(self, container_name, object_name, **kwargs): container = self.find(name=container_name) if container is None or object_name not in container.items: raise swift_exceptions.ClientException("Object GET failed") return (mock.MagicMock(), container.items[object_name]) def put_object(self, container_name, object_name, content, **kwargs): container = self.find(name=container_name) if container is None: raise swift_exceptions.ClientException("Object PUT failed") container.items[object_name] = content return mock.MagicMock() def delete_object(self, container_name, object_name, **kwargs): container = self.find(name=container_name) if container is None or object_name not in container.items: raise swift_exceptions.ClientException("Object DELETE failed") del container.items[object_name] class FakeServiceCatalog(object): def get_endpoints(self): return {"image": [{"publicURL": "http://fake.to"}], "metering": [{"publicURL": "http://fake.to"}], "monitoring": [{"publicURL": "http://fake.to"}]} def url_for(self, **kwargs): return "http://fake.to" class FakeGlanceClient(object): def __init__(self): self.images = FakeImageManager() class FakeMuranoClient(object): def __init__(self): self.packages = FakePackageManager() class FakeCinderClient(object): def __init__(self): self.volumes = FakeVolumeManager() self.volume_types = FakeVolumeTypeManager() self.transfers = FakeVolumeTransferManager() self.volume_snapshots = FakeVolumeSnapshotManager() self.backups = FakeVolumeBackupManager() self.quotas = FakeCinderQuotasManager() class FakeNovaClient(object): def __init__(self, failed_server_manager=False): self.images = FakeImageManager() self.servers = FakeServerManager(self.images) self.floating_ips = FakeFloatingIPsManager() self.floating_ip_pools = FakeFloatingIPPoolsManager() self.networks = FakeNetworkManager() self.flavors = FakeFlavorManager() self.keypairs = FakeKeypairManager() self.security_group_rules = FakeSecurityGroupRuleManager() self.security_groups = FakeSecurityGroupManager( rule_manager=self.security_group_rules) self.quotas = FakeNovaQuotasManager() self.set_management_url = mock.MagicMock() self.availability_zones = FakeAvailabilityZonesManager() class FakeHeatClient(object): def __init__(self): self.stacks = FakeStackManager() class FakeDesignateClient(object): def __init__(self): self.domains = FakeDomainManager() class FakeKeystoneClient(object): def __init__(self): self.tenants = FakeTenantsManager() self.users = FakeUsersManager() self.roles = FakeRolesManager() self.project_id = "abc123" self.auth_url = "http://example.com:5000/v2.0/" self.auth_token = "fake" self.auth_user_id = generate_uuid() self.auth_tenant_id = generate_uuid() self.service_catalog = FakeServiceCatalog() self.services = FakeServicesManager() self.region_name = "RegionOne" self.auth_ref = mock.Mock() self.auth_ref.role_names = ["admin"] self.version = "v2.0" self.session = mock.Mock() self.authenticate = mock.MagicMock() def authenticate(self): return True def list_users(self): return self.users.list() def list_projects(self): return self.tenants.list() def list_services(self): return self.services.list() def list_roles(self): return self.roles.list() def delete_user(self, uuid): return self.users.delete(uuid) class FakeCeilometerClient(object): def __init__(self): self.alarms = FakeAlarmManager() self.meters = FakeMeterManager() self.resources = FakeCeilometerResourceManager() self.statistics = FakeStatisticsManager() self.samples = FakeSampleManager() self.query_alarms = FakeQueryManager() self.query_samples = FakeQueryManager() self.query_alarm_history = FakeQueryManager() class FakeMonascaClient(object): def __init__(self): self.metrics = FakeMetricsManager() class FakeNeutronClient(object): def __init__(self, **kwargs): self.__networks = {} self.__subnets = {} self.__routers = {} self.__ports = {} self.__pools = {} self.__vips = {} self.__fips = {} self.__healthmonitors = {} self.__tenant_id = kwargs.get("tenant_id", generate_uuid()) self.format = "json" self.version = "2.0" @staticmethod def _filter(resource_list, search_opts): return [res for res in resource_list if all(res[field] == value for field, value in search_opts.items())] def add_interface_router(self, router_id, data): subnet_id = data["subnet_id"] if (router_id not in self.__routers or subnet_id not in self.__subnets): raise neutron_exceptions.NeutronClientException subnet = self.__subnets[subnet_id] port = self.create_port( {"port": {"network_id": subnet["network_id"]}})["port"] port["device_id"] = router_id port["fixed_ips"].append({"subnet_id": subnet_id, "ip_address": subnet["gateway_ip"]}) return {"subnet_id": subnet_id, "tenant_id": port["tenant_id"], "port_id": port["id"], "id": router_id} def create_network(self, data): network = setup_dict(data["network"], defaults={"name": generate_name("net_"), "admin_state_up": True}) network_id = generate_uuid() network.update({"id": network_id, "status": "ACTIVE", "subnets": [], "provider:physical_network": None, "tenant_id": self.__tenant_id, "provider:network_type": "local", "router:external": True, "shared": False, "provider:segmentation_id": None}) self.__networks[network_id] = network return {"network": network} def create_pool(self, data): pool = setup_dict(data["pool"], required=["lb_method", "protocol", "subnet_id"], defaults={"name": generate_name("pool_"), "admin_state_up": True}) if pool["subnet_id"] not in self.__subnets: raise neutron_exceptions.NeutronClientException pool_id = generate_uuid() pool.update({"id": pool_id, "status": "PENDING_CREATE", "tenant_id": self.__tenant_id}) self.__pools[pool_id] = pool return {"pool": pool} def create_vip(self, data): vip = setup_dict(data["vip"], required=["protocol_port", "protocol", "subnet_id", "pool_id"], defaults={"name": generate_name("vip_"), "admin_state_up": True}) if (vip["subnet_id"] not in self.__subnets) or (vip["pool_id"] not in self.__pools): raise neutron_exceptions.NeutronClientException vip_id = generate_uuid() vip.update({"id": vip_id, "status": "PENDING_CREATE", "tenant_id": self.__tenant_id}) self.__vips[vip_id] = vip return {"vip": vip} def create_floatingip(self, data): fip = setup_dict(data["floatingip"], required=["floating_network"], defaults={"admin_state_up": True}) if (fip["floating_network"] not in self.__nets): raise neutron_exceptions.NeutronClientException fip_id = generate_uuid() fip.update({"id": fip_id, "tenant_id": self.__tenant_id}) self.__fips[fip_id] = fip return {"fip": fip} def create_health_monitor(self, data): healthmonitor = setup_dict(data["healthmonitor"], required=["type", "timeout", "delay", "max_retries"], defaults={"admin_state_up": True}) healthmonitor_id = generate_uuid() healthmonitor.update({"id": healthmonitor_id, "status": "PENDING_CREATE", "tenant_id": self.__tenant_id}) self.__healthmonitors[healthmonitor_id] = healthmonitor return {"healthmonitor": healthmonitor} def create_port(self, data): port = setup_dict(data["port"], required=["network_id"], defaults={"name": generate_name("port_"), "admin_state_up": True}) if port["network_id"] not in self.__networks: raise neutron_exceptions.NeutronClientException port_id = generate_uuid() port.update({"id": port_id, "status": "ACTIVE", "binding:host_id": "fakehost", "extra_dhcp_opts": [], "binding:vnic_type": "normal", "binding:vif_type": "ovs", "device_owner": "", "mac_address": generate_mac(), "binding:profile": {}, "binding:vif_details": {u"port_filter": True}, "security_groups": [], "fixed_ips": [], "device_id": "", "tenant_id": self.__tenant_id, "allowed_address_pairs": []}) self.__ports[port_id] = port return {"port": port} def create_router(self, data): router = setup_dict(data["router"], defaults={"name": generate_name("router_"), "external_gateway_info": None, "admin_state_up": True}) router_id = generate_uuid() router.update({"id": router_id, "status": "ACTIVE", "external_gateway_info": None, "tenant_id": self.__tenant_id}) self.__routers[router_id] = router return {"router": router} def create_subnet(self, data): subnet = setup_dict( data["subnet"], required=["network_id", "cidr", "ip_version"], defaults={"name": generate_name("subnet_"), "dns_nameservers": ["8.8.8.8", "8.8.4.4"]}) if subnet["network_id"] not in self.__networks: raise neutron_exceptions.NeutronClientException subnet_id = generate_uuid() subnet.update({"id": subnet_id, "enable_dhcp": True, "tenant_id": self.__tenant_id, "ipv6_ra_mode": None, "allocation_pools": [], "gateway_ip": re.sub("./.*$", "1", subnet["cidr"]), "ipv6_address_mode": None, "ip_version": 4, "host_routes": []}) self.__subnets[subnet_id] = subnet return {"subnet": subnet} def update_resource(self, resource_id, resource_dict, data): if resource_id not in resource_dict: raise neutron_exceptions.NeutronClientException self.resource_list[resource_id].update(data) def update_network(self, network_id, data): self.update_resource(network_id, self.__networks, data) def update_pool(self, pool_id, data): self.update_resource(pool_id, self.__pools, data) def update_vip(self, vip_id, data): self.update_resource(vip_id, self.__vips, data) def update_health_monitor(self, healthmonitor_id, data): self.update_resource(healthmonitor_id, self.__healthmonitors, data) def update_subnet(self, subnet_id, data): self.update_resource(subnet_id, self.__subnets, data) def update_port(self, port_id, data): self.update_resource(port_id, self.__ports, data) def update_router(self, router_id, data): self.update_resource(router_id, self.__routers, data) def delete_network(self, network_id): if network_id not in self.__networks: raise neutron_exceptions.NeutronClientException for port in self.__ports.values(): if port["network_id"] == network_id: # Network is in use by port raise neutron_exceptions.NeutronClientException del self.__networks[network_id] return "" def delete_pool(self, pool_id): if pool_id not in self.__pools: raise neutron_exceptions.NeutronClientException del self.__pools[pool_id] return "" def delete_vip(self, vip_id): if vip_id not in self.__vips: raise neutron_exceptions.NeutronClientException del self.__vips[vip_id] def delete_health_monitor(self, healthmonitor_id): if healthmonitor_id not in self.__healthmonitors: raise neutron_exceptions.NeutronClientException del self.__healthmonitors[healthmonitor_id] return "" def delete_floatingip(self, fip_id): if fip_id not in self.__fips: raise neutron_exceptions.NeutronClientException del self.__fips[fip_id] return "" def delete_port(self, port_id): if port_id not in self.__ports: raise neutron_exceptions.PortNotFoundClient if self.__ports[port_id]["device_owner"]: # Port is owned by some device raise neutron_exceptions.NeutronClientException del self.__ports[port_id] return "" def delete_router(self, router_id): if router_id not in self.__routers: raise neutron_exceptions.NeutronClientException for port in self.__ports.values(): if port["device_id"] == router_id: # Router has active port raise neutron_exceptions.NeutronClientException del self.__routers[router_id] return "" def delete_subnet(self, subnet_id): if subnet_id not in self.__subnets: raise neutron_exceptions.NeutronClientException for port in self.__ports.values(): for fip in port["fixed_ips"]: if fip["subnet_id"] == subnet_id: # Subnet has IP allocation from some port raise neutron_exceptions.NeutronClientException del self.__subnets[subnet_id] return "" def list_networks(self, **search_opts): nets = self._filter(self.__networks.values(), search_opts) return {"networks": nets} def list_pools(self, **search_opts): pools = self._filter(self.__pools.values(), search_opts) return {"pools": pools} def list_vips(self, **search_opts): vips = self._filter(self.__vips.values(), search_opts) return {"vips": vips} def list_health_monitors(self, **search_opts): healthmonitors = self._filter( self.__healthmonitors.values(), search_opts) return {"healthmonitors": healthmonitors} def list_ports(self, **search_opts): ports = self._filter(self.__ports.values(), search_opts) return {"ports": ports} def list_routers(self, **search_opts): routers = self._filter(self.__routers.values(), search_opts) return {"routers": routers} def list_subnets(self, **search_opts): subnets = self._filter(self.__subnets.values(), search_opts) return {"subnets": subnets} def list_floatingips(self, **search_opts): fips = self._filter(self.__fips.values(), search_opts) return {"floatingips": fips} def remove_interface_router(self, router_id, data): subnet_id = data["subnet_id"] if (router_id not in self.__routers or subnet_id not in self.__subnets): raise neutron_exceptions.NeutronClientException subnet = self.__subnets[subnet_id] for port_id, port in self.__ports.items(): if port["device_id"] == router_id: for fip in port["fixed_ips"]: if fip["subnet_id"] == subnet_id: del self.__ports[port_id] return {"subnet_id": subnet_id, "tenant_id": subnet["tenant_id"], "port_id": port_id, "id": router_id} raise neutron_exceptions.NeutronClientException def associate_health_monitor(self, pool_id, healthmonitor_id): if pool_id not in self.__pools: raise neutron_exceptions.NeutronClientException if healthmonitor_id not in self.__healthmonitors: raise neutron_exceptions.NeutronClientException self.__pools[pool_id]["pool"]["healthmonitors"] = healthmonitor_id return {"pool": self.__pools[pool_id]} def disassociate_health_monitor(self, pool_id, healthmonitor_id): if pool_id not in self.__pools: raise neutron_exceptions.NeutronClientException if healthmonitor_id not in self.__healthmonitors: raise neutron_exceptions.NeutronClientException del self.__pools[pool_id]["pool"]["healthmonitors"][healthmonitor_id] return "" class FakeIronicClient(object): def __init__(self): # TODO(romcheg):Fake Manager subclasses to manage BM nodes. pass class FakeSaharaClient(object): def __init__(self): self.job_executions = mock.MagicMock() self.jobs = mock.MagicMock() self.job_binary_internals = mock.MagicMock() self.job_binaries = mock.MagicMock() self.data_sources = mock.MagicMock() self.clusters = mock.MagicMock() self.cluster_templates = mock.MagicMock() self.node_group_templates = mock.MagicMock() self.setup_list_methods() def setup_list_methods(self): mock_with_id = mock.MagicMock() mock_with_id.id = 42 # First call of list returns a list with one object, the next should # empty after delete. self.job_executions.list.side_effect = [[mock_with_id], []] self.jobs.list.side_effect = [[mock_with_id], []] self.job_binary_internals.list.side_effect = [[mock_with_id], []] self.job_binaries.list.side_effect = [[mock_with_id], []] self.data_sources.list.side_effect = [[mock_with_id], []] self.clusters.list.side_effect = [[mock_with_id], []] self.cluster_templates.list.side_effect = [[mock_with_id], []] self.node_group_templates.list.side_effect = [[mock_with_id], []] class FakeZaqarClient(object): def __init__(self): self.queues = FakeQueuesManager() def queue(self, name, **kwargs): return self.queues.create(name, **kwargs) class FakeTroveClient(object): def __init__(self): self.instances = FakeDbInstanceManager() class FakeMistralClient(object): def __init__(self): self.workbook = FakeWorkbookManager() class FakeSwiftClient(FakeObjectManager): pass class FakeEC2Client(object): def __init__(self): pass class FakeClients(object): def __init__(self, endpoint_=None): self._nova = None self._glance = None self._keystone = None self._cinder = None self._neutron = None self._sahara = None self._heat = None self._designate = None self._ceilometer = None self._zaqar = None self._trove = None self._mistral = None self._swift = None self._murano = None self._monasca = None self._ec2 = None self._endpoint = endpoint_ or objects.Endpoint( "http://fake.example.org:5000/v2.0/", "fake_username", "fake_password", "fake_tenant_name") def keystone(self): if not self._keystone: self._keystone = FakeKeystoneClient() return self._keystone def verified_keystone(self): return self.keystone() def nova(self): if not self._nova: self._nova = FakeNovaClient() return self._nova def glance(self): if not self._glance: self._glance = FakeGlanceClient() return self._glance def cinder(self): if not self._cinder: self._cinder = FakeCinderClient() return self._cinder def neutron(self): if not self._neutron: self._neutron = FakeNeutronClient() return self._neutron def sahara(self): if not self._sahara: self._sahara = FakeSaharaClient() return self._sahara def heat(self): if not self._heat: self._heat = FakeHeatClient() return self._heat def designate(self): if not self._designate: self._designate = FakeDesignateClient() return self._designate def ceilometer(self): if not self._ceilometer: self._ceilometer = FakeCeilometerClient() return self._ceilometer def monasca(self): if not self._monasca: self._monasca = FakeMonascaClient() return self._monasca def zaqar(self): if not self._zaqar: self._zaqar = FakeZaqarClient() return self._zaqar def trove(self): if not self._trove: self._trove = FakeTroveClient() return self._trove def mistral(self): if not self._mistral: self._mistral = FakeMistralClient() return self._mistral def swift(self): if not self._swift: self._swift = FakeSwiftClient() return self._swift def murano(self): if not self._murano: self._murano = FakeMuranoClient() return self._murano def ec2(self): if not self._ec2: self._ec2 = FakeEC2Client() return self._ec2 class FakeRunner(object): CONFIG_SCHEMA = { "type": "object", "$schema": consts.JSON_SCHEMA, "properties": { "type": { "type": "string", "enum": ["fake"] }, "a": { "type": "string" }, "b": { "type": "number" } }, "required": ["type", "a"] } class FakeScenario(scenario.Scenario): def idle_time(self): return 0 def do_it(self, **kwargs): pass def with_output(self, **kwargs): return {"data": {"a": 1}, "error": None} def too_long(self, **kwargs): pass def something_went_wrong(self, **kwargs): raise Exception("Something went wrong") def raise_timeout(self, **kwargs): raise multiprocessing.TimeoutError() class FakeTimer(rally_utils.Timer): def duration(self): return 10 def timestamp(self): return 0 @context.configure(name="fake", order=1) class FakeContext(context.Context): CONFIG_SCHEMA = { "type": "object", "$schema": consts.JSON_SCHEMA, "properties": { "test": { "type": "integer" }, }, "additionalProperties": False } def __init__(self, context_obj=None): context_obj = context_obj or {} context_obj.setdefault("config", {}) context_obj["config"].setdefault("fake", None) context_obj.setdefault("task", mock.MagicMock()) super(FakeContext, self).__init__(context_obj) def setup(self): pass def cleanup(self): pass @context.configure(name="fake_hidden_context", order=1, hidden=True) class FakeHiddenContext(FakeContext): pass @context.configure(name="fake_user_context", order=1) class FakeUserContext(FakeContext): admin = { "id": "adminuuid", "endpoint": objects.Endpoint("aurl", "aname", "apwd", "atenant") } user = { "id": "uuid", "endpoint": objects.Endpoint("url", "name", "pwd", "tenant"), "tenant_id": "uuid" } tenants = {"uuid": {"name": "tenant"}} def __init__(self, ctx): super(FakeUserContext, self).__init__(ctx) self.context.setdefault("admin", FakeUserContext.admin) self.context.setdefault("users", [FakeUserContext.user]) self.context.setdefault("tenants", FakeUserContext.tenants) self.context.setdefault( "scenario_name", "NovaServers.boot_server_from_volume_and_delete") class FakeDeployment(dict): update_status = mock.Mock() class FakeTask(dict): def __init__(self, task=None, temporary=False, **kwargs): self.is_temporary = temporary self.task = task or kwargs self.set_failed = mock.Mock() def __getitem__(self, key): if key in self: return self[key] return self.task[key] def to_dict(self): return self
# Copyright The PyTorch Lightning team. # # 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. """ Tests to ensure that the training loop works with a dict (1.0) """ import pytest import torch from pytorch_lightning import Trainer from pytorch_lightning.core.lightning import LightningModule from tests.helpers.deterministic_model import DeterministicModel def test__eval_step__flow(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_step_called = True return acc def validation_step(self, batch, batch_idx): self.validation_step_called = True if batch_idx == 0: out = ['1', 2, torch.tensor(2)] if batch_idx > 0: out = {'something': 'random'} return out def backward(self, loss, optimizer, optimizer_idx): return LightningModule.backward(self, loss, optimizer, optimizer_idx) model = TestModel() model.validation_step_end = None model.validation_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=2, limit_val_batches=2, max_epochs=2, log_every_n_steps=1, weights_summary=None, ) trainer.fit(model) # make sure correct steps were called assert model.validation_step_called assert not model.validation_step_end_called assert not model.validation_epoch_end_called # make sure training outputs what is expected for batch_idx, batch in enumerate(model.train_dataloader()): break out = trainer.train_loop.run_training_batch(batch, batch_idx, 0) assert out.signal == 0 assert len(out.grad_norm_dic) == 0 and isinstance(out.grad_norm_dic, dict) train_step_out = out.training_step_output_for_epoch_end assert len(train_step_out) == 1 train_step_out = train_step_out[0][0] assert isinstance(train_step_out['minimize'], torch.Tensor) assert train_step_out['minimize'].item() == 171 # make sure the optimizer closure returns the correct things opt_closure_result = trainer.train_loop.training_step_and_backward( batch, batch_idx, 0, trainer.optimizers[0], trainer.hiddens ) assert opt_closure_result['loss'].item() == 171 def test__eval_step__eval_step_end__flow(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_step_called = True return acc def validation_step(self, batch, batch_idx): self.validation_step_called = True if batch_idx == 0: out = ['1', 2, torch.tensor(2)] if batch_idx > 0: out = {'something': 'random'} self.last_out = out return out def validation_step_end(self, out): self.validation_step_end_called = True assert self.last_out == out return out def backward(self, loss, optimizer, optimizer_idx): return LightningModule.backward(self, loss, optimizer, optimizer_idx) model = TestModel() model.validation_epoch_end = None trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=2, limit_val_batches=2, max_epochs=2, log_every_n_steps=1, weights_summary=None, ) trainer.fit(model) # make sure correct steps were called assert model.validation_step_called assert model.validation_step_end_called assert not model.validation_epoch_end_called # make sure training outputs what is expected for batch_idx, batch in enumerate(model.train_dataloader()): break out = trainer.train_loop.run_training_batch(batch, batch_idx, 0) assert out.signal == 0 assert len(out.grad_norm_dic) == 0 and isinstance(out.grad_norm_dic, dict) train_step_out = out.training_step_output_for_epoch_end assert len(train_step_out) == 1 train_step_out = train_step_out[0][0] assert isinstance(train_step_out['minimize'], torch.Tensor) assert train_step_out['minimize'].item() == 171 # make sure the optimizer closure returns the correct things opt_closure_result = trainer.train_loop.training_step_and_backward( batch, batch_idx, 0, trainer.optimizers[0], trainer.hiddens ) assert opt_closure_result['loss'].item() == 171 def test__eval_step__epoch_end__flow(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_step_called = True return acc def validation_step(self, batch, batch_idx): self.validation_step_called = True if batch_idx == 0: out = ['1', 2, torch.tensor(2)] self.out_a = out if batch_idx > 0: out = {'something': 'random'} self.out_b = out return out def validation_epoch_end(self, outputs): self.validation_epoch_end_called = True assert len(outputs) == 2 out_a = outputs[0] out_b = outputs[1] assert out_a == self.out_a assert out_b == self.out_b return {'no returns needed'} def backward(self, loss, optimizer, optimizer_idx): return LightningModule.backward(self, loss, optimizer, optimizer_idx) model = TestModel() model.validation_step_end = None trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=2, limit_val_batches=2, max_epochs=2, log_every_n_steps=1, weights_summary=None, ) with pytest.warns(UserWarning, match=r".*should not return anything as of 9.1.*"): trainer.fit(model) # make sure correct steps were called assert model.validation_step_called assert not model.validation_step_end_called assert model.validation_epoch_end_called def test__validation_step__step_end__epoch_end__flow(tmpdir): """ Tests that only training_step can be used """ class TestModel(DeterministicModel): def training_step(self, batch, batch_idx): acc = self.step(batch, batch_idx) acc = acc + batch_idx self.training_step_called = True return acc def validation_step(self, batch, batch_idx): self.validation_step_called = True if batch_idx == 0: out = ['1', 2, torch.tensor(2)] self.out_a = out if batch_idx > 0: out = {'something': 'random'} self.out_b = out self.last_out = out return out def validation_step_end(self, out): self.validation_step_end_called = True assert self.last_out == out return out def validation_epoch_end(self, outputs): self.validation_epoch_end_called = True assert len(outputs) == 2 out_a = outputs[0] out_b = outputs[1] assert out_a == self.out_a assert out_b == self.out_b return {'no returns needed'} def backward(self, loss, optimizer, optimizer_idx): return LightningModule.backward(self, loss, optimizer, optimizer_idx) model = TestModel() trainer = Trainer( default_root_dir=tmpdir, limit_train_batches=2, limit_val_batches=2, max_epochs=2, log_every_n_steps=1, weights_summary=None, ) with pytest.warns(UserWarning, match=r".*should not return anything as of 9.1.*"): trainer.fit(model) # make sure correct steps were called assert model.validation_step_called assert model.validation_step_end_called assert model.validation_epoch_end_called
const transD = {'T':'A','A':'U','G':'C','C':'G'} var aminos = `Ala GCU, GCC, GCA, GCG Leu UUA, UUG, CUU, CUC, CUA, CUG Arg CGU, CGC, CGA, CGG, AGA, AGG Lys AAA, AAG Asn AAU, AAC Met AUG Asp GAU, GAC Phe UUU, UUC Cys UGU, UGC Pro CCU, CCC, CCA, CCG Gln CAA, CAG Ser UCU, UCC, UCA, UCG, AGU, AGC Glu GAA, GAG Thr ACU, ACC, ACA, ACG Gly GGU, GGC, GGA, GGG Trp UGG His CAU, CAC Tyr UAU, UAC Ile AUU, AUC, AUA Val GUU, GUC, GUA, GUG Stop UAG, UGA, UAA` aminos = aminos.split('\n') function proteinSynthesis(dna) { const rna=[...dna].map(e=>transD[e]).join``.match(/.{3}|.{1,2}/g) const protein=rna.filter(e=>e.length==3).map(e=>aminos.filter(a=>a.includes(e))[0].match(/[a-z]+/gi)[0]) return [rna.join` `,protein.join` `]; }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Implements an incremental search field which can be shown and hidden. * Canonical implementation is <cr-search-field>. * @polymerBehavior */ var CrSearchFieldBehavior = { properties: { label: { type: String, value: '', }, clearLabel: { type: String, value: '', }, showingSearch: { type: Boolean, value: false, notify: true, observer: 'showingSearchChanged_', reflectToAttribute: true }, /** @private */ lastValue_: { type: String, value: '', }, }, /** * @return {string} The value of the search field. */ getValue: function() { return this.$.searchInput.value; }, /** * Sets the value of the search field. * @param {string} value */ setValue: function(value) { // Use bindValue when setting the input value so that changes propagate // correctly. this.$.searchInput.bindValue = value; this.onValueChanged_(value); }, showAndFocus: function() { this.showingSearch = true; this.focus_(); }, /** @private */ focus_: function() { this.$.searchInput.focus(); }, onSearchTermSearch: function() { this.onValueChanged_(this.getValue()); }, /** * Updates the internal state of the search field based on a change that has * already happened. * @param {string} newValue * @private */ onValueChanged_: function(newValue) { if (newValue == this.lastValue_) return; this.fire('search-changed', newValue); this.lastValue_ = newValue; }, onSearchTermKeydown: function(e) { if (e.key == 'Escape') this.showingSearch = false; }, /** @private */ showingSearchChanged_: function() { if (this.showingSearch) { this.focus_(); return; } this.setValue(''); this.$.searchInput.blur(); }, /** @private */ toggleShowingSearch_: function() { this.showingSearch = !this.showingSearch; }, };
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class MaintenanceConfigurationsOperations: """MaintenanceConfigurationsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.maintenance.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, resource_name: str, **kwargs ) -> "_models.MaintenanceConfiguration": """Get Configuration record. Get Configuration record. :param resource_group_name: Resource Group Name. :type resource_group_name: str :param resource_name: Maintenance Configuration Name. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: MaintenanceConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.maintenance.models.MaintenanceConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MaintenanceConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.MaintenanceError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MaintenanceConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}'} # type: ignore async def create_or_update( self, resource_group_name: str, resource_name: str, configuration: "_models.MaintenanceConfiguration", **kwargs ) -> "_models.MaintenanceConfiguration": """Create or Update configuration record. Create or Update configuration record. :param resource_group_name: Resource Group Name. :type resource_group_name: str :param resource_name: Maintenance Configuration Name. :type resource_name: str :param configuration: The configuration. :type configuration: ~azure.mgmt.maintenance.models.MaintenanceConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :return: MaintenanceConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.maintenance.models.MaintenanceConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MaintenanceConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.create_or_update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(configuration, 'MaintenanceConfiguration') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.MaintenanceError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MaintenanceConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}'} # type: ignore async def delete( self, resource_group_name: str, resource_name: str, **kwargs ) -> Optional["_models.MaintenanceConfiguration"]: """Delete Configuration record. Delete Configuration record. :param resource_group_name: Resource Group Name. :type resource_group_name: str :param resource_name: Maintenance Configuration Name. :type resource_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: MaintenanceConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.maintenance.models.MaintenanceConfiguration or None :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType[Optional["_models.MaintenanceConfiguration"]] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" # Construct URL url = self.delete.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.MaintenanceError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = None if response.status_code == 200: deserialized = self._deserialize('MaintenanceConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}'} # type: ignore async def update( self, resource_group_name: str, resource_name: str, configuration: "_models.MaintenanceConfiguration", **kwargs ) -> "_models.MaintenanceConfiguration": """Patch configuration record. Patch configuration record. :param resource_group_name: Resource Group Name. :type resource_group_name: str :param resource_name: Maintenance Configuration Name. :type resource_name: str :param configuration: The configuration. :type configuration: ~azure.mgmt.maintenance.models.MaintenanceConfiguration :keyword callable cls: A custom type or function that will be passed the direct response :return: MaintenanceConfiguration, or the result of cls(response) :rtype: ~azure.mgmt.maintenance.models.MaintenanceConfiguration :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.MaintenanceConfiguration"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self.update.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'resourceName': self._serialize.url("resource_name", resource_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(configuration, 'MaintenanceConfiguration') body_content_kwargs['content'] = body_content request = self._client.patch(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.MaintenanceError, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('MaintenanceConfiguration', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized update.metadata = {'url': '/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.Maintenance/maintenanceConfigurations/{resourceName}'} # type: ignore def list( self, **kwargs ) -> AsyncIterable["_models.ListMaintenanceConfigurationsResult"]: """Get Configuration records within a subscription. Get Configuration records within a subscription. :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListMaintenanceConfigurationsResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.maintenance.models.ListMaintenanceConfigurationsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListMaintenanceConfigurationsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2021-05-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListMaintenanceConfigurationsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.MaintenanceError, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list.metadata = {'url': '/subscriptions/{subscriptionId}/providers/Microsoft.Maintenance/maintenanceConfigurations'} # type: ignore
import Context from './Context'; function v8n() { return typeof Proxy !== undefined ? proxyContext(new Context()) : proxylessContext(new Context()); } // Custom rules let customRules = {}; v8n.extend = function(newRules) { Object.assign(customRules, newRules); }; v8n.clearCustomRules = function() { customRules = {}; }; function proxyContext(context) { return new Proxy(context, { get(obj, prop) { if (prop in obj) { return obj[prop]; } const newContext = proxyContext(context._clone()); if (prop in availableModifiers) { return newContext._applyModifier(availableModifiers[prop], prop); } if (prop in customRules) { return newContext._applyRule(customRules[prop], prop); } if (prop in availableRules) { return newContext._applyRule(availableRules[prop], prop); } }, }); } function proxylessContext(context) { const addRuleSet = (ruleSet, targetContext) => { Object.keys(ruleSet).forEach(prop => { targetContext[prop] = (...args) => { const newContext = proxylessContext(targetContext._clone()); const contextWithRuleApplied = newContext._applyRule( ruleSet[prop], prop, )(...args); return contextWithRuleApplied; }; }); return targetContext; }; const contextWithAvailableRules = addRuleSet(availableRules, context); const contextWithAllRules = addRuleSet( customRules, contextWithAvailableRules, ); Object.keys(availableModifiers).forEach(prop => { Object.defineProperty(contextWithAllRules, prop, { get: () => { const newContext = proxylessContext(contextWithAllRules._clone()); return newContext._applyModifier(availableModifiers[prop], prop); }, }); }); return contextWithAllRules; } const availableModifiers = { not: { simple: fn => value => !fn(value), async: fn => value => Promise.resolve(fn(value)) .then(result => !result) .catch(() => true), }, some: { simple: fn => value => { return split(value).some(item => { try { return fn(item); } catch (ex) { return false; } }); }, async: fn => value => { return Promise.all( split(value).map(item => { try { return fn(item).catch(() => false); } catch (ex) { return false; } }), ).then(result => result.some(Boolean)); }, }, every: { simple: fn => value => value !== false && split(value).every(fn), async: fn => value => Promise.all(split(value).map(fn)).then(result => result.every(Boolean)), }, }; function split(value) { if (typeof value === 'string') { return value.split(''); } return value; } const availableRules = { // Value equal: expected => value => value == expected, exact: expected => value => value === expected, // Types number: (allowInfinite = true) => value => typeof value === 'number' && (allowInfinite || isFinite(value)), integer: () => value => { const isInteger = Number.isInteger || isIntegerPolyfill; return isInteger(value); }, numeric: () => value => !isNaN(parseFloat(value)) && isFinite(value), string: () => testType('string'), boolean: () => testType('boolean'), undefined: () => testType('undefined'), null: () => testType('null'), array: () => testType('array'), object: () => testType('object'), instanceOf: instance => value => value instanceof instance, // Pattern pattern: expected => value => expected.test(value), lowercase: () => value => /^([a-z]+\s*)+$/.test(value), uppercase: () => value => /^([A-Z]+\s*)+$/.test(value), vowel: () => value => /^[aeiou]+$/i.test(value), consonant: () => value => /^(?=[^aeiou])([a-z]+)$/i.test(value), // Value at first: expected => value => value[0] == expected, last: expected => value => value[value.length - 1] == expected, // Length empty: () => value => value.length === 0, length: (min, max) => value => value.length >= min && value.length <= (max || min), minLength: min => value => value.length >= min, maxLength: max => value => value.length <= max, // Range negative: () => value => value < 0, positive: () => value => value >= 0, between: (a, b) => value => value >= a && value <= b, range: (a, b) => value => value >= a && value <= b, lessThan: n => value => value < n, lessThanOrEqual: n => value => value <= n, greaterThan: n => value => value > n, greaterThanOrEqual: n => value => value >= n, // Divisible even: () => value => value % 2 === 0, odd: () => value => value % 2 !== 0, includes: expected => value => ~value.indexOf(expected), schema: schema => testSchema(schema), // branching passesAnyOf: (...validations) => value => validations.some(validation => validation.test(value)), optional: createOptionalRule(false), optionalAsync: createOptionalRule(true), }; function createOptionalRule(asynchronous) { return (validation, considerTrimmedEmptyString = false) => value => { if ( considerTrimmedEmptyString && typeof value === 'string' && value.trim() === '' ) { return true; } if (value !== undefined && value !== null) { if (!asynchronous) { validation.check(value); } else { return validation.testAsync(value); } } return true; }; } function testType(expected) { return value => { return ( (Array.isArray(value) && expected === 'array') || (value === null && expected === 'null') || typeof value === expected ); }; } function isIntegerPolyfill(value) { return ( typeof value === 'number' && isFinite(value) && Math.floor(value) === value ); } function testSchema(schema) { return { simple: value => { const causes = []; Object.keys(schema).forEach(key => { const nestedValidation = schema[key]; try { nestedValidation.check((value || {})[key]); } catch (ex) { ex.target = key; causes.push(ex); } }); if (causes.length > 0) { throw causes; } return true; }, async: value => { const causes = []; const nested = Object.keys(schema).map(key => { const nestedValidation = schema[key]; return nestedValidation.testAsync((value || {})[key]).catch(ex => { ex.target = key; causes.push(ex); }); }); return Promise.all(nested).then(() => { if (causes.length > 0) { throw causes; } return true; }); }, }; } export default v8n;
# imports import yfinance as yf from pandas_datareader import data as pdr import pandas as pd # list all stocks url = 'ftp://ftp.nasdaqtrader.com/SymbolDirectory/nasdaqlisted.txt' df = pd.read_csv(url, sep = "|") def lookup_fn(df, key_row, key_col): try: return df.iloc[key_row][key_col] except IndexError: return 0 movementlist = [] for stock in df['Symbol'].tolist()[:5]: # get history thestock = yf.Ticker(stock) hist = thestock.history(period="5d") # print(stock) low = float(10000) high = float(0) # print(thestock.info) for day in hist.itertuples(index=True, name='Pandas'): if day.Low < low: low = day.Low if high < day.High: high = day.High deltapercent = 100 * (high - low)/low Open = lookup_fn(hist, 0, "Open") # some error handling: if len(hist >=5): Close = lookup_fn(hist, 4, "Close") else : Close = Open if(Open == 0): deltaprice = 0 else: deltaprice = 100 * (Close - Open) / Open print(stock+" "+str(deltapercent)+ " "+ str(deltaprice)) pair = [stock, deltapercent, deltaprice] movementlist.append(pair) for entry in movementlist: if entry[1] > float(100): print(entry) # High risers: def lookup_stockinfo(thestock): try: return thestock.info except IndexError: return 0 cutoff = float(80) for entry in movementlist: if entry[2] > cutoff: print("\n"+ str(entry)) thestock = yf.Ticker(str(entry[0])) if entry[0]=='HJLIW': print("no info") else: a = lookup_stockinfo(thestock) if a == 0 or a == None or a == "": print("no info") else: print(a) print('Up '+ str(entry[2]) + "%") print(str(a['sector'])) print(str(a['longBusinessSummary'])) print("year high "+ str(a['fiftyTwoWeekHigh']))
'use strict'; module.exports = { /** * When editing your questions pay attention to your punctuation. Make sure you use question marks or periods. * Make sure the first answer is the correct one. Set at least ANSWER_COUNT answers, any extras will be shuffled in. */ "QUESTIONS_EN_GB" : [ { "Who was the founder of the DevOps K C Meetup?": [ "Aaron Blythe", "Jerry Maguire", "Dane Hammer", "Chris Stein", "Ryan McNair", "Chase Pettet" ] }, { "Which presenters first coined the term devops?": [ "Patrick Debois and Andrew Clay Shafer", "Jez Humble and Dave Farley", "Adrian Cockcroft and Brendan Gregg", "Baron Schwartz and Anders Wallgren", "Damon Edward and John Willis", "Gene Kim and Kris Buytaert", "John Allspaw and Martin Fowler" ] }, { "Where was the first devops days held?": [ "Ghent, Belgium", "Chicago, Illinois", "Paris, France", "Berlin, Germany", "Minneapolis, Minnesota", "San Francisco, California", "Kansas City, Missouri" ] }, { "What year was the first devops days?": [ "2009", "2008", "2010", "2011", "2007", "2006" ] }, { "What year was the devops k c meetup started?": [ "2013", "2012", "2011", "2014", "2015", "2010", "2009" ] }, { "What year was the first devops days k c?": [ "2016", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2017" ] }, { "Who was the first presenter at the devops k c meetup?": [ "Adam Jacob", "Aaron Blythe", "Andrew Clay Shaffer", "Doug Cutting" ] }, { "What day was the first devops k c meetup?": [ "April Fools\' Day", "Saint Patrick\'s Day", "Columbus Day", "Valentine's Day", "May Day", "Ides of March" ] }, { "Who hosts arrested devops?": [ "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "John Willis and Damon Edwards", "J. Paul Reed, Seth Thomas, and Pete Cheslock" ] }, { "Who hosts devops cafe?": [ "John Willis and Damon Edwards", "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "J. Paul Reed, Seth Thomas, and Pete Cheslock" ] }, { "Who hosts the ship show?": [ "J. Paul Reed, Seth Thomas, and Pete Cheslock", "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "John Willis and Damon Edwards" ] }, { "In Chef, what is the fundamental element of configuration in an organization?": [ "Recipe", "Cookbook", "Role", "Chef server", "chef client" ] }, { "Which of the following is Puppet’s cross-platform profiling library?": [ "Facter", "Geppetto", "Puppet D B", "Hiera" ] }, { "In what format are Ansible playbooks?": [ "yaml", "json", "xml", "sdl" ] }, { "Vagrantfile syntax is from which language?": [ "Ruby", "Java", "Python", "Go", "JavaScript", "C" ] }, { "Which of these is not a principle of DevOps?": [ "Rewarding firefighting", "Resilient Engineering", "Amplifying of feedback loops", "Reduction of Tech Debt" ] }, { "Which of these statements are true?": [ "All other answers" "DevOps looks to extend Dev into Production", "DevOps looks to embed Development into IT Operations", "DevOps looks to embed IT Operations into Development" ] }, { "Which phrase does DevOps accurately describe, encompass, embody?": [ "All other answers", "DevOps is a cultural approach to improving communications between the development and operations teams in an organization", "DevOps is the term describing someone who moderates the exchanges between development and operations", "DevOps is the name of a job for an employee who can work as both a systems engineer and a developer" ] }, { "The DevOps movement is an outgrowth of which software development methodology?": [ "Agile", "Waterfall", "Promise-based algorithms", "Test-driven development and model-driven development" ] }, { "Which of these tools is not associated with DevOps?": [ "Liebert M.P.X.", "Chef", "Puppet", "Ansible" ] }, { "The DevOps movement has evolved to solve which problem?": [ "All other answers", "Increasingly complex, virtualized I.T. environments", "The need for multiple rapidly timed software releases; sometimes many in one day", "The traditional siloed approach to app development and deployment" ] }, { "Which of these would not rank as a primary concern when choosing a DevOps tool?": [ "Integration with environmental sensors on the data center floor", "Compatibility with cloud platforms, such as Amazon Web Services", "Reporting and control integration with collaboration tools", "Communication with other management or monitoring tools" ] }, { "Where does Ansible come from?": [ "It's a fictional device capable of instantaneous or superluminal communication.", "It's a fictional device used to communicate in multiple languages", "It's a fictional device that builds robots in the epic thriller \"Ada, and the sons of Atlantis", "It's a fictional character who battled culinary artisans and marionettes for supremacy over a great empire" ] }, { "What does Kubernetes mean?": [ "Helmsman", "Captain", "Docker", "Orchestrator" ] }, { "Who created Kubernetes?": [ "Google", "Red Hat", "Amazon", "Twitter" ] }, { "Who created Mesos?": [ "Twitter", "Google", "Amazon", "Facebook" ] }, { "Hudson was forked, what's the name of the fork?": [ "Jenkins", "Alfred", "Watson", "Jensen" ] }, { "What was the term coined to describe actions taken through group text messaging platforms?": [ "chat ops", "talk ops", "slack ops", "google ops" ] }, { "Which is not a part of the ELK stack?": [ "Elastic Search", "Log Stash", "Kibana", "logregator" ] }, { "Which is not an Atlassian product?": [ "Remedy", "JIRA", "Confluence", "Bamboo", "crucible", "hip chat" ] } ], "QUESTIONS_EN_US" : [ { "Who was the founder of the DevOps K C Meetup?": [ "Aaron Blythe", "Jerry Maguire", "Dane Hammer", "Chris Stein", "Ryan McNair", "Chase Pettet" ] }, { "Which presenters first coined the term devops?": [ "Patrick Debois and Andrew Clay Shafer", "Jez Humble and Dave Farley", "Adrian Cockcroft and Brendan Gregg", "Baron Schwartz and Anders Wallgren", "Damon Edward and John Willis", "Gene Kim and Kris Buytaert", "John Allspaw and Martin Fowler" ] }, { "Where was the first devops days held?": [ "Ghent, Belgium", "Chicago, Illinois", "Paris, France", "Berlin, Germany", "Minneapolis, Minnesota", "San Francisco, California", "Kansas City, Missouri" ] }, { "What year was the first devops days?": [ "2009", "2008", "2010", "2011", "2007", "2006" ] }, { "What year was the devops k c meetup started?": [ "2013", "2012", "2011", "2014", "2015", "2010", "2009" ] }, { "What year was the first devops days k c?": [ "2016", "2015", "2014", "2013", "2012", "2011", "2010", "2009", "2017" ] }, { "Who was the first presenter at the devops k c meetup?": [ "Adam Jacob", "Aaron Blythe", "Andrew Clay Shaffer", "Doug Cutting" ] }, { "What day was the first devops k c meetup?": [ "April Fools\' Day", "Saint Patrick\'s Day", "Columbus Day", "Valentine's Day", "May Day", "Ides of March" ] }, { "Who hosts arrested devops?": [ "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "John Willis and Damon Edwards", "J. Paul Reed, Seth Thomas, and Pete Cheslock" ] }, { "Who hosts devops cafe?": [ "John Willis and Damon Edwards", "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "J. Paul Reed, Seth Thomas, and Pete Cheslock" ] }, { "Who hosts the ship show?": [ "J. Paul Reed, Seth Thomas, and Pete Cheslock", "Matt Stratton, Trevor Hess, and Bridget Kromhout", "Matt Stratton and Bridget Kromhout", "John Willis and Damon Edwards" ] }, { "In Chef, what is the fundamental element of configuration in an organization?": [ "Recipe", "Cookbook", "Role", "Chef server", "chef client" ] }, { "Which of the following is Puppet’s cross-platform profiling library?": [ "Facter", "Geppetto", "Puppet D B", "Hiera" ] }, { "In what format are Ansible playbooks?": [ "yaml", "json", "xml", "sdl" ] }, { "Vagrantfile syntax is from which language?": [ "Ruby", "Java", "Python", "Go", "JavaScript", "C" ] }, { "Which of these is not a principle of DevOps?": [ "Rewarding firefighting", "Resilient Engineering", "Amplifying of feedback loops", "Reduction of Tech Debt" ] }, { "Which of these statements are true?": [ "All other answers", "DevOps looks to extend Dev into Production", "DevOps looks to embed Development into IT Operations", "DevOps looks to embed IT Operations into Development" ] }, { "Which phrase does DevOps accurately describe, encompass, embody?": [ "All other answers", "DevOps is a cultural approach to improving communications between the development and operations teams in an organization", "DevOps is the term describing someone who moderates the exchanges between development and operations", "DevOps is the name of a job for an employee who can work as both a systems engineer and a developer" ] }, { "The DevOps movement is an outgrowth of which software development methodology?": [ "Agile", "Waterfall", "Promise-based algorithms", "Test-driven development and model-driven development" ] }, { "Which of these tools is not associated with DevOps?": [ "Liebert M.P.X.", "Chef", "Puppet", "Ansible" ] }, { "The DevOps movement has evolved to solve which problem?": [ "All other answers", "Increasingly complex, virtualized I.T. environments", "The need for multiple rapidly timed software releases; sometimes many in one day", "The traditional siloed approach to app development and deployment" ] }, { "Which of these would not rank as a primary concern when choosing a DevOps tool?": [ "Integration with environmental sensors on the data center floor", "Compatibility with cloud platforms, such as Amazon Web Services", "Reporting and control integration with collaboration tools", "Communication with other management or monitoring tools" ] }, { "Where does Ansible come from?": [ "It's a fictional device capable of instantaneous or superluminal communication.", "It's a fictional device used to communicate in multiple languages", "It's a fictional device that builds robots in the epic thriller \"Ada, and the sons of Atlantis", "It's a fictional character who battled culinary artisans and marionettes for supremacy over a great empire" ] }, { "What does Kubernetes mean?": [ "Helmsman", "Captain", "Docker", "Orchestrator" ] }, { "Who created Kubernetes?": [ "Google", "Red Hat", "Amazon", "Twitter" ] }, { "Who created Mesos?": [ "Twitter", "Google", "Amazon", "Facebook" ] }, { "Hudson was forked, what's the name of the fork?": [ "Jenkins", "Alfred", "Watson", "Jensen" ] }, { "What was the term coined to describe actions taken through group text messaging platforms?": [ "chat ops", "talk ops", "slack ops", "google ops" ] }, { "Which is not a part of the ELK stack?": [ "Elastic Search", "Log Stash", "Kibana", "logregator" ] }, { "Which is not an Atlassian product?": [ "Remedy", "JIRA", "Confluence", "Bamboo", "crucible", "hip chat" ] }, { "What is a two-pizza team?": [ "A team that can be reasonably fed by two pizzas. Popularized by Amazon.", "A team that can make two pizzas at a time. Popularized by Domino's", "One very large man, popularized by Chris Chirstie", "A team of people who can each make one pizza. Popularized by Little Caesars" ] } ] };
export var options = { colorStart: 'Ω', colorEnd: '∆', field: '§', defaultFg: null, defaultBg: null, }; // const RE_RGB = /^[a-fA-F0-9]*$/; // // export function parseColor(color:string) { // if (color.startsWith('#')) { // color = color.substring(1); // } // else if (color.startsWith('0x')) { // color = color.substring(2); // } // if (color.length == 3) { // if (RE_RGB.test(color)) { // return Number.parseInt(color, 16); // } // } // if (color.length == 6) { // if (RE_RGB.test(color)) { // const v = Number.parseInt(color, 16); // const r = Math.round( ((v & 0xFF0000) >> 16) / 17); // const g = Math.round( ((v & 0xFF00) >> 8) / 17); // const b = Math.round((v & 0xFF) / 17); // return (r << 8) + (g << 4) + b; // } // } // return 0xFFF; // } export var helpers = { eachColor: (() => { }), default: ((name, _, value) => { if (value !== undefined) return `${value}.!!${name}!!`; return `!!${name}!!`; }), }; export function addHelper(name, fn) { helpers[name] = fn; }
import gzip import json from pathlib import Path import numpy as np def check_bidsphysio_outputs(outPrefix, expectedPhysioLabels, expectedDataFilePrefix, ): """ Auxiliary function to check the output of running dcm2bids Parameters ---------- outPrefix : Path or str Prefix of the path of the output of dcm2bids (the bidsprefix arg). E.g.: '/tmp/mydir/sub-01_task-rest' expectedPhysioLabels : list List with the expected physio labels expectedDataFilePrefix : Path or str or None Prefix of the path to the file with the expected data (If we don't need to check the results, set to None) If there is only one expectedPhysioLabel, the expectedDataFilePrefix must be the whols file path (including extension) Returns ------- """ outPrefix = Path(outPrefix) if not isinstance(expectedPhysioLabels, list): expectedPhysioLabels = [expectedPhysioLabels] json_files = sorted(outPrefix.parent.glob('*.json')) data_files = sorted(outPrefix.parent.glob('*.tsv*')) assert len(json_files) == len(data_files) == len(expectedPhysioLabels) for label in expectedPhysioLabels: if len(expectedPhysioLabels) == 1: expectedFileBaseName = Path(outPrefix).name + '_physio' else: expectedFileBaseName = Path(str(outPrefix) + '_recording-' + ''.join(label) + '_physio').name expectedFileName = outPrefix.parent / expectedFileBaseName assert expectedFileName.with_suffix('.json') in json_files assert expectedFileName.with_suffix('.tsv.gz') in data_files # check content of the json file: with open(expectedFileName.with_suffix('.json')) as f: d = json.load(f) if isinstance(label, list): for c in d['Columns']: assert c in label or c == 'trigger' else: assert d['Columns'] == [label, 'trigger'] # check content of the tsv file: if expectedDataFilePrefix: expectedDataFilePrefix = Path(expectedDataFilePrefix) if len(expectedPhysioLabels) == 1: expectedDataFile = expectedDataFilePrefix.with_suffix('.tsv') expectedJsonFile = expectedDataFilePrefix.with_suffix('.json') else: expectedDataFile = str(expectedDataFilePrefix) + ''.join(label) + '.tsv' expectedJsonFile = str(expectedDataFilePrefix) + ''.join(label) + '.json' with open(expectedJsonFile) as f: expected_d = json.load(f) assert d['SamplingFrequency'] == expected_d['SamplingFrequency'] if 'StartTime' in d: assert d['StartTime'] == expected_d['StartTime'] with open(expectedDataFile, 'rt') as expected, \ gzip.open(expectedFileName.with_suffix('.tsv.gz'), 'rt') as f: for expected_line, written_line in zip(expected, f): assert expected_line == written_line def get_physio_TRs(bids_prefix): """ Get the TRs from the triggers of BIDS physiology files Parameters ---------- bids_prefix : Path or str Prefix of the path of the BIDS physio files. E.g.: '/tmp/mydir/sub-01_task-rest' Returns ------- TRs : list List with the TRs of the files found """ bids_prefix = Path(bids_prefix) json_files = sorted(bids_prefix.parent.glob('*.json')) data_files = sorted(bids_prefix.parent.glob('*.tsv*')) TRs = [] for j_file, d_file in zip(json_files, data_files): # check that we have a trigger column: with open(j_file) as f: d = json.load(f) if 'trigger' not in d['Columns']: pass # we have a trigger column: # get the triggers from the data itself: trig_column = d['Columns'].index('trigger') freq = d['SamplingFrequency'] trigger = np.genfromtxt(fname=d_file, delimiter="\t")[:, trig_column] trigger_indices = np.nonzero(trigger) if not trigger_indices: tr = float('NaN') else: tr = np.mean(np.diff(trigger_indices) / freq) TRs.append(tr) return TRs
import VueRouter from "vue-router"; import AdminPage from "./pages/Admin"; import StudentPage from "./pages/Student"; import CourseSchedulerPage from "./pages/CourseScheduler"; import UploadCsvPage from "./pages/UploadCsv"; import EditSemestersPage from "./pages/EditSemesters"; import CourseExplorerPage from "./pages/CourseExplorer"; import CoursePage from "./pages/CoursePage"; import DegreeTemplatesPage from "./pages/DegreeTemplates"; import SubjectExplorerPage from "./pages/SubjectExplorer"; var router = new VueRouter({ routes: [ { path: "/", component: StudentPage, props: true, children: [ { path: "/", component: CourseSchedulerPage, name: "CourseScheduler", props: true, }, { path: "/explore", component: CourseExplorerPage, name: "CourseExplorer", props: true, }, { path: "/template", component: DegreeTemplatesPage, name: "DegreeTemplates", }, { path: "/explore/:subject", component: SubjectExplorerPage, name: "SubjectExplorer", props: true, }, { path: "/explore/:subject/:course", component: CoursePage, name: "CoursePage", props: true, }, ], }, { path: "/Admin", component: AdminPage, name: "Admin", }, { path: "/admin/csv", component: UploadCsvPage, name: "UploadCsv", }, { path: "/admin/editsemesters", component: EditSemestersPage, name: "EditSemesters", }, ], mode: "history", }); export default router;
'use strict'; const _ = require('lodash'); module.exports = ({ Aigle, neoAsync }) => { return { 'pick:array': { setup: config => { this.array = _.times(config.count); this.promiseIterator = value => value % 2; this.neoAsyncIterator = (n, cb) => cb(null, n % 2); }, aigle: () => { return Aigle.pick(this.array, this.promiseIterator); }, neoAsync: callback => { neoAsync.pick(this.array, this.neoAsyncIterator, callback); } }, 'pick:array:async': { setup: config => { this.array = _.times(config.count); this.aigleIterator = value => new Aigle(resolve => setImmediate(resolve, value % 2)); this.neoAsyncIterator = (n, cb) => setImmediate(cb, null, n % 2); }, aigle: () => { return Aigle.pick(this.array, this.aigleIterator); }, neoAsync: callback => { neoAsync.pick(this.array, this.neoAsyncIterator, callback); } } }; };
import React from 'react' import Link from 'gatsby-link' import * as utils from './utils' import logo from "./logo.png"; const Header = ({ siteTitle }) => ( <div style={{ background: 'rebeccapurple', marginBottom: '1.45rem', }} > <div> <nav className="navbar is-transparent"> <div className="navbar-brand"> <a className="navbar-item" href="/"> <img src={logo} alt="AAsia Travel" width="30" height="30" /> <p style={{marginLeft: 10, color: 'red'}}>AAsia Travel</p> </a> <div className="navbar-burger burger" data-target="navbarExampleTransparentExample"> <span></span> <span></span> <span></span> </div> </div> <div id="navbarExampleTransparentExample" className="navbar-menu"> <div className="navbar-start"> {/* <a className="navbar-item" href="/"> Home </a> */} <div className="navbar-item has-dropdown is-hoverable"> <a className="navbar-link" href="/documentation/overview/start/"> Destinations </a> <div className="navbar-dropdown is-boxed"> <a className="navbar-item" href="/hongkong/"> Hong Kong </a> <a className="navbar-item" href="/macao/"> Macao </a> <a className="navbar-item" href="/Russia"> Russia </a> </div> </div> <div className="navbar-item has-dropdown is-hoverable"> <a className="navbar-link" href="/documentation/overview/start/"> Services </a> <div className="navbar-dropdown is-boxed"> <a className="navbar-item" href="/attractions/"> Attractions </a> <a className="navbar-item" href="/transfer/"> Transfers </a> <a className="navbar-item" href="/guides"> Guides </a> <a className="navbar-item" href="/privatejet"> Privat Jet </a> </div> </div> </div> <div className="navbar-end"> <div className="navbar-item"> <div className="field is-grouped"> {/* <a className="navbar-item" href="/blog"> Blog </a> */} <a className="navbar-item" href="/about"> About </a> <a className="navbar-item" href="/contact"> Contact </a> </div> </div> </div> </div> </nav> </div> {/* <div style={{ margin: '0 auto', maxWidth: 960, padding: '1.45rem 1.0875rem', }} > <h1 style={{ margin: 0 }}> <Link to="/" style={{ color: 'white', textDecoration: 'none', }} > {siteTitle} </Link> </h1> </div> */} </div> ) export default Header
$(function(){ const toggleDisplay = elemId => { let x = document.getElementById(elemId); if (x.style.display !== 'block') { x.style.display = 'block'; } else { x.style.display = 'none'; } }; $("#readme-button").click(function() { toggleDisplay("readme-text"); }); document.addEventListener("click", function(evt) { var readmeButtonElement = document.getElementById('readme-button'), readmeTextElement = document.getElementById('readme-text'), targetElement = evt.target; // clicked element if (targetElement == readmeButtonElement || targetElement == readmeTextElement) { return; //readme-button or readme-text is clicked. do nothing. } if(readmeTextElement.style.display === 'block') { readmeTextElement.style.display = 'none'; } }); $('#start').click(function(){ $("#buttonrun").append('<img id="myProgressBar" style="width:100px;height:100px;" src="https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif"/>') var carbontax = parseFloat($('#carbontax').val()); var interestfactor = "1.0"; var intmarketpricefactor = parseFloat($('#intmarketpricefactor').val()); var intmarketlowestprice = JSON.parse($('#intmarketlowestprice').val()); var timefactor = $('#timefactor').val().split(","); var list =[carbontax,interestfactor,intmarketpricefactor,intmarketlowestprice,timefactor]; var query = { "CarbonTax": carbontax, //"InterestFactor":interestfactor, "InternationalMarketPriceFactor":intmarketpricefactor, "InternationalMarketLowestPriceApplied":intmarketlowestprice, "AnnualCostFactor":timefactor } query = JSON.stringify(query); console.log("data of input= "+JSON.stringify(list)); $.getJSON('/JPS_MEN/MENTableAgent', { query }, function(data) { var result = data; console.log("data of result= "+JSON.stringify(result)); $('#myProgressBar').remove() var n= $('#timefactor').val().replace("[","").replace("]","").split(","); var totalyear=n.length; var tablestring="<TABLE id=\"table\" border=\"2\" >"; tablestring+="<tr>"; tablestring+="<TH>Project life times</TH>"; tablestring+="<TH>Transport Cost per year <br> (10^3 x $/yr)</TH>"; tablestring+="<TH> Material Purchase Cost per year <br> (10^9 x $/yr)</TH>"; tablestring+="<TH>Pipeline Installation Cost <br> (10^6 x $)</TH>"; tablestring+="<TH>CO<sub>2</sub> Emission per year <br> (ton/yr)</TH>"; tablestring+="<TH>CO<sub>2</sub> Emission cost per year <br> (10^3 x $/yr)</TH>"; for(var c=0; c<totalyear; c++) { tablestring+="<TH>Total Cost Related to Transportation in "+n[c]+" year <br> (10^6 x $)</TH>"; } tablestring+="</tr>"; for (var a=1; a <= totalyear; a++) { tablestring+="<tr>"; tablestring+="<TH>"+n[a-1]+" year</TH>"; for(var b=1; b<=5+totalyear; b++) { tablestring+="<td align=\"center\" id=cell"+a+b+"></td>"; } tablestring+="</tr>"; } tablestring+="</table>"; document.getElementById("outputFields").innerHTML = tablestring; for (var i=1; i<=timefactor.length;i++) { document.getElementById("cell"+i+"1").innerHTML = result.totalTransportationCost[i-1]; document.getElementById("cell"+i+"2").innerHTML = result.totalMaterialPurchaseCost[i-1]; document.getElementById("cell"+i+"3").innerHTML = result.totalInstallationCost[i-1]; document.getElementById("cell"+i+"4").innerHTML = result.totalCO2Emission[i-1]; document.getElementById("cell"+i+"5").innerHTML = result.totalCO2EmissionCost[i-1]; for(var h=0;h<timefactor.length;h++) { document.getElementById("cell"+i+String(6+h)).innerHTML = result.totaltransportyearcost[timefactor.length*(i-1)+h]; } } }).fail(function (){ $('#myProgressBar').remove() document.getElementById("outputFields").innerHTML = '<div id="outputFields"><table id="table" border="2"><tbody><tr><th>Project life times</th><th>Transport Cost per year <br> (10^3 x $/yr)</th><th> Material Purchase Cost per year <br> (10^9 x $/yr)</th><th>Pipeline Installation Cost <br> (10^6 x $)</th><th>CO<sub>2</sub> Emission per year <br> (ton/yr)</th><th>CO<sub>2</sub> Emission cost per year <br> (10^3 x $/yr)</th><th>Total Cost Related to Transportation in 1 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 10 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 50 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 100 year <br> (10^6 x $)</th></tr><tr><th>1 year</th><td id="cell11" align="center">577.38</td><td id="cell12" align="center">6.42</td><td id="cell13" align="center">0.00</td><td id="cell14" align="center">802.84</td><td id="cell15" align="center">40.14</td><td id="cell16" align="center">0.58</td><td id="cell17" align="center">5.77</td><td id="cell18" align="center">28.87</td><td id="cell19" align="center">57.74</td></tr><tr><th>10 year</th><td id="cell21" align="center">64.49</td><td id="cell22" align="center">6.64</td><td id="cell23" align="center">0.68</td><td id="cell24" align="center">108.33</td><td id="cell25" align="center">5.42</td><td id="cell26" align="center">0.74</td><td id="cell27" align="center">1.32</td><td id="cell28" align="center">3.90</td><td id="cell29" align="center">7.13</td></tr><tr><th>50 year</th><td id="cell31" align="center">22.54</td><td id="cell32" align="center">6.64</td><td id="cell33" align="center">1.55</td><td id="cell34" align="center">53.71</td><td id="cell35" align="center">2.69</td><td id="cell36" align="center">1.57</td><td id="cell37" align="center">1.78</td><td id="cell38" align="center">2.68</td><td id="cell39" align="center">3.80</td></tr><tr><th>100 year</th><td id="cell41" align="center">12.66</td><td id="cell42" align="center">6.64</td><td id="cell43" align="center">2.39</td><td id="cell44" align="center">40.85</td><td id="cell45" align="center">2.04</td><td id="cell46" align="center">2.40</td><td id="cell47" align="center">2.52</td><td id="cell48" align="center">3.02</td><td id="cell49" align="center">3.66</td></tr></tbody></table></div>'; }) }) // If start fails (ie simulation doesn't work anymore, replace the method with this:) $('#startv2').click(function(){ document.getElementById("outputFields").innerHTML = '<div id="outputFields"><table id="table" border="2"><tbody><tr><th>Project life times</th><th>Transport Cost per year <br> (10^3 x $/yr)</th><th> Material Purchase Cost per year <br> (10^9 x $/yr)</th><th>Pipeline Installation Cost <br> (10^6 x $)</th><th>CO<sub>2</sub> Emission per year <br> (ton/yr)</th><th>CO<sub>2</sub> Emission cost per year <br> (10^3 x $/yr)</th><th>Total Cost Related to Transportation in 1 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 10 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 50 year <br> (10^6 x $)</th><th>Total Cost Related to Transportation in 100 year <br> (10^6 x $)</th></tr><tr><th>1 year</th><td id="cell11" align="center">577.38</td><td id="cell12" align="center">6.42</td><td id="cell13" align="center">0.00</td><td id="cell14" align="center">802.84</td><td id="cell15" align="center">40.14</td><td id="cell16" align="center">0.58</td><td id="cell17" align="center">5.77</td><td id="cell18" align="center">28.87</td><td id="cell19" align="center">57.74</td></tr><tr><th>10 year</th><td id="cell21" align="center">64.49</td><td id="cell22" align="center">6.64</td><td id="cell23" align="center">0.68</td><td id="cell24" align="center">108.33</td><td id="cell25" align="center">5.42</td><td id="cell26" align="center">0.74</td><td id="cell27" align="center">1.32</td><td id="cell28" align="center">3.90</td><td id="cell29" align="center">7.13</td></tr><tr><th>50 year</th><td id="cell31" align="center">22.54</td><td id="cell32" align="center">6.64</td><td id="cell33" align="center">1.55</td><td id="cell34" align="center">53.71</td><td id="cell35" align="center">2.69</td><td id="cell36" align="center">1.57</td><td id="cell37" align="center">1.78</td><td id="cell38" align="center">2.68</td><td id="cell39" align="center">3.80</td></tr><tr><th>100 year</th><td id="cell41" align="center">12.66</td><td id="cell42" align="center">6.64</td><td id="cell43" align="center">2.39</td><td id="cell44" align="center">40.85</td><td id="cell45" align="center">2.04</td><td id="cell46" align="center">2.40</td><td id="cell47" align="center">2.52</td><td id="cell48" align="center">3.02</td><td id="cell49" align="center">3.66</td></tr></tbody></table></div>'; }) });
#!/usr/bin/python from __future__ import absolute_import, division, print_function # Copyright 2019-2021 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. __metaclass__ = type ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: fmgr_user_fortitoken short_description: Configure FortiToken. description: - This module is able to configure a FortiManager device. - Examples include all parameters and values which need to be adjusted to data sources before usage. version_added: "2.10" author: - Link Zheng (@chillancezen) - Jie Xue (@JieX19) - Frank Shen (@fshen01) - Hongbin Lu (@fgtdev-hblu) notes: - Running in workspace locking mode is supported in this FortiManager module, the top level parameters workspace_locking_adom and workspace_locking_timeout help do the work. - To create or update an object, use state present directive. - To delete an object, use state absent directive. - Normally, running one module can fail when a non-zero rc is returned. you can also override the conditions to fail or succeed with parameters rc_failed and rc_succeeded options: enable_log: description: Enable/Disable logging for task required: false type: bool default: false proposed_method: description: The overridden method for the underlying Json RPC request required: false type: str choices: - update - set - add bypass_validation: description: only set to True when module schema diffs with FortiManager API structure, module continues to execute without validating parameters required: false type: bool default: false workspace_locking_adom: description: the adom to lock for FortiManager running in workspace mode, the value can be global and others including root required: false type: str workspace_locking_timeout: description: the maximum time in seconds to wait for other user to release the workspace lock required: false type: int default: 300 state: description: the directive to create, update or delete an object type: str required: true choices: - present - absent rc_succeeded: description: the rc codes list with which the conditions to succeed will be overriden type: list required: false rc_failed: description: the rc codes list with which the conditions to fail will be overriden type: list required: false adom: description: the parameter (adom) in requested url type: str required: true user_fortitoken: description: the top level parameters set required: false type: dict suboptions: comments: type: str description: 'Comment.' license: type: str description: 'Mobile token license.' os-ver: type: str description: 'Device Mobile Version.' reg-id: type: str description: 'Device Reg ID.' serial-number: type: str description: 'Serial number.' status: type: str description: 'Status' choices: - 'lock' - 'active' ''' EXAMPLES = ''' - name: gathering fortimanager facts hosts: fortimanager00 gather_facts: no connection: httpapi collections: - fortinet.fortimanager vars: ansible_httpapi_use_ssl: True ansible_httpapi_validate_certs: False ansible_httpapi_port: 443 tasks: - name: retrieve all the FortiTokens fmgr_fact: facts: selector: 'user_fortitoken' params: adom: 'ansible' fortitoken: '' - hosts: fortimanager00 collections: - fortinet.fortimanager connection: httpapi vars: ansible_httpapi_use_ssl: True ansible_httpapi_validate_certs: False ansible_httpapi_port: 443 tasks: - name: Configure FortiToken. fmgr_user_fortitoken: bypass_validation: False adom: ansible state: present user_fortitoken: comments: ansible-comment serial-number: # need a valid FortiToken serial number status: lock #<value in [lock, active]> ''' RETURN = ''' request_url: description: The full url requested returned: always type: str sample: /sys/login/user response_code: description: The status of api request returned: always type: int sample: 0 response_message: description: The descriptive message of the api response type: str returned: always sample: OK. ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.connection import Connection from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import NAPIManager from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_galaxy_version from ansible_collections.fortinet.fortimanager.plugins.module_utils.napi import check_parameter_bypass def main(): jrpc_urls = [ '/pm/config/adom/{adom}/obj/user/fortitoken', '/pm/config/global/obj/user/fortitoken' ] perobject_jrpc_urls = [ '/pm/config/adom/{adom}/obj/user/fortitoken/{fortitoken}', '/pm/config/global/obj/user/fortitoken/{fortitoken}' ] url_params = ['adom'] module_primary_key = 'serial-number' module_arg_spec = { 'enable_log': { 'type': 'bool', 'required': False, 'default': False }, 'forticloud_access_token': { 'type': 'str', 'required': False, 'no_log': True }, 'proposed_method': { 'type': 'str', 'required': False, 'choices': [ 'set', 'update', 'add' ] }, 'bypass_validation': { 'type': 'bool', 'required': False, 'default': False }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'rc_succeeded': { 'required': False, 'type': 'list' }, 'rc_failed': { 'required': False, 'type': 'list' }, 'state': { 'type': 'str', 'required': True, 'choices': [ 'present', 'absent' ] }, 'adom': { 'required': True, 'type': 'str' }, 'user_fortitoken': { 'required': False, 'type': 'dict', 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'options': { 'comments': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'license': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'os-ver': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False }, 'type': 'str' }, 'reg-id': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': False, '6.4.5': False, '7.0.0': False }, 'type': 'str' }, 'serial-number': { 'required': True, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'status': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'lock', 'active' ], 'type': 'str' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'user_fortitoken'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False) connection.set_option('forticloud_access_token', module.params['forticloud_access_token'] if 'forticloud_access_token' in module.params else None) fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data') fmgr.validate_parameters(params_validation_blob) fmgr.process_curd(argument_specs=module_arg_spec) else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params) if __name__ == '__main__': main()
angular.module('portainer.app').directive('rdWidgetHeader', function rdWidgetTitle() { var directive = { requires: '^rdWidget', scope: { titleText: '@', icon: '@', classes: '@?', }, transclude: true, template: '<div class="widget-header"><div class="row"><span ng-class="classes" class="pull-left"><i class="fa" ng-class="icon"></i> {{titleText}} </span><span ng-class="classes" class="pull-right" ng-transclude></span></div></div>', restrict: 'E', }; return directive; });
import copy import re from emarkdown.Processor.ExtractProcessor.BasicProcessor import BasicProcessor from emarkdown.Processor.ExtractProcessor.Block.TableProcessor import TableProcessor from emarkdown.Processor.ExtractProcessor.Config import TagConfig as Config, TagTypes class HeaderProcessor(BasicProcessor): tag_name = TagTypes.TYPE_HEADER # Type 1 regx1 = r"((?<=\n)|(?<!\W|\w))^( )*((#){1,6})( +)((?!\n)(\w|\W))*" # Type 2 regx2 = r"(\w|(?!\n)\W)+\n((-){3,}|(=){3,})$" # 在block里面都可以处理header,除了List和Table def process_tag(self, md_dict): tp_dict = copy.deepcopy(md_dict) for level, level_dict in md_dict.items(): for uuid, tag_dict in level_dict.items(): # Filter tag_type = tag_dict[Config.KEY_TYPE] tag_inline = tag_dict[Config.KEY_INLINE_FLAG] if not tag_inline and TableProcessor.tag_name != tag_type and HeaderProcessor.tag_name != tag_type: pass else: continue # Start process in_txt = tag_dict[Config.KEY_TEXT] in_txt, tp_dict, md_dict = self.__process_head(in_txt, level, uuid, self.regx1, 1, tp_dict, md_dict) in_txt, tp_dict, md_dict = self.__process_head(in_txt, level, uuid, self.regx2, 2, tp_dict, md_dict) return tp_dict def __process_head(self, in_txt, in_level, in_uuid, in_regx, in_type, tp_dict, md_dict): match, b_txt, m_txt, a_txt = self.re_search_get_txt(in_txt, None, in_regx, re.MULTILINE) while match: m_txt, exact_type = self.__get_exact_type(m_txt, in_type) new_dict, new_uuid = self.get_new_dict(m_txt, self.tag_name, exact_type, False, "") tp_dict = self.insert_tag_md_dict(tp_dict, in_level, new_uuid, new_dict) in_txt = b_txt + new_uuid + a_txt tp_dict[in_level][in_uuid][Config.KEY_TEXT] = in_txt md_dict[in_level][in_uuid][Config.KEY_TEXT] = in_txt match, b_txt, m_txt, a_txt = self.re_search_get_txt(in_txt, None, in_regx, re.MULTILINE) return in_txt, tp_dict, md_dict @staticmethod def __get_exact_type(m_txt, in_type): exact_type = "" if in_type == 1: type_match = re.search("#{1,6}( )*", m_txt) number_sign = m_txt[type_match.start():type_match.end()].replace(" ", "") exact_type = "<h" + str(len(number_sign)) + " id = \"%s\">" m_txt = m_txt[type_match.end():] elif in_type == 2: match_text_list = m_txt.split("\n") number_sign = str(1) if "=" in match_text_list[1] else str(2) exact_type = "<h" + number_sign + " id = \"%s\">" m_txt = match_text_list[0] return m_txt, exact_type
/** * 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 TouchBubblingTestAppModule */ 'use strict'; var Recording = require('NativeModules').Recording; var React = require('React'); var StyleSheet = require('StyleSheet'); var View = require('View'); var TouchableWithoutFeedback = require('TouchableWithoutFeedback'); var TouchBubblingTestApp = React.createClass({ handlePress: function(record) { Recording.record(record); }, render: function() { return ( <View style={styles.container}> <TouchableWithoutFeedback onPress={this.handlePress.bind(this, 'outer')} testID="D"> <View style={styles.outer}> <TouchableWithoutFeedback onPress={this.handlePress.bind(this, 'inner')} testID="B"> <View style={styles.inner}> <View style={styles.superinner} testID="A" /> </View> </TouchableWithoutFeedback> <View style={styles.inner} testID="C" /> </View> </TouchableWithoutFeedback> <TouchableWithoutFeedback onPress={this.handlePress.bind(this, 'outsider')} testID="E"> <View style={styles.element} /> </TouchableWithoutFeedback> </View> ); }, }); var styles = StyleSheet.create({ container: { flexDirection: 'column', backgroundColor: '#ccdd44', }, element: { backgroundColor: '#ff0000', height: 100, margin: 30, }, outer: { backgroundColor: '#00ff00', height: 100, margin: 30, flexDirection: 'row', justifyContent: 'space-between', }, inner: { backgroundColor: '#0000ff', height: 50, width: 50, margin: 10, }, superinner: { backgroundColor: '#eeeeee', height: 20, width: 20, } }); module.exports = TouchBubblingTestApp;
/*! ========================================================= * Argon Dashboard React - v1.1.0 ========================================================= * Product Page: https://www.creative-tim.com/product/argon-dashboard-react * Copyright 2019 Creative Tim (https://www.creative-tim.com) * Licensed under MIT (https://github.com/creativetimofficial/argon-dashboard-react/blob/master/LICENSE.md) * Coded by Creative Tim ========================================================= * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ import React from "react"; import Cards from "./Cards" // reactstrap components import { Card, CardBody, CardTitle, Container, Row, Col } from "reactstrap"; class Header extends React.Component { render() { let items =[] let CardTitles =["demande extraction documents admin", "Demande de report de démarcation", "Demande de voir une épreuve", "Demande de changement de filiere", "Fiche d'information stage", "Letter d'affectation", "Proposition de sujet Master Recherche", "lettre d'appui (étudient satgiaire)"] CardTitles.forEach(element =>items.push( <Col lg="6" xl="3"> <Cards name={element} ></Cards> </Col>) ) return ( <> <div className="header bg-gradient-info pb-8 pt-5 pt-md-8"> <Container fluid> <div className="header-body"> <Row> {items} </Row> </div> </Container> </div> </> ); } } export default Header;
module.exports = new basis.Token(3).as(function(n){ return n * n; });
# # For licensing see accompanying LICENSE file. # Copyright (C) 2020 Apple Inc. All Rights Reserved. # import argparse import math from utils import logger import numpy as np from . import register_scheduler from .base_scheduler import BaseLRScheduler SUPPORTED_LAST_CYCLES = ['cosine', 'linear'] @register_scheduler("cyclic") class CyclicLRScheduler(BaseLRScheduler): """ Cyclic LR: https://arxiv.org/abs/1811.11431 """ def __init__(self, opts, **kwargs) -> None: cycle_steps = getattr(opts, "scheduler.cyclic.steps", [25]) if cycle_steps is not None and isinstance(cycle_steps, int): cycle_steps = [cycle_steps] gamma = getattr(opts, "scheduler.cyclic.gamma", 0.5) anneal_type = getattr(opts, "scheduler.cyclic.last_cycle_type", "linear") min_lr = getattr(opts, "scheduler.cyclic.min_lr", 0.1) end_lr = getattr(opts, "scheduler.cyclic.last_cycle_end_lr", 1e-3) ep_per_cycle = getattr(opts, "scheduler.cyclic.epochs_per_cycle", 5) warmup_iterations = getattr(opts, "scheduler.warmup_iterations", 0) n_cycles = getattr(opts, "scheduler.cyclic.total_cycles", 10) - 1 max_epochs = getattr(opts, "scheduler.max_epochs", 100) if anneal_type not in SUPPORTED_LAST_CYCLES: logger.error("Supported anneal types for {} are: {}".format(self.__class__.__name__, SUPPORTED_LAST_CYCLES) ) if min_lr < end_lr: logger.error("Min LR should be greater than end LR. Got: {} and {}".format(min_lr, end_lr)) super(CyclicLRScheduler, self).__init__(opts=opts) self.min_lr = min_lr self.cycle_length = ep_per_cycle self.end_lr = end_lr self.max_lr = self.min_lr * self.cycle_length self.last_cycle_anneal_type = anneal_type self.warmup_iterations = max(warmup_iterations, 0) if self.warmup_iterations > 0: warmup_init_lr = getattr(opts, "scheduler.warmup_init_lr", 1e-7) self.warmup_init_lr = warmup_init_lr self.warmup_step = (self.min_lr - self.warmup_init_lr) / self.warmup_iterations self.n_cycles = n_cycles self.cyclic_epochs = self.cycle_length * self.n_cycles self.max_epochs = max_epochs self.last_cycle_epochs = self.max_epochs - self.cyclic_epochs assert self.max_epochs == self.cyclic_epochs + self.last_cycle_epochs self.steps = [self.max_epochs] if cycle_steps is None else cycle_steps self.gamma = gamma if cycle_steps is not None else 1 self._lr_per_cycle() self.epochs_lr_stepped = [] def _lr_per_cycle(self) -> None: lrs = list(np.linspace(self.max_lr, self.min_lr, self.cycle_length, dtype=np.float)) lrs = [lrs[-1]] + lrs[:-1] self.cycle_lrs = lrs @classmethod def add_arguments(cls, parser: argparse.ArgumentParser) -> argparse.ArgumentParser: group = parser.add_argument_group(title="Cyclic LR arguments", description="Cyclic LR arguments") group.add_argument('--scheduler.cyclic.min-lr', default=0.1, type=float, help='Min. lr for a cycle') group.add_argument('--scheduler.cyclic.last-cycle-end-lr', default=1e-3, type=float, help='End LR for the last cycle') group.add_argument('--scheduler.cyclic.total-cycles', default=11, type=int, help='Number of cycles. Default is 10') group.add_argument('--scheduler.cyclic.epochs-per-cycle', default=5, type=int, help='Number of epochs per cycle. Default is 5') group.add_argument('--scheduler.cyclic.steps', default=None, type=int, nargs='+', help='steps at which LR should be decreased') group.add_argument('--scheduler.cyclic.gamma', default=0.5, type=float, help='Factor by which LR should be decreased') group.add_argument('--scheduler.cyclic.last-cycle-type', default='linear', type=str, choices=SUPPORTED_LAST_CYCLES, help='Annealing in last cycle') return parser def get_lr(self, epoch: int, curr_iter: int) -> float: if curr_iter < self.warmup_iterations: curr_lr = self.warmup_init_lr + curr_iter * self.warmup_step else: if epoch <= self.cyclic_epochs: if epoch in self.steps and epoch not in self.epochs_lr_stepped: self.min_lr *= (self.gamma ** (self.steps.index(epoch) + 1)) self.max_lr *= (self.gamma ** (self.steps.index(epoch) + 1)) self._lr_per_cycle() self.epochs_lr_stepped.append(epoch) idx = (epoch % self.cycle_length) curr_lr = self.cycle_lrs[idx] else: base_lr = self.min_lr if self.last_cycle_anneal_type == 'linear': lr_step = (base_lr - self.end_lr) / self.last_cycle_epochs curr_lr = base_lr - (epoch - self.cyclic_epochs + 1) * lr_step elif self.last_cycle_anneal_type == 'cosine': curr_epoch = epoch - self.cyclic_epochs period = self.max_epochs - self.cyclic_epochs + 1 curr_lr = self.end_lr + 0.5 * (base_lr - self.end_lr) * (1 + math.cos(math.pi * curr_epoch / period)) else: raise NotImplementedError return max(0.0, curr_lr) def __repr__(self): repr_str = '{}(\n \t C={},\n \t C_length={},\n \t C_last={},\n \t Total_Epochs={}, ' \ '\n \t steps={},\n \t gamma={},\n \t last_cycle_anneal_method={} ' \ '\n \t min_lr={}, \n\t max_lr={}, \n\t end_lr={}\n)'.format(self.__class__.__name__, self.n_cycles, self.cycle_length, self.last_cycle_epochs, self.max_epochs, self.steps, self.gamma, self.last_cycle_anneal_type, self.min_lr, self.min_lr * self.cycle_length, self.end_lr) return repr_str if __name__ == "__main__": opts = None sch = CyclicLRScheduler(opts=opts) n_epochs = 100 lrs = [] iter_per_epoch = 1000 for i in range(n_epochs): lr = 0.0 for it in range(iter_per_epoch): curr_iter = (i * iter_per_epoch + it) lr = sch.get_lr(epoch=i, curr_iter=curr_iter) lrs.append(lr) print(lrs[-1]) import matplotlib.pyplot as plt plt.plot(lrs) plt.show()
main+u1+u2+staged user1
import { StyleSheet, Dimensions } from 'react-native'; import Fonts from 'App/Theme/Fonts'; const { width, height } = Dimensions.get('window'); export default StyleSheet.create({ inputContainerStyle: { paddingLeft: 10, top: 5, borderWidth: 0, }, titleTextStyle: { color: 'white' }, containerStyle: { height: 50, width: width - 25, justifyContent: 'center', borderRadius: 6, borderColor: '#EE5C7F', borderWidth: 2, marginTop: 10, marginBottom: 10 }, labelTextStyle: { color: 'transparent', marginTop: -15 }, affixTextStyle: { ...Fonts.style.normal, textAlign: 'center', color: 'white', fontWeight: '800', letterSpacing: 3 } })
(function(mainNav){ var $_main, $_navIcon; $_main = $( '.main-container' ); $_navIcon = $( '<i class="fa"></i>' ); var addIcon = function(targetNav) { targetNav.before( $_navIcon ); } var expand = function(targetNav) { $_navIcon.removeClass( 'open' ).addClass( 'close' ); targetNav.removeClass( 'collapsed' ).addClass( 'expanded' ); } // Collapse the navigation when anything outside of the nav is clicked var collapse = function(targetNav) { $_navIcon.removeClass( 'close' ).addClass( 'open' ); targetNav.removeClass( 'expanded' ).addClass( 'collapsed' ); } // Clear mobile classes on desktop and larger var clear = function(targetNav) { $_navIcon.removeClass( 'open close' ); targetNav.removeClass( 'collapsed expanded' ); } mainNav.toggle = function (nav) { nav = $( nav ); // Add navigation icon addIcon( nav ); // Collapse the navigation to start if (!nav.hasClass('collapsed') && !nav.hasClass('expanded')) { $_navIcon.addClass('open'); nav.addClass( 'collapsed' ); } // When the hamburger/close icon is clicked $_navIcon.on( 'click', function(){ if (nav.hasClass('collapsed')){ // Expand the navigation expand(nav); } else if (nav.hasClass('expanded')){ // Collapse the navigation collapse(nav); } }); // Collapse the navigation when anything outside of the nav // is clicked $_main.on( 'click', function(){ collapse(nav); }); }; })(this.topNav = {});
import { bindActionCreators } from 'redux' import { connect } from 'react-redux' import KontakteIntern from '../../components/geschaeft/KontakteIntern' import * as GeschaefteKontakteInternActions from '../../actions/geschaefteKontakteIntern' import * as AppActions from '../../actions/app' const actions = Object.assign( GeschaefteKontakteInternActions, AppActions, ) function mapStateToProps(state, props) { const { geschaefteKontakteIntern, activeIdGeschaeft, activeIdKontakt, } = state.geschaefteKontakteIntern const { interneOptions, activeId, } = state.geschaefte const path = state.routing.locationBeforeTransitions.pathname const isPrintPreview = path === '/geschaeftPdf' const { tabIndex, } = props return { geschaefteKontakteIntern, activeIdGeschaeft, activeIdKontakt, interneOptions, activeId, tabIndex, isPrintPreview, } } function mapDispatchToProps(dispatch) { return bindActionCreators(actions, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(KontakteIntern)
// This file was procedurally generated from the following sources: // - src/dstr-binding/obj-ptrn-id-init-fn-name-fn.case // - src/dstr-binding/default/async-gen-method-dflt.template /*--- description: SingleNameBinding assigns name to "anonymous" functions (async generator method (default parameter)) esid: sec-asyncgenerator-definitions-propertydefinitionevaluation features: [async-iteration] flags: [generated, async] info: | AsyncGeneratorMethod : async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody } 1. Let propKey be the result of evaluating PropertyName. 2. ReturnIfAbrupt(propKey). 3. If the function code for this AsyncGeneratorMethod is strict mode code, let strict be true. Otherwise let strict be false. 4. Let scope be the running execution context's LexicalEnvironment. 5. Let closure be ! AsyncGeneratorFunctionCreate(Method, UniqueFormalParameters, AsyncGeneratorBody, scope, strict). [...] 13.3.3.7 Runtime Semantics: KeyedBindingInitialization SingleNameBinding : BindingIdentifier Initializeropt [...] 6. If Initializer is present and v is undefined, then [...] d. If IsAnonymousFunctionDefinition(Initializer) is true, then i. Let hasNameProperty be HasOwnProperty(v, "name"). ii. ReturnIfAbrupt(hasNameProperty). iii. If hasNameProperty is false, perform SetFunctionName(v, bindingId). ---*/ var callCount = 0; var obj = { async *method({ fn = function () {}, xFn = function x() {} } = {}) { assert.sameValue(fn.name, 'fn'); assert.notSameValue(xFn.name, 'xFn'); callCount = callCount + 1; } }; obj.method().next().then(() => { assert.sameValue(callCount, 1, 'invoked exactly once'); }).then($DONE, $DONE);
# # 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. # # Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import InstanceCommunication_pb2 as InstanceCommunication__pb2 from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 class InstanceControlStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.GetFunctionStatus = channel.unary_unary( '/proto.InstanceControl/GetFunctionStatus', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=InstanceCommunication__pb2.FunctionStatus.FromString, ) self.GetAndResetMetrics = channel.unary_unary( '/proto.InstanceControl/GetAndResetMetrics', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=InstanceCommunication__pb2.MetricsData.FromString, ) self.HealthCheck = channel.unary_unary( '/proto.InstanceControl/HealthCheck', request_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, response_deserializer=InstanceCommunication__pb2.HealthCheckResult.FromString, ) class InstanceControlServicer(object): # missing associated documentation comment in .proto file pass def GetFunctionStatus(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def GetAndResetMetrics(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def HealthCheck(self, request, context): # missing associated documentation comment in .proto file pass context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!') def add_InstanceControlServicer_to_server(servicer, server): rpc_method_handlers = { 'GetFunctionStatus': grpc.unary_unary_rpc_method_handler( servicer.GetFunctionStatus, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=InstanceCommunication__pb2.FunctionStatus.SerializeToString, ), 'GetAndResetMetrics': grpc.unary_unary_rpc_method_handler( servicer.GetAndResetMetrics, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=InstanceCommunication__pb2.MetricsData.SerializeToString, ), 'HealthCheck': grpc.unary_unary_rpc_method_handler( servicer.HealthCheck, request_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, response_serializer=InstanceCommunication__pb2.HealthCheckResult.SerializeToString, ), } generic_handler = grpc.method_handlers_generic_handler( 'proto.InstanceControl', rpc_method_handlers) server.add_generic_rpc_handlers((generic_handler,))
"""Timeout for tests to stop hanging testruns This plugin will dump the stack and terminate the test. This can be useful when running tests on a continuous integration server. If the platform supports SIGALRM this is used to raise an exception in the test, otherwise os._exit(1) is used. """ import os import signal import sys import threading import traceback from collections import namedtuple from distutils.version import StrictVersion import py import pytest HAVE_SIGALRM = hasattr(signal, 'SIGALRM') if HAVE_SIGALRM: DEFAULT_METHOD = 'signal' else: DEFAULT_METHOD = 'thread' TIMEOUT_DESC = """ Timeout in seconds before dumping the stacks. Default is 0 which means no timeout. """.strip() METHOD_DESC = """ Timeout mechanism to use. 'signal' uses SIGALRM if available, 'thread' uses a timer thread. The default is to use 'signal' and fall back to 'thread'. """.strip() FUNC_ONLY_DESC = """ When set to True, defers the timeout evaluation to only the test function body, ignoring the time it takes when evaluating any fixtures used in the test. """.strip() Settings = namedtuple('Settings', ['timeout', 'method', 'func_only']) @pytest.hookimpl def pytest_addoption(parser): """Add options to control the timeout plugin""" group = parser.getgroup( 'timeout', 'Interrupt test run and dump stacks of all threads after ' 'a test times out') group.addoption('--timeout', type=float, help=TIMEOUT_DESC) group.addoption('--timeout_method', action='store', choices=['signal', 'thread'], help='Deprecated, use --timeout-method') group.addoption('--timeout-method', dest='timeout_method', action='store', choices=['signal', 'thread'], help=METHOD_DESC) parser.addini('timeout', TIMEOUT_DESC) parser.addini('timeout_method', METHOD_DESC) parser.addini('timeout_func_only', FUNC_ONLY_DESC, type='bool') @pytest.hookimpl def pytest_configure(config): # Register the marker so it shows up in --markers output. config.addinivalue_line( 'markers', 'timeout(timeout, method=None, func_only=False): Set a timeout, timeout ' 'method and func_only evaluation on just one test item. The first ' 'argument, *timeout*, is the timeout in seconds while the keyword, ' '*method*, takes the same values as the --timeout_method option. The ' '*func_only* keyword, when set to True, defers the timeout evaluation ' 'to only the test function body, ignoring the time it takes when ' 'evaluating any fixrures used in the test.') settings = get_env_settings(config) config._env_timeout = settings.timeout config._env_timeout_method = settings.method config._env_timeout_func_only = settings.func_only @pytest.hookimpl(hookwrapper=True) def pytest_runtest_protocol(item): func_only = get_func_only_setting(item) if func_only is False: timeout_setup(item) outcome = yield if func_only is False: timeout_teardown(item) @pytest.hookimpl(hookwrapper=True) def pytest_runtest_call(item): func_only = get_func_only_setting(item) if func_only is True: timeout_setup(item) outcome = yield if func_only is True: timeout_teardown(item) @pytest.hookimpl(tryfirst=True) def pytest_report_header(config): if config._env_timeout: return ["timeout: %ss\ntimeout method: %s\ntimeout func_only: %s" % (config._env_timeout, config._env_timeout_method, config._env_timeout_func_only)] @pytest.hookimpl(tryfirst=True) def pytest_exception_interact(node): timeout_teardown(node) @pytest.hookimpl def pytest_enter_pdb(): # Since pdb.set_trace happens outside of any pytest control, we don't have # any pytest ``item`` here, so we cannot use timeout_teardown. Thus, we # need another way to signify that the timeout should not be performed. global SUPPRESS_TIMEOUT SUPPRESS_TIMEOUT = True SUPPRESS_TIMEOUT = False def timeout_setup(item): """Setup up a timeout trigger and handler""" params = get_params(item) if params.timeout is None or params.timeout <= 0: return if params.method == 'signal': def handler(signum, frame): __tracebackhide__ = True timeout_sigalrm(item, params.timeout) def cancel(): signal.setitimer(signal.ITIMER_REAL, 0) signal.signal(signal.SIGALRM, signal.SIG_DFL) item.cancel_timeout = cancel signal.signal(signal.SIGALRM, handler) signal.setitimer(signal.ITIMER_REAL, params.timeout) elif params.method == 'thread': timer = threading.Timer(params.timeout, timeout_timer, (item, params.timeout)) timer.name = "%s %s" (__name__, item.nodeid) def cancel(): timer.cancel() timer.join() item.cancel_timeout = cancel timer.start() def timeout_teardown(item): """Cancel the timeout trigger if it was set""" # When skipping is raised from a pytest_runtest_setup function # (as is the case when using the pytest.mark.skipif marker) we # may be called without our setup counterpart having been # called. cancel = getattr(item, 'cancel_timeout', None) if cancel: cancel() def get_env_settings(config): timeout = config.getvalue('timeout') if timeout is None: timeout = _validate_timeout( os.environ.get('PYTEST_TIMEOUT'), 'PYTEST_TIMEOUT environment variable') if timeout is None: ini = config.getini('timeout') if ini: timeout = _validate_timeout(ini, 'config file') method = config.getvalue('timeout_method') if method is None: ini = config.getini('timeout_method') if ini: method = _validate_method(ini, 'config file') if method is None: method = DEFAULT_METHOD func_only = config.getini('timeout_func_only') if func_only == []: # No value set func_only = None if func_only is not None: func_only = _validate_func_only(func_only, 'config file') return Settings(timeout, method, func_only or False) def get_func_only_setting(item): """Return the func_only setting for an item""" func_only = None marker = item.get_closest_marker('timeout') if marker: settings = get_params(item, marker=marker) func_only = _validate_func_only(settings.func_only, 'marker') if func_only is None: func_only = item.config._env_timeout_func_only if func_only is None: func_only = False return func_only def get_params(item, marker=None): """Return (timeout, method) for an item""" timeout = method = func_only = None if not marker: marker = item.get_closest_marker('timeout') if marker is not None: settings = _parse_marker(item.get_closest_marker(name='timeout')) timeout = _validate_timeout(settings.timeout, 'marker') method = _validate_method(settings.method, 'marker') func_only = _validate_func_only(settings.func_only, 'marker') if timeout is None: timeout = item.config._env_timeout if method is None: method = item.config._env_timeout_method if func_only is None: func_only = item.config._env_timeout_func_only return Settings(timeout, method, func_only) def _parse_marker(marker): """Return (timeout, method) tuple from marker Either could be None. The values are not interpreted, so could still be bogus and even the wrong type. """ if not marker.args and not marker.kwargs: raise TypeError('Timeout marker must have at least one argument') timeout = method = func_only = NOTSET = object() for kw, val in marker.kwargs.items(): if kw == 'timeout': timeout = val elif kw == 'method': method = val elif kw == 'func_only': func_only = val else: raise TypeError( 'Invalid keyword argument for timeout marker: %s' % kw) if len(marker.args) >= 1 and timeout is not NOTSET: raise TypeError( 'Multiple values for timeout argument of timeout marker') elif len(marker.args) >= 1: timeout = marker.args[0] if len(marker.args) >= 2 and method is not NOTSET: raise TypeError( 'Multiple values for method argument of timeout marker') elif len(marker.args) >= 2: method = marker.args[1] if len(marker.args) > 2: raise TypeError('Too many arguments for timeout marker') if timeout is NOTSET: timeout = None if method is NOTSET: method = None if func_only is NOTSET: func_only = None return Settings(timeout, method, func_only) def _validate_timeout(timeout, where): """Helper for get_params()""" if timeout is None: return None try: return float(timeout) except ValueError: raise ValueError('Invalid timeout %s from %s' % (timeout, where)) def _validate_method(method, where): """Helper for get_params()""" if method is None: return None if method not in ['signal', 'thread']: raise ValueError('Invalid method %s from %s' % (method, where)) return method def _validate_func_only(func_only, where): """Helper for get_params()""" if func_only is None: return False if not isinstance(func_only, bool): raise ValueError('Invalid func_only value %s from %s' % (func_only, where)) return func_only def timeout_sigalrm(item, timeout): """Dump stack of threads and raise an exception This will output the stacks of any threads other then the current to stderr and then raise an AssertionError, thus terminating the test. """ if SUPPRESS_TIMEOUT: return __tracebackhide__ = True nthreads = len(threading.enumerate()) if nthreads > 1: write_title('Timeout', sep='+') dump_stacks() if nthreads > 1: write_title('Timeout', sep='+') pytest.fail('Timeout >%ss' % timeout) def timeout_timer(item, timeout): """Dump stack of threads and call os._exit() This disables the capturemanager and dumps stdout and stderr. Then the stacks are dumped and os._exit(1) is called. """ if SUPPRESS_TIMEOUT: return try: capman = item.config.pluginmanager.getplugin('capturemanager') if capman: pytest_version = StrictVersion(pytest.__version__) if pytest_version >= StrictVersion('3.7.3'): capman.suspend_global_capture(item) stdout, stderr = capman.read_global_capture() else: stdout, stderr = capman.suspend_global_capture(item) else: stdout, stderr = None, None write_title('Timeout', sep='+') caplog = item.config.pluginmanager.getplugin('_capturelog') if caplog and hasattr(item, 'capturelog_handler'): log = item.capturelog_handler.stream.getvalue() if log: write_title('Captured log') write(log) if stdout: write_title('Captured stdout') write(stdout) if stderr: write_title('Captured stderr') write(stderr) dump_stacks() write_title('Timeout', sep='+') except Exception: traceback.print_exc() finally: sys.stdout.flush() sys.stderr.flush() os._exit(1) def dump_stacks(): """Dump the stacks of all threads except the current thread""" current_ident = threading.current_thread().ident for thread_ident, frame in sys._current_frames().items(): if thread_ident == current_ident: continue for t in threading.enumerate(): if t.ident == thread_ident: thread_name = t.name break else: thread_name = '<unknown>' write_title('Stack of %s (%s)' % (thread_name, thread_ident)) write(''.join(traceback.format_stack(frame))) def write_title(title, stream=None, sep='~'): """Write a section title If *stream* is None sys.stderr will be used, *sep* is used to draw the line. """ if stream is None: stream = sys.stderr width = py.io.get_terminal_width() fill = int((width - len(title) - 2) / 2) line = ' '.join([sep * fill, title, sep * fill]) if len(line) < width: line += sep * (width - len(line)) stream.write('\n' + line + '\n') def write(text, stream=None): """Write text to stream Pretty stupid really, only here for symetry with .write_title(). """ if stream is None: stream = sys.stderr stream.write(text)
# Copyright 2015-2016 Yelp Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import copy from behave import then from behave import when from paasta_tools import chronos_tools from paasta_tools.utils import _run from paasta_tools.utils import paasta_print @then('we should see a job for the service "{service}" and instance "{instance}" in the job list') def job_exists(context, service, instance): matching_jobs = chronos_tools.lookup_chronos_jobs( client=context.chronos_client, service=service, instance=instance, include_temporary=True, include_disabled=True, ) assert len(matching_jobs) == 1 @when('we run setup_chronos_job for service_instance "{service_instance}"') def run_setup_chronos_job(context, service_instance): cmd = "../paasta_tools/setup_chronos_job.py %s -d %s" % (service_instance, context.soa_dir) exit_code, output = _run(cmd) context.exit_code, context.output = exit_code, output @then('we should get exit code {expected_exit_code:d}') def check_exit_code(context, expected_exit_code): try: assert context.exit_code == expected_exit_code, \ "expected %d, got %d" % (expected_exit_code, context.exit_code) except AssertionError: # behave likes to back up by two lines and then print some stuff, which clobbers my output, so I stick some # extra newlines on here. paasta_print("Output of setup_chronos_job:\n" + context.output + "\n") raise @when('we create {job_count:d} disabled jobs that look like the job stored as "{job_name}"') def old_jobs_leftover(context, job_count, job_name): for i in range(job_count): job_definition = copy.deepcopy(context.jobs[job_name]) # modify the name by replacing the last character in the config hash modified_name = "%s%s" % (job_definition['name'][:-1], i) job_definition['name'] = modified_name job_definition['disabled'] = True context.chronos_client.add(job_definition) @then('there should be {job_count} {disabled} jobs for the service "{service}" and instance "{instance}"') def should_be_disabled_jobs(context, disabled, job_count, service, instance): is_disabled = True if disabled == "disabled" else False all_jobs = chronos_tools.lookup_chronos_jobs( service=service, instance=instance, client=context.chronos_client, include_disabled=True, include_temporary=True, ) filtered_jobs = [job for job in all_jobs if job["disabled"] is is_disabled] assert len(filtered_jobs) == int(job_count) @then( 'setup_chronos_job exits with return code "{expected_return_code}"' ' and the output contains "{expected_output_substring}"', ) def check_setup_chronos_job_output(context, expected_return_code, expected_output_substring): assert int(expected_return_code) == context.exit_code assert expected_output_substring in context.output
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component, PropTypes } from 'react'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-video`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'video'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M15,9 L23,5 L23,19 L15,15 L15,9 Z M1,5 L15,5 L15,19 L1,19 L1,5 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Video'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
# Copyright (C) 2019 The Raphielscape Company LLC. # # Licensed under the Raphielscape Public License, Version 1.c (the "License"); # you may not use this file except in compliance with the License. """ Userbot module to help you manage a group """ from asyncio import sleep from os import remove from telethon import events import asyncio from datetime import datetime from telethon.tl.functions.channels import EditBannedRequest from telethon.tl.types import ChatBannedRights from telethon.errors import (BadRequestError, ChatAdminRequiredError, ImageProcessFailedError, PhotoCropSizeSmallError, UserAdminInvalidError) from telethon.errors.rpcerrorlist import (UserIdInvalidError, MessageTooLongError) from telethon.tl.functions.channels import (EditAdminRequest, EditBannedRequest, EditPhotoRequest) from telethon.tl.functions.messages import UpdatePinnedMessageRequest from telethon.tl.types import (ChannelParticipantsAdmins, ChatAdminRights, ChatBannedRights, MessageEntityMentionName, MessageMediaPhoto) from userbot import BOTLOG, BOTLOG_CHATID, CMD_HELP, bot from userbot.utils import register, errors_handler, admin_cmd # =================== CONSTANT =================== PP_TOO_SMOL = "`The image is too small`" PP_ERROR = "`Failure while processing the image`" NO_ADMIN = "`I am not an admin nub nibba!`" NO_PERM = "`I don't have sufficient permissions! This is so sed. Alexa play despacito`" NO_SQL = "`Running on Non-SQL mode!`" CHAT_PP_CHANGED = "`Chat Picture Changed`" CHAT_PP_ERROR = "`Some issue with updating the pic,`" \ "`maybe coz I'm not an admin,`" \ "`or don't have enough rights.`" INVALID_MEDIA = "`Invalid Extension`" BANNED_RIGHTS = ChatBannedRights( until_date=None, view_messages=True, send_messages=True, send_media=True, send_stickers=True, send_gifs=True, send_games=True, send_inline=True, embed_links=True, ) UNBAN_RIGHTS = ChatBannedRights( until_date=None, send_messages=None, send_media=None, send_stickers=None, send_gifs=None, send_games=None, send_inline=None, embed_links=None, ) MUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True) UNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False) # ================================================ @register(outgoing=True, pattern="^.setgpic$") @errors_handler async def set_group_photo(gpic): """ For .setgpic command, changes the picture of a group """ if not gpic.is_group: await gpic.edit("`I don't think this is a group.`") return replymsg = await gpic.get_reply_message() chat = await gpic.get_chat() admin = chat.admin_rights creator = chat.creator photo = None if not admin and not creator: await gpic.edit(NO_ADMIN) return if replymsg and replymsg.media: if isinstance(replymsg.media, MessageMediaPhoto): photo = await gpic.client.download_media(message=replymsg.photo) elif "image" in replymsg.media.document.mime_type.split('/'): photo = await gpic.client.download_file(replymsg.media.document) else: await gpic.edit(INVALID_MEDIA) if photo: try: await gpic.client( EditPhotoRequest(gpic.chat_id, await gpic.client.upload_file(photo))) await gpic.edit(CHAT_PP_CHANGED) except PhotoCropSizeSmallError: await gpic.edit(PP_TOO_SMOL) except ImageProcessFailedError: await gpic.edit(PP_ERROR) @register(outgoing=True, pattern="^.promote(?: |$)(.*)") @errors_handler async def promote(promt): """ For .promote command, promotes the replied/tagged person """ # Get targeted chat chat = await promt.get_chat() # Grab admin status or creator in a chat admin = chat.admin_rights creator = chat.creator # If not admin and not creator, also return if not admin and not creator: await promt.edit(NO_ADMIN) return new_rights = ChatAdminRights(add_admins=False, invite_users=True, change_info=False, ban_users=True, delete_messages=True, pin_messages=True) await promt.edit("`Promoting...`") user, rank = await get_user_from_event(promt) if not rank: rank = "admeme" # Just in case. if user: pass else: return # Try to promote if current user is admin or creator try: await promt.client( EditAdminRequest(promt.chat_id, user.id, new_rights, rank)) await promt.edit("`Promoted Successfully! Now gib Party`") # If Telethon spit BadRequestError, assume # we don't have Promote permission except BadRequestError: await promt.edit(NO_PERM) return # Announce to the logging group if we have promoted successfully if BOTLOG: await promt.client.send_message( BOTLOG_CHATID, "#PROMOTE\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {promt.chat.title}(`{promt.chat_id}`)") @register(outgoing=True, pattern="^.demote(?: |$)(.*)") @errors_handler async def demote(dmod): """ For .demote command, demotes the replied/tagged person """ # Admin right check chat = await dmod.get_chat() admin = chat.admin_rights creator = chat.creator if not admin and not creator: await dmod.edit(NO_ADMIN) return # If passing, declare that we're going to demote await dmod.edit("`Demoting...`") rank = "admeme" # dummy rank, lol. user = await get_user_from_event(dmod) user = user[0] if user: pass else: return # New rights after demotion newrights = ChatAdminRights(add_admins=None, invite_users=None, change_info=None, ban_users=None, delete_messages=None, pin_messages=None) # Edit Admin Permission try: await dmod.client( EditAdminRequest(dmod.chat_id, user.id, newrights, rank)) # If we catch BadRequestError from Telethon # Assume we don't have permission to demote except BadRequestError: await dmod.edit(NO_PERM) return await dmod.edit("`Demoted this retard Successfully!`") # Announce to the logging group if we have demoted successfully if BOTLOG: await dmod.client.send_message( BOTLOG_CHATID, "#DEMOTE\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {dmod.chat.title}(`{dmod.chat_id}`)") @borg.on(admin_cmd(pattern="(ban|unban) ?(.*)")) async def _(event): # Space weirdness in regex required because argument is optional and other # commands start with ".unban" if event.fwd_from: return start = datetime.now() to_ban_id = None rights = None input_cmd = event.pattern_match.group(1) if input_cmd == "ban": rights = BANNED_RIGHTS elif input_cmd == "unban": rights = UNBAN_RIGHTS input_str = event.pattern_match.group(2) reply_msg_id = event.reply_to_msg_id if reply_msg_id: r_mesg = await event.get_reply_message() to_ban_id = r_mesg.from_id elif input_str and "all" not in input_str: to_ban_id = int(input_str) else: return False try: await borg(EditBannedRequest(event.chat_id, to_ban_id, rights)) except (Exception) as exc: await event.edit(str(exc)) else: await event.edit(f"{input_cmd}ned Successfully!") @borg.on(admin_cmd(pattern="pgs ?(.*)")) async def _(event): if event.fwd_from: return if event.reply_to_msg_id: i = 1 msgs = [] from_user = None input_str = event.pattern_match.group(1) if input_str: from_user = await borg.get_entity(input_str) logger.info(from_user) async for message in borg.iter_messages( event.chat_id, min_id=event.reply_to_msg_id, from_user=from_user ): i = i + 1 msgs.append(message) if len(msgs) == 100: await borg.delete_messages(event.chat_id, msgs, revoke=True) msgs = [] if len(msgs) <= 100: await borg.delete_messages(event.chat_id, msgs, revoke=True) msgs = [] await event.delete() else: await event.edit("**PURGE** Failed!") @borg.on(admin_cmd(pattern="(ban|unban) ?(.*)")) async def _(event): # Space weirdness in regex required because argument is optional and other # commands start with ".unban" if event.fwd_from: return start = datetime.now() to_ban_id = None rights = None input_cmd = event.pattern_match.group(1) if input_cmd == "ban": rights = BANNED_RIGHTS elif input_cmd == "unban": rights = UNBAN_RIGHTS input_str = event.pattern_match.group(2) reply_msg_id = event.reply_to_msg_id if reply_msg_id: r_mesg = await event.get_reply_message() to_ban_id = r_mesg.from_id elif input_str and "all" not in input_str: to_ban_id = int(input_str) else: return False try: await borg(EditBannedRequest(event.chat_id, to_ban_id, rights)) except (Exception) as exc: await event.edit(str(exc)) else: await event.edit(f"{input_cmd}ned Successfully!") @register(incoming=True) @errors_handler async def muter(moot): """ Used for deleting the messages of muted people """ try: from userbot.modules.sql_helper.spam_mute_sql import is_muted from userbot.modules.sql_helper.gmute_sql import is_gmuted except AttributeError: return muted = is_muted(moot.chat_id) gmuted = is_gmuted(moot.sender_id) rights = ChatBannedRights( until_date=None, send_messages=True, send_media=True, send_stickers=True, send_gifs=True, send_games=True, send_inline=True, embed_links=True, ) if muted: for i in muted: if str(i.sender) == str(moot.sender_id): await moot.delete() await moot.client( EditBannedRequest(moot.chat_id, moot.sender_id, rights)) for i in gmuted: if i.sender == str(moot.sender_id): await moot.delete() @borg.on(admin_cmd(pattern="affk(?: |$)(.*)")) @errors_handler async def promote(promt): """ For .promote command, promotes the replied/tagged person """ # Get targeted chat chat = await promt.get_chat() # Grab admin status or creator in a chat admin = chat.admin_rights creator = chat.creator new_rights = ChatAdminRights(add_admins=False, invite_users=True, change_info=False, ban_users=True, delete_messages=True, pin_messages=True) await promt.edit("`Promoting...`") user, rank = await get_user_from_event(promt) if not rank: rank = "admeme" # Just in case. if user: pass else: return # Try to promote if current user is admin or creator try: await promt.client( EditAdminRequest(promt.chat_id, user.id, new_rights, rank)) await promt.edit("`Promoted Successfully! Now gib Party`") # If Telethon spit BadRequestError, assume # we don't have Promote permission except BadRequestError: await promt.edit(NO_PERM) return # Announce to the logging group if we have promoted successfully if BOTLOG: await promt.client.send_message( BOTLOG_CHATID, "#PROMOTE\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {promt.chat.title}(`{promt.chat_id}`)") @register(outgoing=True, pattern="^.gmute(?: |$)(.*)") @errors_handler async def gspider(gspdr): """ For .gmute command, globally mutes the replied/tagged person """ # Admin or creator check chat = await gspdr.get_chat() admin = chat.admin_rights creator = chat.creator # If not admin and not creator, return if not admin and not creator: await gspdr.edit(NO_ADMIN) return # Check if the function running under SQL mode try: from userbot.modules.sql_helper.gmute_sql import gmute except AttributeError: await gspdr.edit(NO_SQL) return user, reason = await get_user_from_event(gspdr) if user: pass else: return # If pass, inform and start gmuting await gspdr.edit("`Grabs a huge, sticky duct tape!`") if gmute(user.id) is False: await gspdr.edit( '`Error! User probably already gmuted.\nRe-rolls the tape.`') else: if reason: await gspdr.edit(f"`Globally taped!`Reason: {reason}") else: await gspdr.edit("`Globally taped!`") if BOTLOG: await gspdr.client.send_message( BOTLOG_CHATID, "#GMUTE\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {gspdr.chat.title}(`{gspdr.chat_id}`)") @register(outgoing=True, pattern="^.delusers(?: |$)(.*)") @errors_handler async def rm_deletedacc(show): """ For .delusers command, list all the ghost/deleted accounts in a chat. """ if not show.is_group: await show.edit("`I don't think this is a group.`") return con = show.pattern_match.group(1) del_u = 0 del_status = "`No deleted accounts found, Group is cleaned as Hell`" if con != "clean": await show.edit("`Searching for zombie accounts...`") async for user in show.client.iter_participants(show.chat_id, aggressive=True): if user.deleted: del_u += 1 await sleep(1) if del_u > 0: del_status = f"Found **{del_u}** deleted account(s) in this group,\ \nclean them by using .delusers clean" await show.edit(del_status) return # Here laying the sanity check chat = await show.get_chat() admin = chat.admin_rights creator = chat.creator # Well if not admin and not creator: await show.edit("`I am not an admin here!`") return await show.edit("`Deleting deleted accounts...\nOh I can do that?!?!`") del_u = 0 del_a = 0 async for user in show.client.iter_participants(show.chat_id): if user.deleted: try: await show.client( EditBannedRequest(show.chat_id, user.id, BANNED_RIGHTS)) except ChatAdminRequiredError: await show.edit("`I don't have ban rights in this group`") return except UserAdminInvalidError: del_u -= 1 del_a += 1 await show.client( EditBannedRequest(show.chat_id, user.id, UNBAN_RIGHTS)) del_u += 1 if del_u > 0: del_status = f"Cleaned **{del_u}** deleted account(s)" if del_a > 0: del_status = f"Cleaned **{del_u}** deleted account(s) \ \n**{del_a}** deleted admin accounts are not removed" await show.edit(del_status) await sleep(2) await show.delete() if BOTLOG: await show.client.send_message( BOTLOG_CHATID, "#CLEANUP\n" f"Cleaned **{del_u}** deleted account(s) !!\ \nCHAT: {show.chat.title}(`{show.chat_id}`)") @register(outgoing=True, pattern="^.admins$") @errors_handler async def get_admin(show): """ For .admins command, list all of the admins of the chat. """ info = await show.client.get_entity(show.chat_id) title = info.title if info.title else "this chat" mentions = f'<b>Admins in {title}:</b> \n' try: async for user in show.client.iter_participants( show.chat_id, filter=ChannelParticipantsAdmins): if not user.deleted: link = f"<a href=\"tg://user?id={user.id}\">{user.first_name}</a>" userid = f"<code>{user.id}</code>" mentions += f"\n{link} {userid}" else: mentions += f"\nDeleted Account <code>{user.id}</code>" except ChatAdminRequiredError as err: mentions += " " + str(err) + "\n" await show.edit(mentions, parse_mode="html") @register(outgoing=True, pattern="^.pin(?: |$)(.*)") @errors_handler async def pin(msg): """ For .pin command, pins the replied/tagged message on the top the chat. """ # Admin or creator check chat = await msg.get_chat() admin = chat.admin_rights creator = chat.creator # If not admin and not creator, return if not admin and not creator: await msg.edit(NO_ADMIN) return to_pin = msg.reply_to_msg_id if not to_pin: await msg.edit("`Reply to a message to pin it.`") return options = msg.pattern_match.group(1) is_silent = True if options.lower() == "loud": is_silent = False try: await msg.client( UpdatePinnedMessageRequest(msg.to_id, to_pin, is_silent)) except BadRequestError: await msg.edit(NO_PERM) return await msg.edit("`Pinned Successfully!`") user = await get_user_from_id(msg.from_id, msg) if BOTLOG: await msg.client.send_message( BOTLOG_CHATID, "#PIN\n" f"ADMIN: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {msg.chat.title}(`{msg.chat_id}`)\n" f"LOUD: {not is_silent}") @register(outgoing=True, pattern="^.kick(?: |$)(.*)") @errors_handler async def kick(usr): """ For .kick command, kicks the replied/tagged person from the group. """ # Admin or creator check chat = await usr.get_chat() admin = chat.admin_rights creator = chat.creator # If not admin and not creator, return if not admin and not creator: await usr.edit(NO_ADMIN) return user, reason = await get_user_from_event(usr) if not user: await usr.edit("`Couldn't fetch user.`") return await usr.edit("`Kicking...`") try: await usr.client.kick_participant(usr.chat_id, user.id) await sleep(.5) except Exception as e: await usr.edit(NO_PERM + f"\n{str(e)}") return if reason: await usr.edit( f"`Kicked` [{user.first_name}](tg://user?id={user.id})`!`\nReason: {reason}" ) else: await usr.edit( f"`Kicked` [{user.first_name}](tg://user?id={user.id})`!`") if BOTLOG: await usr.client.send_message( BOTLOG_CHATID, "#KICK\n" f"USER: [{user.first_name}](tg://user?id={user.id})\n" f"CHAT: {usr.chat.title}(`{usr.chat_id}`)\n") @register(outgoing=True, pattern="^.users ?(.*)") @errors_handler async def get_users(show): """ For .users command, list all of the users in a chat. """ info = await show.client.get_entity(show.chat_id) title = info.title if info.title else "this chat" mentions = 'Users in {}: \n'.format(title) try: if not show.pattern_match.group(1): async for user in show.client.iter_participants(show.chat_id): if not user.deleted: mentions += f"\n[{user.first_name}](tg://user?id={user.id}) `{user.id}`" else: mentions += f"\nDeleted Account `{user.id}`" else: searchq = show.pattern_match.group(1) async for user in show.client.iter_participants( show.chat_id, search=f'{searchq}'): if not user.deleted: mentions += f"\n[{user.first_name}](tg://user?id={user.id}) `{user.id}`" else: mentions += f"\nDeleted Account `{user.id}`" except ChatAdminRequiredError as err: mentions += " " + str(err) + "\n" try: await show.edit(mentions) except MessageTooLongError: await show.edit( "Damn, this is a huge group. Uploading users lists as file.") file = open("userslist.txt", "w+") file.write(mentions) file.close() await show.client.send_file( show.chat_id, "userslist.txt", caption='Users in {}'.format(title), reply_to=show.id, ) remove("userslist.txt") async def get_user_from_event(event): """ Get the user from argument or replied message. """ args = event.pattern_match.group(1).split(' ', 1) extra = None if event.reply_to_msg_id: previous_message = await event.get_reply_message() user_obj = await event.client.get_entity(previous_message.from_id) extra = event.pattern_match.group(1) elif args: user = args[0] if len(args) == 2: extra = args[1] if user.isnumeric(): user = int(user) if not user: await event.edit("`Pass the user's username, id or reply!`") return if event.message.entities is not None: probable_user_mention_entity = event.message.entities[0] if isinstance(probable_user_mention_entity, MessageEntityMentionName): user_id = probable_user_mention_entity.user_id user_obj = await event.client.get_entity(user_id) return user_obj try: user_obj = await event.client.get_entity(user) except (TypeError, ValueError) as err: await event.edit(str(err)) return None return user_obj, extra async def get_user_from_id(user, event): if isinstance(user, str): user = int(user) try: user_obj = await event.client.get_entity(user) except (TypeError, ValueError) as err: await event.edit(str(err)) return None return user_obj CMD_HELP.update({ "admin": ".promote <username/reply> <custom rank (optional)>\ \nUsage: Provides admin rights to the person in the chat.\ \n\n.demote <username/reply>\ \nUsage: Revokes the person's admin permissions in the chat.\ \n\n.ban <username/reply> <reason (optional)>\ \nUsage: Bans the person off your chat.\ \n\n.unban <username/reply>\ \nUsage: Removes the ban from the person in the chat.\ \n\n.mute <username/reply> <reason (optional)>\ \nUsage: Mutes the person in the chat, works on admins too.\ \n\n.unmute <username/reply>\ \nUsage: Removes the person from the muted list.\ \n\n.gmute <username/reply> <reason (optional)>\ \nUsage: Mutes the person in all groups you have in common with them.\ \n\n.ungmute <username/reply>\ \nUsage: Reply someone's message with .ungmute to remove them from the gmuted list.\ \n\n.delusers\ \nUsage: Searches for deleted accounts in a group. Use .delusers clean to remove deleted accounts from the group.\ \n\n.admins\ \nUsage: Retrieves a list of admins in the chat.\ \n\n.users or .users <name of member>\ \nUsage: Retrieves all (or queried) users in the chat.\ \n\n.setgppic <reply to image>\ \nUsage: Changes the group's display picture." })
/** * Auto-generated action file for "ServiceBusManagementClient (servicebus)" API. * * Generated at: 2019-06-11T15:14:17.351Z * Mass generator version: 1.1.0 * * flowground :- Telekom iPaaS / azure-com-servicebus-connector * Copyright © 2019, Deutsche Telekom AG * contact: flowground@telekom.de * * All files of this connector are licensed under the Apache 2.0 License. For details * see the file LICENSE on the toplevel directory. * * * Operation: 'Topics_Delete' * Endpoint Path: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}' * Method: 'delete' * */ const Swagger = require('swagger-client'); const processWrapper = require('../services/process-wrapper'); const spec = require('../spec.json'); // this wrapers offers a simplified emitData(data) function module.exports.process = processWrapper(processAction); // parameter names for this call const PARAMETERS = [ "resourceGroupName", "namespaceName", "topicName", "api-version", "subscriptionId" ]; // mappings from connector field names to API field names const FIELD_MAP = { "resourceGroupName": "resourceGroupName", "namespaceName": "namespaceName", "topicName": "topicName", "api_version": "api-version", "subscriptionId": "subscriptionId" }; function processAction(msg, cfg) { var isVerbose = process.env.debug || cfg.verbose; if (isVerbose) { console.log(`---MSG: ${JSON.stringify(msg)}`); console.log(`---CFG: ${JSON.stringify(cfg)}`); console.log(`---ENV: ${JSON.stringify(process.env)}`); } const contentType = undefined; const body = msg.body; mapFieldNames(body); let parameters = {}; for(let param of PARAMETERS) { parameters[param] = body[param]; } // credentials for this operation let securities = {}; securities['azure_auth'] = {token: cfg['auth_azure_auth']}; let callParams = { spec: spec, operationId: 'Topics_Delete', pathName: '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ServiceBus/namespaces/{namespaceName}/topics/{topicName}', method: 'delete', parameters: parameters, requestContentType: contentType, requestBody: body.requestBody, securities: {authorized: securities}, server: spec.servers[cfg.server] || cfg.otherServer, }; if (isVerbose) { let out = Object.assign({}, callParams); out.spec = '[omitted]'; console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`); } // Call operation via Swagger client return Swagger.execute(callParams).then(data => { // emit a single message with data this.emitData(data); // if the response contains an array of entities, you can emit them one by one: // data.obj.someItems.forEach((item) => { // this.emitData(item); // } }); } function mapFieldNames(obj) { if(Array.isArray(obj)) { obj.forEach(mapFieldNames); } else if(typeof obj === 'object' && obj) { Object.keys(obj).forEach(key => { mapFieldNames(obj[key]); let goodKey = FIELD_MAP[key]; if(goodKey && goodKey !== key) { obj[goodKey] = obj[key]; delete obj[key]; } }); } }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["moment-locale-gom-latn-js"],{"0caa":function(a,e,n){(function(a,e){e(n("c1df"))})(0,(function(a){"use strict"; //! moment.js locale configuration function e(a,e,n,r){var o={s:["thoddea sekondamni","thodde sekond"],ss:[a+" sekondamni",a+" sekond"],m:["eka mintan","ek minut"],mm:[a+" mintamni",a+" mintam"],h:["eka voran","ek vor"],hh:[a+" voramni",a+" voram"],d:["eka disan","ek dis"],dd:[a+" disamni",a+" dis"],M:["eka mhoinean","ek mhoino"],MM:[a+" mhoineamni",a+" mhoine"],y:["eka vorsan","ek voros"],yy:[a+" vorsamni",a+" vorsam"]};return r?o[n][0]:o[n][1]}var n=a.defineLocale("gom-latn",{months:{standalone:"Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr".split("_"),format:"Janerachea_Febrerachea_Marsachea_Abrilachea_Maiachea_Junachea_Julaiachea_Agostachea_Setembrachea_Otubrachea_Novembrachea_Dezembrachea".split("_"),isFormat:/MMMM(\s)+D[oD]?/},monthsShort:"Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.".split("_"),monthsParseExact:!0,weekdays:"Aitar_Somar_Mongllar_Budhvar_Birestar_Sukrar_Son'var".split("_"),weekdaysShort:"Ait._Som._Mon._Bud._Bre._Suk._Son.".split("_"),weekdaysMin:"Ai_Sm_Mo_Bu_Br_Su_Sn".split("_"),weekdaysParseExact:!0,longDateFormat:{LT:"A h:mm [vazta]",LTS:"A h:mm:ss [vazta]",L:"DD-MM-YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY A h:mm [vazta]",LLLL:"dddd, MMMM Do, YYYY, A h:mm [vazta]",llll:"ddd, D MMM YYYY, A h:mm [vazta]"},calendar:{sameDay:"[Aiz] LT",nextDay:"[Faleam] LT",nextWeek:"[Fuddlo] dddd[,] LT",lastDay:"[Kal] LT",lastWeek:"[Fattlo] dddd[,] LT",sameElse:"L"},relativeTime:{future:"%s",past:"%s adim",s:e,ss:e,m:e,mm:e,h:e,hh:e,d:e,dd:e,M:e,MM:e,y:e,yy:e},dayOfMonthOrdinalParse:/\d{1,2}(er)/,ordinal:function(a,e){switch(e){case"D":return a+"er";default:case"M":case"Q":case"DDD":case"d":case"w":case"W":return a}},week:{dow:1,doy:4},meridiemParse:/rati|sokallim|donparam|sanje/,meridiemHour:function(a,e){return 12===a&&(a=0),"rati"===e?a<4?a:a+12:"sokallim"===e?a:"donparam"===e?a>12?a:a+12:"sanje"===e?a+12:void 0},meridiem:function(a,e,n){return a<4?"rati":a<12?"sokallim":a<16?"donparam":a<20?"sanje":"rati"}});return n}))}}]);
const Sections = [ { id: 'new-users', color: 'var(--primary)', title: 'New Users', subtitle: 'Reliability', prefix: '1', content: 'Keep your candidate users on the website by pointing out to key feature of your app/dashboard.', }, { id: 'new-hidden-features', color: '#007CF0', title: 'New/Hidden Features', subtitle: 'Visibility', prefix: '2', content: 'Show all of your hidden features to be able to make more efficient users. In that way, some of the pain use cases may be transform to easy things!', }, { id: 'shortcuts', color: '#00DFD8', title: 'Shortcuts', subtitle: 'Adaptivity', prefix: '3', content: 'Explain your long feature flows that can be manage more easily in short ways. Best for explaining shortcuts/automations.', }, ]; export { Sections };
// https://github.com/michael-ciniawsky/postcss-load-config module.exports = { "plugins": { // to edit target browsers: use "browserslist" field in package.json "autoprefixer": {} } }
import arrow from django.db.models import QuerySet from core.globals import logger from pyrogram import types from tasks.task_scaffold import TaskScaffold from ..base_response import BaseResponse class IterateChatHistoryTask(TaskScaffold): def iterate_chat_history_task(self, *args, **kwargs) -> BaseResponse: db_chats: QuerySet = self.db.telegram.get_chats_filter_by_analyzer( message_view_analyzer=True, ) if db_chats.exists(): for db_chat in db_chats: db_telegram_accounts = self.get_telegram_accounts(db_chat) if db_telegram_accounts is None or not len(db_telegram_accounts): # return BaseResponse().done(message='No Telegram Account is available now.') continue db_telegram_account = db_telegram_accounts[0] client = self.get_client(session_name=db_telegram_account.session_name) last_raw_message: 'types.Message' = self.get_last_valid_message(client, db_chat.chat_id) if last_raw_message is not None: now = arrow.utcnow().timestamp() for raw_message in self.iter_messages( client, db_chat.chat_id, last_raw_message.message_id, ): self.db.telegram.update_message_and_view( db_chat=db_chat, raw_message=raw_message, logger_account=db_telegram_account, now=now ) self.db.telegram.update_analyzer_metadata( analyzer=db_chat.message_view_analyzer, timestamp=now, ) else: return BaseResponse().done(message='No analyzer is enabled.') return BaseResponse().done()
import React from 'react'; import '../styles/CustomTag.css'; const CustomTag = ({ color, text }) => { return ( <div className={`ui ${color} label nonSelect`} >{text}</div> ) } export default CustomTag;
import { render } from '~/lib/gfm'; describe('gfm', () => { describe('render', () => { it('processes Commonmark and provides an ast to the renderer function', async () => { let result; await render({ markdown: 'This is text', renderer: (tree) => { result = tree; }, }); expect(result.type).toBe('root'); }); it('transforms raw HTML into individual nodes in the AST', async () => { let result; await render({ markdown: '<strong>This is bold text</strong>', renderer: (tree) => { result = tree; }, }); expect(result.children[0].children[0]).toMatchObject({ type: 'element', tagName: 'strong', properties: {}, }); }); it('returns the result of executing the renderer function', async () => { const result = await render({ markdown: '<strong>This is bold text</strong>', renderer: () => { return 'rendered tree'; }, }); expect(result).toBe('rendered tree'); }); }); });
/* * Document : app.js * Author : pixelcave * Description: UI Framework Custom Functionality (available to all pages) * */ var App = function() { // Helper variables - set in uiInit() var $lHtml, $lBody, $lPage, $lSidebar, $lSidebarScroll, $lSideOverlay, $lSideOverlayScroll, $lHeader, $lMain, $lFooter; /* ******************************************************************************************** * * BASE UI FUNCTIONALITY * * Functions which handle vital UI functionality such as main navigation and layout * They are auto initialized in every page * ********************************************************************************************* */ // User Interface init var uiInit = function() { // Set variables $lHtml = jQuery('html'); $lBody = jQuery('body'); $lPage = jQuery('#page-container'); $lSidebar = jQuery('#sidebar'); $lSidebarScroll = jQuery('#sidebar-scroll'); $lSideOverlay = jQuery('#side-overlay'); $lSideOverlayScroll = jQuery('#side-overlay-scroll'); $lHeader = jQuery('#header-navbar'); $lMain = jQuery('#main-container'); $lFooter = jQuery('#page-footer'); // Initialize Tooltips jQuery('[data-toggle="tooltip"], .js-tooltip').tooltip({ container: 'body', animation: false }); // Initialize Popovers jQuery('[data-toggle="popover"], .js-popover').popover({ container: 'body', animation: true, trigger: 'hover' }); // Initialize Tabs jQuery('[data-toggle="tabs"] a, .js-tabs a').click(function(e){ e.preventDefault(); jQuery(this).tab('show'); }); // Init form placeholder (for IE9) jQuery('.form-control').placeholder(); }; // Layout functionality var uiLayout = function() { // Resizes #main-container min height (push footer to the bottom) var $resizeTimeout; if ($lMain.length) { uiHandleMain(); jQuery(window).on('resize orientationchange', function(){ clearTimeout($resizeTimeout); $resizeTimeout = setTimeout(function(){ uiHandleMain(); }, 150); }); } // Init sidebar and side overlay custom scrolling uiHandleScroll('init'); // Init transparent header functionality (solid on scroll - used in frontend) if ($lPage.hasClass('header-navbar-fixed') && $lPage.hasClass('header-navbar-transparent')) { jQuery(window).on('scroll', function(){ if (jQuery(this).scrollTop() > 20) { $lPage.addClass('header-navbar-scroll'); } else { $lPage.removeClass('header-navbar-scroll'); } }); } // Call layout API on button click jQuery('[data-toggle="layout"]').on('click', function(){ var $btn = jQuery(this); uiLayoutApi($btn.data('action')); if ($lHtml.hasClass('no-focus')) { $btn.blur(); } }); }; // Resizes #main-container to fill empty space if exists var uiHandleMain = function() { var $hWindow = jQuery(window).height(); var $hHeader = $lHeader.outerHeight(); var $hFooter = $lFooter.outerHeight(); if ($lPage.hasClass('header-navbar-fixed')) { $lMain.css('min-height', $hWindow - $hFooter); } else { $lMain.css('min-height', $hWindow - ($hHeader + $hFooter)); } }; // Handles sidebar and side overlay custom scrolling functionality var uiHandleScroll = function($mode) { var $windowW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // Init scrolling if ($mode === 'init') { // Init scrolling only if required the first time uiHandleScroll(); // Handle scrolling on resize or orientation change var $sScrollTimeout; jQuery(window).on('resize orientationchange', function(){ clearTimeout($sScrollTimeout); $sScrollTimeout = setTimeout(function(){ uiHandleScroll(); }, 150); }); } else { // If screen width is greater than 991 pixels and .side-scroll is added to #page-container if ($windowW > 991 && $lPage.hasClass('side-scroll')) { // Turn scroll lock off (sidebar and side overlay - slimScroll will take care of it) jQuery($lSidebar).scrollLock('disable'); jQuery($lSideOverlay).scrollLock('disable'); // If sidebar scrolling does not exist init it.. if ($lSidebarScroll.length && (!$lSidebarScroll.parent('.slimScrollDiv').length)) { $lSidebarScroll.slimScroll({ height: $lSidebar.outerHeight(), color: '#fff', size: '5px', opacity : .35, wheelStep : 15, distance : '2px', railVisible: false, railOpacity: 1 }); } else { // ..else resize scrolling height $lSidebarScroll .add($lSidebarScroll.parent()) .css('height', $lSidebar.outerHeight()); } } else { // Turn scroll lock on (sidebar and side overlay) jQuery($lSidebar).scrollLock(); jQuery($lSideOverlay).scrollLock(); // If sidebar scrolling exists destroy it.. if ($lSidebarScroll.length && $lSidebarScroll.parent('.slimScrollDiv').length) { $lSidebarScroll .slimScroll({destroy: true}); $lSidebarScroll .attr('style', ''); } } } }; // Layout API var uiLayoutApi = function($mode) { var $windowW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; // Mode selection switch($mode) { case 'sidebar_pos_toggle': $lPage.toggleClass('sidebar-l sidebar-r'); break; case 'sidebar_pos_left': $lPage .removeClass('sidebar-r') .addClass('sidebar-l'); break; case 'sidebar_pos_right': $lPage .removeClass('sidebar-l') .addClass('sidebar-r'); break; case 'sidebar_toggle': if ($windowW > 991) { $lPage.toggleClass('sidebar-o'); } else { $lPage.toggleClass('sidebar-o-xs'); } break; case 'sidebar_open': if ($windowW > 991) { $lPage.addClass('sidebar-o'); } else { $lPage.addClass('sidebar-o-xs'); } break; case 'sidebar_close': if ($windowW > 991) { $lPage.removeClass('sidebar-o'); } else { $lPage.removeClass('sidebar-o-xs'); } break; case 'sidebar_mini_toggle': if ($windowW > 991) { if ($lPage.hasClass('sidebar-mini')) { $lPage.removeClass('sidebar-mini'); Cookies.remove('sidebarMini'); } else { $lPage.addClass('sidebar-mini'); Cookies.set('sidebarMini', 'true', { expires: 7 }); } } break; case 'sidebar_mini_on': if ($windowW > 991) { $lPage.addClass('sidebar-mini'); } break; case 'sidebar_mini_off': if ($windowW > 991) { $lPage.removeClass('sidebar-mini'); } break; case 'side_overlay_toggle': // If side overlay scrolling does not exist init it.. if ($lSideOverlayScroll.length && (!$lSideOverlayScroll.parent('.slimScrollDiv').length)) { $lSideOverlayScroll.slimScroll({ height: $lSideOverlay.outerHeight(), color: '#000', size: '5px', opacity : .35, wheelStep : 15, distance : '2px', railVisible: false, railOpacity: 1 }); } else { // ..else resize scrolling height $lSideOverlayScroll .add($lSideOverlayScroll.parent()) .css('height', $lSideOverlay.outerHeight()); } $lPage.toggleClass('side-overlay-o'); break; case 'side_overlay_open': $lPage.addClass('side-overlay-o'); break; case 'side_overlay_close': // If side overlay scrolling exists destroy it.. if ($lSideOverlayScroll.length && $lSideOverlayScroll.parent('.slimScrollDiv').length) { $lSideOverlayScroll .slimScroll({destroy: true}); $lSideOverlayScroll .attr('style', ''); } $lPage.removeClass('side-overlay-o'); break; case 'side_overlay_hoverable_toggle': $lPage.toggleClass('side-overlay-hover'); break; case 'side_overlay_hoverable_on': $lPage.addClass('side-overlay-hover'); break; case 'side_overlay_hoverable_off': $lPage.removeClass('side-overlay-hover'); break; case 'header_fixed_toggle': $lPage.toggleClass('header-navbar-fixed'); break; case 'header_fixed_on': $lPage.addClass('header-navbar-fixed'); break; case 'header_fixed_off': $lPage.removeClass('header-navbar-fixed'); break; case 'side_scroll_toggle': $lPage.toggleClass('side-scroll'); uiHandleScroll(); break; case 'side_scroll_on': $lPage.addClass('side-scroll'); uiHandleScroll(); break; case 'side_scroll_off': $lPage.removeClass('side-scroll'); uiHandleScroll(); break; default: return false; } }; // Main navigation functionality var uiNav = function() { // When a submenu link is clicked jQuery('[data-toggle="nav-submenu"]').on('click', function(e){ // Get link var $link = jQuery(this); // Get link's parent var $parentLi = $link.parent('li'); if ($parentLi.hasClass('open')) { // If submenu is open, close it.. $parentLi.removeClass('open'); } else { // .. else if submenu is closed, close all other (same level) submenus first before open it $link .closest('ul') .find('> li') .removeClass('open'); $parentLi .addClass('open'); } // Remove focus from submenu link if ($lHtml.hasClass('no-focus')) { $link.blur(); } return false; }); }; // Blocks options functionality var uiBlocks = function() { // Init default icons fullscreen and content toggle buttons uiBlocksApi(false, 'init'); // Call blocks API on option button click jQuery('[data-toggle="block-option"]').on('click', function(){ uiBlocksApi(jQuery(this).closest('.block'), jQuery(this).data('action')); }); }; // Blocks API var uiBlocksApi = function($block, $mode) { // Set default icons for fullscreen and content toggle buttons var $iconFullscreen = 'si si-size-fullscreen'; var $iconFullscreenActive = 'si si-size-actual'; var $iconContent = 'si si-arrow-up'; var $iconContentActive = 'si si-arrow-down'; if ($mode === 'init') { // Auto add the default toggle icons to fullscreen and content toggle buttons jQuery('[data-toggle="block-option"][data-action="fullscreen_toggle"]').each(function(){ var $this = jQuery(this); $this.html('<i class="' + (jQuery(this).closest('.block').hasClass('block-opt-fullscreen') ? $iconFullscreenActive : $iconFullscreen) + '"></i>'); }); jQuery('[data-toggle="block-option"][data-action="content_toggle"]').each(function(){ var $this = jQuery(this); $this.html('<i class="' + ($this.closest('.block').hasClass('block-opt-hidden') ? $iconContentActive : $iconContent) + '"></i>'); }); } else { // Get block element var $elBlock = ($block instanceof jQuery) ? $block : jQuery($block); // If element exists, procceed with blocks functionality if ($elBlock.length) { // Get block option buttons if exist (need them to update their icons) var $btnFullscreen = jQuery('[data-toggle="block-option"][data-action="fullscreen_toggle"]', $elBlock); var $btnToggle = jQuery('[data-toggle="block-option"][data-action="content_toggle"]', $elBlock); // Mode selection switch($mode) { case 'fullscreen_toggle': $elBlock.toggleClass('block-opt-fullscreen'); // Enable/disable scroll lock to block if ($elBlock.hasClass('block-opt-fullscreen')) { jQuery($elBlock).scrollLock(); } else { jQuery($elBlock).scrollLock('disable'); } // Update block option icon if ($btnFullscreen.length) { if ($elBlock.hasClass('block-opt-fullscreen')) { jQuery('i', $btnFullscreen) .removeClass($iconFullscreen) .addClass($iconFullscreenActive); } else { jQuery('i', $btnFullscreen) .removeClass($iconFullscreenActive) .addClass($iconFullscreen); } } if (typeof(init_table) === "function") { init_table(); } break; case 'fullscreen_on': $elBlock.addClass('block-opt-fullscreen'); // Enable scroll lock to block jQuery($elBlock).scrollLock(); // Update block option icon if ($btnFullscreen.length) { jQuery('i', $btnFullscreen) .removeClass($iconFullscreen) .addClass($iconFullscreenActive); } break; case 'fullscreen_off': $elBlock.removeClass('block-opt-fullscreen'); // Disable scroll lock to block jQuery($elBlock).scrollLock('disable'); // Update block option icon if ($btnFullscreen.length) { jQuery('i', $btnFullscreen) .removeClass($iconFullscreenActive) .addClass($iconFullscreen); } break; case 'content_toggle': $elBlock.toggleClass('block-opt-hidden'); // Update block option icon if ($btnToggle.length) { if ($elBlock.hasClass('block-opt-hidden')) { jQuery('i', $btnToggle) .removeClass($iconContent) .addClass($iconContentActive); } else { jQuery('i', $btnToggle) .removeClass($iconContentActive) .addClass($iconContent); } } break; case 'content_hide': $elBlock.addClass('block-opt-hidden'); // Update block option icon if ($btnToggle.length) { jQuery('i', $btnToggle) .removeClass($iconContent) .addClass($iconContentActive); } break; case 'content_show': $elBlock.removeClass('block-opt-hidden'); // Update block option icon if ($btnToggle.length) { jQuery('i', $btnToggle) .removeClass($iconContentActive) .addClass($iconContent); } break; case 'refresh_toggle': $elBlock.toggleClass('block-opt-refresh'); // Return block to normal state if the demostration mode is on in the refresh option button - data-action-mode="demo" if (jQuery('[data-toggle="block-option"][data-action="refresh_toggle"][data-action-mode="demo"]', $elBlock).length) { setTimeout(function(){ $elBlock.removeClass('block-opt-refresh'); }, 2000); } break; case 'state_loading': $elBlock.addClass('block-opt-refresh'); break; case 'state_normal': $elBlock.removeClass('block-opt-refresh'); break; case 'close': $elBlock.hide(); break; case 'open': $elBlock.show(); break; default: return false; } } } }; // Material inputs helper var uiForms = function() { jQuery('.form-material.floating > .form-control').each(function(){ var $input = jQuery(this); var $parent = $input.parent('.form-material'); if ($input.val()) { $parent.addClass('open'); } $input.on('change', function(){ if ($input.val()) { $parent.addClass('open'); } else { $parent.removeClass('open'); } }); }); }; // Set active color themes functionality var uiHandleTheme = function() { var $cssTheme = jQuery('#css-theme'); // When a color theme link is clicked jQuery('[data-toggle="theme"]').on('click', function(){ var $this = jQuery(this); var $theme = $this.data('theme'); var $css = $this.data('css'); Dolphin.loading(); jQuery.get(dolphin.theme_url, {theme: $theme}, function (res) { Dolphin.loading('hide'); if (res.code) { // Set this color theme link as active jQuery('[data-toggle="theme"]') .parent('li') .removeClass('active'); jQuery('[data-toggle="theme"][data-theme="' + $theme + '"]') .parent('li') .addClass('active'); // Update color theme if ($theme === 'default') { if ($cssTheme.length) { $cssTheme.remove(); } } else { if ($cssTheme.length) { $cssTheme.attr('href', $css); } else { jQuery('#css-main') .after('<link rel="stylesheet" id="css-theme" href="' + $css + '">'); } } $cssTheme = jQuery('#css-theme'); Dolphin.notify(res.msg, 'success'); } else { Dolphin.notify(res.msg, 'danger'); } }); }); }; // Scroll to element animation helper var uiScrollTo = function() { jQuery('[data-toggle="scroll-to"]').on('click', function(){ var $this = jQuery(this); var $target = $this.data('target'); var $speed = $this.data('speed') ? $this.data('speed') : 1000; jQuery('html, body').animate({ scrollTop: jQuery($target).offset().top }, $speed); }); }; // Toggle class helper var uiToggleClass = function() { jQuery('[data-toggle="class-toggle"]').on('click', function(){ var $el = jQuery(this); jQuery($el.data('target').toString()).toggleClass($el.data('class').toString()); if ($lHtml.hasClass('no-focus')) { $el.blur(); } }); }; // Add the correct copyright year var uiYearCopy = function() { var $date = new Date(); var $yearCopy = jQuery('.js-year-copy'); if ($date.getFullYear() === 2015) { $yearCopy.html('2015'); } else { $yearCopy.html('2015-' + $date.getFullYear().toString().substr(2,2)); } }; // Manage page loading screen functionality var uiLoader = function($mode) { var $lpageLoader = jQuery('#page-loader'); if ($mode === 'show') { if ($lpageLoader.length) { $lpageLoader.fadeIn(250); } else { $lBody.prepend('<div id="page-loader"></div>'); } } else if ($mode === 'hide') { if ($lpageLoader.length) { $lpageLoader.fadeOut(250); } } return false; }; /* ******************************************************************************************** * * UI HELPERS (ON DEMAND) * * Third party plugin inits or various custom user interface helpers to extend functionality * They need to be called in a page to be initialized. They are included here to be easy to * init them on demand on multiple pages (usually repeated init code in common components) * ******************************************************************************************** */ /* * Print Page functionality * * App.initHelper('print-page'); * */ var uiHelperPrint = function() { // Store all #page-container classes var $pageCls = $lPage.prop('class'); // Remove all classes from #page-container $lPage.prop('class', ''); // Print the page window.print(); // Restore all #page-container classes $lPage.prop('class', $pageCls); }; /* * Custom Table functionality such as section toggling or checkable rows * * App.initHelper('table-tools'); * */ // Table sections functionality var uiHelperTableToolsSections = function(){ // For each table jQuery('.js-table-sections').each(function(){ var $table = jQuery(this); // When a row is clicked in tbody.js-table-sections-header jQuery('.js-table-sections-header > tr', $table).on('click', function(e) { var $row = jQuery(this); var $tbody = $row.parent('tbody'); if (! $tbody.hasClass('open')) { jQuery('tbody', $table).removeClass('open'); } $tbody.toggleClass('open'); }); }); }; // Checkable table functionality var uiHelperTableToolsCheckable = function() { // For each table jQuery('.js-table-checkable').each(function(){ var $table = jQuery(this); var $table_target = jQuery('.js-table-checkable-target'); // When a checkbox is clicked in thead jQuery('thead input:checkbox', $table).on('click', function() { var $checkedStatus = jQuery(this).prop('checked'); // Check or uncheck all checkboxes in tbody jQuery('tbody input[name="ids[]"]:checkbox', $table_target).each(function() { var $checkbox = jQuery(this); $checkbox.prop('checked', $checkedStatus); uiHelperTableToolscheckRow($checkbox, $checkedStatus); }); }); // When a checkbox is clicked in tbody jQuery('tbody input[name="ids[]"]:checkbox', $table_target).on('click', function() { var $checkbox = jQuery(this); uiHelperTableToolscheckRow($checkbox, $checkbox.prop('checked')); }); }); jQuery('.js-table-checkable-left').each(function(){ var $table = jQuery(this); var $table_target = jQuery('.js-table-checkable-target-left'); var $tr = $table_target.find('tr'); // When a checkbox is clicked in thead jQuery('thead input:checkbox', $table).on('click', function() { var $checkedStatus = jQuery(this).prop('checked'); // Check or uncheck all checkboxes in tbody jQuery('tbody input[name="ids[]"]:checkbox', $table_target).each(function() { var $checkbox = jQuery(this); var $index = $table_target.find('input[name="ids[]"]:checkbox').index($(this)); $checkbox.prop('checked', $checkedStatus); uiHelperTableToolscheckRow($checkbox, $checkedStatus, $index); }); }); // When a checkbox is clicked in tbody jQuery('tbody input[name="ids[]"]:checkbox', $table_target).on('click', function(e) { var $checkbox = jQuery(this); var $index = $table_target.find('input[name="ids[]"]:checkbox').index($(this)); uiHelperTableToolscheckRow($checkbox, $checkbox.prop('checked'), $index); }); }); }; // Checkable table functionality helper - Checks or unchecks table row var uiHelperTableToolscheckRow = function($checkbox, $checkedStatus, $index) { if ($checkedStatus) { $checkbox .closest('tr') .addClass('active'); $('.js-table-checkable-target').find('tr').eq($index).addClass('active'); $('#builder-table-right-body-inner').find('tr').eq($index).addClass('active'); } else { $checkbox .closest('tr') .removeClass('active'); $('.js-table-checkable-target').find('tr').eq($index).removeClass('active'); $('#builder-table-right-body-inner').find('tr').eq($index).removeClass('active'); } }; /* * jQuery Appear, for more examples you can check out https://github.com/bas2k/jquery.appear * * App.initHelper('appear'); * */ var uiHelperAppear = function(){ // Add a specific class on elements (when they become visible on scrolling) jQuery('[data-toggle="appear"]').each(function(){ var $windowW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; var $this = jQuery(this); var $class = $this.data('class') ? $this.data('class') : 'animated fadeIn'; var $offset = $this.data('offset') ? $this.data('offset') : 0; var $timeout = ($lHtml.hasClass('ie9') || $windowW < 992) ? 0 : ($this.data('timeout') ? $this.data('timeout') : 0); $this.appear(function() { setTimeout(function(){ $this .removeClass('visibility-hidden') .addClass($class); }, $timeout); },{accY: $offset}); }); }; /* * jQuery Appear + jQuery countTo, for more examples you can check out https://github.com/bas2k/jquery.appear and https://github.com/mhuggins/jquery-countTo * * App.initHelper('appear-countTo'); * */ var uiHelperAppearCountTo = function(){ // Init counter functionality jQuery('[data-toggle="countTo"]').each(function(){ var $this = jQuery(this); var $after = $this.data('after'); var $before = $this.data('before'); var $speed = $this.data('speed') ? $this.data('speed') : 1500; var $interval = $this.data('interval') ? $this.data('interval') : 15; $this.appear(function() { $this.countTo({ speed: $speed, refreshInterval: $interval, onComplete: function() { if($after) { $this.html($this.html() + $after); } else if ($before) { $this.html($before + $this.html()); } } }); }); }); }; /* * jQuery SlimScroll, for more examples you can check out http://rocha.la/jQuery-slimScroll * * App.initHelper('slimscroll'); * */ var uiHelperSlimscroll = function(){ // Init slimScroll functionality jQuery('[data-toggle="slimscroll"]').each(function(){ var $this = jQuery(this); var $height = $this.data('height') ? $this.data('height') : '200px'; var $size = $this.data('size') ? $this.data('size') : '5px'; var $position = $this.data('position') ? $this.data('position') : 'right'; var $color = $this.data('color') ? $this.data('color') : '#000'; var $avisible = $this.data('always-visible') ? true : false; var $rvisible = $this.data('rail-visible') ? true : false; var $rcolor = $this.data('rail-color') ? $this.data('rail-color') : '#999'; var $ropacity = $this.data('rail-opacity') ? $this.data('rail-opacity') : .3; $this.slimScroll({ height: $height, size: $size, position: $position, color: $color, alwaysVisible: $avisible, railVisible: $rvisible, railColor: $rcolor, railOpacity: $ropacity }); }); }; /* ******************************************************************************************** * * All the following helpers require each plugin's resources (JS, CSS) to be included in order to work * ******************************************************************************************** */ /* * Magnific Popup functionality, for more examples you can check out http://dimsemenov.com/plugins/magnific-popup/ * * App.initHelper('magnific-popup'); * */ var uiHelperMagnific = function(){ // Simple Gallery init jQuery('.js-gallery').each(function(){ jQuery(this).viewer({url: 'data-original'}); }); // Advanced Gallery init jQuery('.js-gallery-advanced').each(function(){ jQuery(this).magnificPopup({ delegate: 'a.img-lightbox', type: 'image', gallery: { enabled: true } }); }); }; /* * CKEditor init, for more examples you can check out http://ckeditor.com/ * * App.initHelper('ckeditor'); * */ var uiHelperCkeditor = function(){ // Disable auto init when contenteditable property is set to true CKEDITOR.disableAutoInline = true; // Init inline text editor jQuery('.js-ckeditor-inlin').each(function () { var editor_id = $(this).attr('id'); CKEDITOR.inline(editor_id); }); // Init full text editor jQuery('.js-ckeditor').each(function () { var editor_id = $(this).attr('id'); var editor = CKEDITOR.replace(editor_id, { filebrowserImageUploadUrl: dolphin.ckeditor_img_upload_url, image_previewText: ' ', height: $(this).data('height') || 400, width: $(this).data('width') || '100%', toolbarCanCollapse: true }); editor.on('change', function( evt ) { editor.updateElement(); }); }); }; /* * Summernote init, for more examples you can check out http://summernote.org/ * * App.initHelper('summernote'); * */ var uiHelperSummernote = function(){ // Init text editor in air mode (inline) jQuery('.js-summernote-air').summernote({ airMode: true }); // Init full text editor jQuery('.js-summernote').each(function () { var $summernote = $(this); $summernote.summernote({ width: $summernote.data('width') || '100%', height: $summernote.data('height') || 350, minHeight: null, maxHeight: null, lang: 'zh-CN', callbacks: { onImageUpload: function(files) { //上传图片到服务器 var formData = new FormData(); $.each(files, function () { formData.append('file', $(this)[0]); $.ajax({ url : dolphin.image_upload_url,//后台文件上传接口 type : 'POST', data : formData, cache: false, processData : false, contentType : false, success : function(res) { if (res.code) { $summernote.summernote('insertImage', res.path); } else { Dolphin.notify(res.info, 'danger'); } } }); }); } } }); }); }; /* * Slick init, for more examples you can check out http://kenwheeler.github.io/slick/ * * App.initHelper('slick'); * */ var uiHelperSlick = function(){ // Get each slider element (with .js-slider class) jQuery('.js-slider').each(function(){ var $slider = jQuery(this); // Get each slider's init data var $sliderArrows = $slider.data('slider-arrows') ? $slider.data('slider-arrows') : false; var $sliderDots = $slider.data('slider-dots') ? $slider.data('slider-dots') : false; var $sliderNum = $slider.data('slider-num') ? $slider.data('slider-num') : 1; var $sliderAuto = $slider.data('slider-autoplay') ? $slider.data('slider-autoplay') : false; var $sliderAutoSpeed = $slider.data('slider-autoplay-speed') ? $slider.data('slider-autoplay-speed') : 3000; // Init slick slider $slider.slick({ arrows: $sliderArrows, dots: $sliderDots, slidesToShow: $sliderNum, autoplay: $sliderAuto, autoplaySpeed: $sliderAutoSpeed }); }); }; /* * Bootstrap Datepicker init, for more examples you can check out https://github.com/eternicode/bootstrap-datepicker * * App.initHelper('datepicker'); * */ var uiHelperDatepicker = function(){ // Init datepicker (with .js-datepicker and .input-daterange class) jQuery('.js-datepicker').add('.input-daterange').each(function () { var $datepicker = jQuery(this); var $weekStart = $datepicker.data('week-start') || 1; var $autoclose = $datepicker.data('autoclose') === undefined ? true : $datepicker.data('autoclose'); var $todayHighlight = $datepicker.data('today-highlight') === undefined ? true : $datepicker.data('today-highlight'); var $language = $datepicker.data('language') || 'zh-CN'; var $startDate = $datepicker.data('start-date') === undefined ? -Infinity : $datepicker.data('start-date'); var $endDate = $datepicker.data('end-date') === undefined ? Infinity : $datepicker.data('end-date'); var $startView = $datepicker.data('start-view') === undefined ? 0 : $datepicker.data('start-view'); var $minViewMode = $datepicker.data('min-view-mode') === undefined ? 0 : $datepicker.data('min-view-mode'); var $maxViewMode = $datepicker.data('max-view-mode') === undefined ? 4 : $datepicker.data('max-view-mode'); var $todayBtn = $datepicker.data('today-btn') === undefined ? false : $datepicker.data('today-btn'); var $clearBtn = $datepicker.data('clear-btn') === undefined ? false : $datepicker.data('clear-btn'); var $orientation = $datepicker.data('orientation') === undefined ? "auto" : $datepicker.data('orientation'); var $multidate = $datepicker.data('multidate') === undefined ? false : $datepicker.data('multidate'); var $multidateSeparator = $datepicker.data('multidate-separator') === undefined ? ',' : $datepicker.data('multidate-separator'); var $daysOfWeekDisabled = $datepicker.data('days-of-week-disabled') === undefined ? [] : $datepicker.data('days-of-week-disabled'); var $daysOfWeekHighlighted = $datepicker.data('days-of-week-highlighted') === undefined ? [] : $datepicker.data('days-of-week-highlighted'); var $calendarWeeks = $datepicker.data('calendar-weeks') === undefined ? false : $datepicker.data('calendar-weeks'); var $keyboardNavigation = $datepicker.data('keyboard-navigation') === undefined ? true : $datepicker.data('keyboard-navigation'); var $forceParse = $datepicker.data('force-parse') === undefined ? true : $datepicker.data('force-parse'); var $datesDisabled = $datepicker.data('dates-disabled') === undefined ? [] : $datepicker.data('dates-disabled'); var $toggleActive = $datepicker.data('toggle-active') === undefined ? false : $datepicker.data('toggle-active'); $datepicker.datepicker({ weekStart: $weekStart, autoclose: $autoclose, todayHighlight: $todayHighlight, language: $language, startDate: $startDate, endDate: $endDate, startView: $startView, minViewMode: $minViewMode, maxViewMode: $maxViewMode, todayBtn: $todayBtn, clearBtn: $clearBtn, orientation: $orientation, multidate: $multidate, multidateSeparator: $multidateSeparator, daysOfWeekDisabled: $daysOfWeekDisabled, daysOfWeekHighlighted: $daysOfWeekHighlighted, calendarWeeks: $calendarWeeks, keyboardNavigation: $keyboardNavigation, forceParse: $forceParse, datesDisabled: $datesDisabled, toggleActive: $toggleActive }); }); }; /* * 日期时间范围 * * App.initHelper('daterangepicker'); * */ var uiHelperDaterangepicker = function () { jQuery('.js-daterangepicker').each(function () { var $daterangepicker = jQuery(this); var $format = $daterangepicker.data('format') === undefined ? "YYYY-MM-DD" : $daterangepicker.data('format'); var $autoUpdateInput = $daterangepicker.data('auto-update-input') === undefined ? false : $daterangepicker.data('auto-update-input'); var $showDropdowns = $daterangepicker.data('show-dropdowns') === undefined ? true : $daterangepicker.data('show-dropdowns'); var $singleDatePicker = $daterangepicker.data('single-date-picker') === undefined ? false : $daterangepicker.data('single-date-picker'); $daterangepicker.daterangepicker({ autoUpdateInput: $autoUpdateInput, showDropdowns: $showDropdowns, locale: { "format": $format, "separator": " - ", "applyLabel": "确定", "cancelLabel": "取消", "fromLabel": "From", "toLabel": "To", "customRangeLabel": "Custom", "weekLabel": "W", "daysOfWeek": ["日", "一", "二", "三", "四", "五", "六"], "monthNames": ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"] } }); if (!$singleDatePicker) { $daterangepicker.on('apply.daterangepicker', function(ev, picker) { $(this).val(picker.startDate.format($format) + ' - ' + picker.endDate.format($format)); }); } else { $daterangepicker.on('apply.daterangepicker', function(ev, picker) { $(this).val(picker.startDate.format($format)); }); } $daterangepicker.on('cancel.daterangepicker', function(ev, picker) { $(this).val(''); }); }); }; /* * Bootstrap Colorpicker init, for more examples you can check out http://mjolnic.com/bootstrap-colorpicker/ * * App.initHelper('colorpicker'); * */ var uiHelperColorpicker = function(){ // Get each colorpicker element (with .js-colorpicker class) jQuery('.js-colorpicker').each(function(){ var $colorpicker = jQuery(this); // Get each colorpicker's init data var $colorpickerMode = $colorpicker.data('colorpicker-mode') ? $colorpicker.data('colorpicker-mode') : 'hex'; var $colorpickerinline = $colorpicker.data('colorpicker-inline') ? true : false; // Init colorpicker $colorpicker.colorpicker({ 'format': $colorpickerMode, 'inline': $colorpickerinline }); }); }; /* * Masked Inputs, for more examples you can check out http://digitalbush.com/projects/masked-input-plugin/ * * App.initHelper('masked-inputs'); * */ var uiHelperMaskedInputs = function(){ // Init Masked Inputs // a - Represents an alpha character (A-Z,a-z) // 9 - Represents a numeric character (0-9) // * - Represents an alphanumeric character (A-Z,a-z,0-9) jQuery('.js-masked-date').mask('99/99/9999'); jQuery('.js-masked-date-dash').mask('99-99-9999'); jQuery('.js-masked-phone').mask('(999) 999-9999'); jQuery('.js-masked-phone-ext').mask('(999) 999-9999? x99999'); jQuery('.js-masked-taxid').mask('99-9999999'); jQuery('.js-masked-ssn').mask('999-99-9999'); jQuery('.js-masked-pkey').mask('a*-999-a999'); jQuery('.js-masked-time').mask('99:99'); }; /* * Tags Inputs, for more examples you can check out https://github.com/xoxco/jQuery-Tags-Input * * App.initHelper('tags-inputs'); * */ var uiHelperTagsInputs = function(){ // Init Tags Inputs (with .js-tags-input class) jQuery('.js-tags-input').tagsInput({ height: '36px', width: '100%', defaultText: '添加标签', removeWithBackspace: true, delimiter: [','] }); }; /* * Select2, for more examples you can check out https://github.com/select2/select2 * * App.initHelper('select2'); * */ var uiHelperSelect2 = function(){ // Init Select2 (with .js-select2 class) jQuery('.js-select2').each(function () { var $select2 = jQuery(this); var $width = $select2.data('width') || '100%'; $select2.select2({ width: $width, //设置下拉框的宽度 language: "zh-CN" }); }); }; /* * Highlight.js, for more examples you can check out https://highlightjs.org/usage/ * * App.initHelper('highlightjs'); * */ var uiHelperHighlightjs = function(){ // Init Highlight.js hljs.initHighlightingOnLoad(); }; /* * Bootstrap Notify, for more examples you can check out http://bootstrap-growl.remabledesigns.com/ * * App.initHelper('notify'); * */ var uiHelperNotify = function(){ // Init notifications (with .js-notify class) jQuery('.js-notify').on('click', function(){ var $notify = jQuery(this); var $notifyMsg = $notify.data('notify-message'); var $notifyType = $notify.data('notify-type') ? $notify.data('notify-type') : 'info'; var $notifyFrom = $notify.data('notify-from') ? $notify.data('notify-from') : 'top'; var $notifyAlign = $notify.data('notify-align') ? $notify.data('notify-align') : 'right'; var $notifyIcon = $notify.data('notify-icon') ? $notify.data('notify-icon') : ''; var $notifyUrl = $notify.data('notify-url') ? $notify.data('notify-url') : ''; jQuery.notify({ icon: $notifyIcon, message: $notifyMsg, url: $notifyUrl }, { element: 'body', type: $notifyType, allow_dismiss: true, newest_on_top: true, showProgressbar: false, placement: { from: $notifyFrom, align: $notifyAlign }, offset: 20, spacing: 10, z_index: 1033, delay: 5000, timer: 1000, animate: { enter: 'animated fadeIn', exit: 'animated fadeOutDown' } }); }); }; /* * Draggable items with jQuery, for more examples you can check out https://jqueryui.com/sortable/ * * App.initHelper('draggable-items'); * */ var uiHelperDraggableItems = function(){ // Init draggable items functionality (with .js-draggable-items class) jQuery('.js-draggable-items > .draggable-column').sortable({ connectWith: '.draggable-column', items: '.draggable-item', dropOnEmpty: true, opacity: .75, handle: '.draggable-handler', placeholder: 'draggable-placeholder', tolerance: 'pointer', start: function(e, ui){ ui.placeholder.css({ 'height': ui.item.outerHeight(), 'margin-bottom': ui.item.css('margin-bottom') }); } }); }; /* * Easy Pie Chart, for more examples you can check out http://rendro.github.io/easy-pie-chart/ * * App.initHelper('easy-pie-chart'); * */ var uiHelperEasyPieChart = function(){ // Init Easy Pie Charts (with .js-pie-chart class) jQuery('.js-pie-chart').easyPieChart({ barColor: jQuery(this).data('bar-color') ? jQuery(this).data('bar-color') : '#777777', trackColor: jQuery(this).data('track-color') ? jQuery(this).data('track-color') : '#eeeeee', lineWidth: jQuery(this).data('line-width') ? jQuery(this).data('line-width') : 3, size: jQuery(this).data('size') ? jQuery(this).data('size') : '80', animate: 750, scaleColor: jQuery(this).data('scale-color') ? jQuery(this).data('scale-color') : false }); }; /* * Bootstrap Maxlength, for more examples you can check out https://github.com/mimo84/bootstrap-maxlength * * App.initHelper('maxlength'); * */ var uiHelperMaxlength = function(){ // Init Bootstrap Maxlength (with .js-maxlength class) jQuery('.js-maxlength').each(function(){ var $input = jQuery(this); $input.maxlength({ alwaysShow: $input.data('always-show') ? true : false, threshold: $input.data('threshold') ? $input.data('threshold') : 10, warningClass: $input.data('warning-class') ? $input.data('warning-class') : 'label label-warning', limitReachedClass: $input.data('limit-reached-class') ? $input.data('limit-reached-class') : 'label label-danger', placement: $input.data('placement') ? $input.data('placement') : 'bottom', preText: $input.data('pre-text') ? $input.data('pre-text') : '', separator: $input.data('separator') ? $input.data('separator') : '/', postText: $input.data('post-text') ? $input.data('post-text') : '' }); }); }; /* * Bootstrap Datetimepicker, for more examples you can check out https://github.com/Eonasdan/bootstrap-datetimepicker * * App.initHelper('datetimepicker'); * */ var uiHelperDatetimepicker = function(){ // Init Bootstrap Datetimepicker (with .js-datetimepicker class) jQuery('.js-datetimepicker').each(function(){ var $input = jQuery(this); $input.datetimepicker({ format: $input.data('format') ? $input.data('format') : false, useCurrent: $input.data('use-current') ? $input.data('use-current') : false, locale: moment.locale('' + ($input.data('locale') ? $input.data('locale') : '') +''), showTodayButton: $input.data('show-today-button') ? $input.data('show-today-button') : false, showClear: $input.data('show-clear') ? $input.data('show-clear') : false, showClose: $input.data('show-close') ? $input.data('show-close') : false, sideBySide: $input.data('side-by-side') ? $input.data('side-by-side') : false, inline: $input.data('inline') ? $input.data('inline') : false, icons: { time: 'si si-clock', date: 'si si-calendar', up: 'si si-arrow-up', down: 'si si-arrow-down', previous: 'si si-arrow-left', next: 'si si-arrow-right', today: 'si si-size-actual', clear: 'si si-trash', close: 'si si-close' } }); }); }; /* * Ion Range Slider, for more examples you can check out https://github.com/IonDen/ion.rangeSlider * * App.initHelper('rangeslider'); * */ var uiHelperRangeslider = function(){ // Init Ion Range Slider (with .js-rangeslider class) jQuery('.js-rangeslider').each(function(){ var $input = jQuery(this); $input.ionRangeSlider({ input_values_separator: ';' }); }); }; return { init: function($func) { switch ($func) { case 'uiInit': uiInit(); break; case 'uiLayout': uiLayout(); break; case 'uiNav': uiNav(); break; case 'uiBlocks': uiBlocks(); break; case 'uiForms': uiForms(); break; case 'uiHandleTheme': uiHandleTheme(); break; case 'uiToggleClass': uiToggleClass(); break; case 'uiScrollTo': uiScrollTo(); break; case 'uiYearCopy': uiYearCopy(); break; case 'uiLoader': uiLoader('hide'); break; default: // Init all vital functions uiInit(); uiLayout(); uiNav(); uiBlocks(); uiForms(); uiHandleTheme(); uiToggleClass(); uiScrollTo(); uiYearCopy(); uiLoader('hide'); } }, layout: function($mode) { uiLayoutApi($mode); }, loader: function($mode) { uiLoader($mode); }, blocks: function($block, $mode) { uiBlocksApi($block, $mode); }, initHelper: function($helper) { switch ($helper) { case 'print-page': uiHelperPrint(); break; case 'table-tools': uiHelperTableToolsSections(); uiHelperTableToolsCheckable(); break; case 'appear': uiHelperAppear(); break; case 'appear-countTo': uiHelperAppearCountTo(); break; case 'slimscroll': uiHelperSlimscroll(); break; case 'magnific-popup': uiHelperMagnific(); break; case 'ckeditor': uiHelperCkeditor(); break; case 'summernote': uiHelperSummernote(); break; case 'slick': uiHelperSlick(); break; case 'datepicker': uiHelperDatepicker(); break; case 'daterangepicker': uiHelperDaterangepicker(); break; case 'colorpicker': uiHelperColorpicker(); break; case 'tags-inputs': uiHelperTagsInputs(); break; case 'masked-inputs': uiHelperMaskedInputs(); break; case 'select2': uiHelperSelect2(); break; case 'highlightjs': uiHelperHighlightjs(); break; case 'notify': uiHelperNotify(); break; case 'draggable-items': uiHelperDraggableItems(); break; case 'easy-pie-chart': uiHelperEasyPieChart(); break; case 'maxlength': uiHelperMaxlength(); break; case 'datetimepicker': uiHelperDatetimepicker(); break; case 'rangeslider': uiHelperRangeslider(); break; default: return false; } }, initHelpers: function($helpers) { if ($helpers instanceof Array) { for(var $index in $helpers) { App.initHelper($helpers[$index]); } } else { App.initHelper($helpers); } } }; }(); // Create an alias for App (you can use OneUI in your pages instead of App if you like) var OneUI = App; // Initialize app when page loads jQuery(function(){ if (typeof angular == 'undefined') { App.init(); } });
'use strict'; class KueInput { constructor(config, logger, queue){ config.options = config.options || {}; config.options.kue = config.options.kue || {}; this.concurrency = config.options.kue.concurrency || 1; this.topicName = config.input.slice(config.input.indexOf(':') + 1); this.logger = logger; this.queue = queue; this.queue.process(this.topicName, this.concurrency, this.receiveMessage.bind(this)); } static get dependencies(){ return [ { provider: 'logger' }, { provider: 'kue' } ]; } onMessage(handler){ this.dispatch = handler; } receiveMessage(job, context, done){ if (this.dispatch === null){ throw new Error('No message handler was set. Who am I supposed to provide this message to?'); } this.dispatch(job.data, (err) => { if (err){ this.logger.log(['error'], { message: 'Error occurred dispatching message to handler.', error: err }); return done(err); } this.logger.log(['debug'], { message: 'Dispatched message to handler.' }); done(); }); } } module.exports = KueInput;
import { StyleSheet } from 'react-native'; import Constants from 'expo-constants'; export default StyleSheet.create({ container: { flex: 1, paddingHorizontal: 24, paddingTop: Constants.statusBarHeight + 20, }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }, headerText:{ fontSize: 15, color: '#737380', }, headerTextBold: { fontWeight: 'bold', }, title:{ fontSize: 30, marginBottom:16, marginTop: 48, color: '#13131a', fontWeight: 'bold', }, description:{ fontSize:16, lineHeight: 24, color: '#737380', }, occurrenceList:{ marginTop: 32, }, occurrence:{ padding: 24, borderRadius: 8, backgroundColor: '#fff', marginBottom: 16, }, occurrenceProperty:{ fontSize: 14, color: '#41414d', fontWeight: 'bold', }, occurrenceValue: { marginTop: 8, fontSize: 15, marginBottom: 24, color: '#737380' }, detailsButton: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', }, detailsButtonText:{ color: '#e02041', fontSize: 15, } });
module.exports={title:"Shelly",slug:"shelly",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Shelly</title><path d="M12 0C5.373 0 0 5.373 0 12a12 12 0 0 0 .033.88c1.07-.443 2.495-.679 4.322-.679h5.762c-.167.61-.548 1.087-1.142 1.436-.532.308-1.14.463-1.823.463h-.927c-.89 0-1.663.154-2.32.463-.859.403-1.286 1-1.286 1.789 0 .893.59 1.594 1.774 2.1a7.423 7.423 0 0 0 2.927.581c1.318 0 2.416-.29 3.297-.867 1.024-.664 1.535-1.616 1.535-2.857 0-.854-.325-2.08-.976-3.676-.65-1.597-.975-2.837-.975-3.723 0-2.79 2.305-4.233 6.916-4.324.641-.01 1.337-.005 1.916-.004.593 0 1.144.05 1.66.147A12 12 0 0 0 12 0zm4.758 5.691c-1.206 0-1.809.502-1.809 1.506 0 .514.356 1.665 1.067 3.451.71 1.787 1.064 3.186 1.064 4.198 0 2.166-1.202 3.791-3.607 4.875-1.794.797-3.892 1.197-6.297 1.197-1.268 0-2.442-.114-3.543-.316A12 12 0 0 0 12 24c6.627 0 12-5.373 12-12a12 12 0 0 0-.781-4.256 3.404 3.404 0 0 1-.832.77h-4.371l1.425-2.828a299.94 299.94 0 0 0-2.683.005Z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://shelly.cloud/",hex:"4495D1",guidelines:void 0,license:void 0};
from typing import Iterable, Dict from networkx import DiGraph, NetworkXNoCycle from tree_format import format_tree from mach_nix.data.nixpkgs import NixpkgsIndex from mach_nix.resolver import ResolvedPkg def make_name(pkg: ResolvedPkg, nixpkgs: NixpkgsIndex): pi = pkg.provider_info extras = f"[{' '.join(pkg.extras_selected)}]" if pkg.extras_selected else '' name = f"{pkg.name}{extras} - {pkg.ver} - {pi.provider.name}" if pi.provider.name == 'wheel': name += f" - {'-'.join(pi.wheel_fname.split('-')[-3:])[:-4]}" if pi.provider.name == 'nixpkgs': name += f" (attrs: {' '.join(c.nix_key for c in nixpkgs.get_all_candidates(pkg.name))})" if pi.provider.name.startswith('conda'): if pkg.build: name += f" - {pkg.build}" return name def mark_removed_circular_dep(pkgs: Dict[str, ResolvedPkg], G: DiGraph, node, removed_node): pkgs[node].removed_circular_deps.add(removed_node) for pred in G.predecessors(node): mark_removed_circular_dep(pkgs, G, pred, removed_node) def remove_dependecy(pkgs: Dict[str, ResolvedPkg], G: DiGraph, node_from, node_to): if pkgs[node_from].build_inputs is not None and node_to in pkgs[node_from].build_inputs: raise Exception( f"Fata error: cycle detected in setup requirements\n" f"Cannot fix automatically.\n{[node_from, node_to]}") G.remove_edge(node_from, node_to) pkgs[node_from].prop_build_inputs.remove(node_to) print( f"WARNING: Circular dependency detected and removed:" f" {node_from}:{ pkgs[node_from].ver} -> {node_to}:{ pkgs[node_to].ver}") def remove_circles_and_print(pkgs: Iterable[ResolvedPkg], nixpkgs: NixpkgsIndex): import networkx as nx print("\n### Resolved Dependencies ###\n") indexed_pkgs = {p.name: p for p in sorted(pkgs, key=lambda p: p.name)} roots: Iterable[ResolvedPkg] = sorted([p for p in pkgs if p.is_root], key=lambda p: p.name) def get_build_inputs(pkg: ResolvedPkg): build_inputs, prop_build_inputs = [], [] if pkg.build_inputs is not None: build_inputs = pkg.build_inputs if pkg.prop_build_inputs is not None: prop_build_inputs = pkg.prop_build_inputs return build_inputs, prop_build_inputs edges = set() for p in pkgs: build_inputs, prop_build_inputs = get_build_inputs(p) for child in build_inputs + prop_build_inputs: edges.add((p.name, child)) G = nx.DiGraph(sorted(list(edges))) cycle_count = 0 removed_edges = [] for root in roots: try: while True: cycle = nx.find_cycle(G, root.name) cycle_count += 1 remove_dependecy(indexed_pkgs, G, cycle[-1][0], cycle[-1][1]) removed_edges.append((cycle[-1][0], cycle[-1][1])) except NetworkXNoCycle: continue for node, removed_node in removed_edges: mark_removed_circular_dep(indexed_pkgs, G, node, removed_node) class Limiter: visited = set() def name(self, node_name): if node_name in self.visited: if indexed_pkgs[node_name].build_inputs or indexed_pkgs[node_name].prop_build_inputs: return make_name(indexed_pkgs[node_name], nixpkgs) return f"{make_name(indexed_pkgs[node_name], nixpkgs)} -> ..." return make_name(indexed_pkgs[node_name], nixpkgs) def get_children(self, node_name): if node_name in self.visited: return [] self.visited.add(node_name) build_inputs, prop_build_inputs = get_build_inputs(indexed_pkgs[node_name]) return list(set(build_inputs + prop_build_inputs)) for root in roots: limiter = Limiter() print(format_tree( root.name, format_node=limiter.name, get_children=limiter.get_children) ) print(f"Total number of python modules: {len(indexed_pkgs)}") print(f"Removed circular dependencies: {cycle_count}\n")
var express = require('express'); var router = express.Router(); /* pull all env into a string */ let strValue = ''; Object.keys(process.env).forEach( function (key) { strValue += key + '=' + process.env[key] + '\n'; }); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'env values' , text: strValue }); }); module.exports = router;
import React from 'react'; import {createDevTools} from 'redux-devtools'; // Monitors are separate packages, and you can make a custom one import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; import SliderMonitor from 'redux-slider-monitor'; // createDevTools takes a monitor and produces a DevTools component export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-q" changeMonitorKey="ctrl-m"> <LogMonitor theme="nicinabox"/> <SliderMonitor keyboardEnabled/> </DockMonitor> );
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); const index = require('./index-8fc102d1.js'); const dom = require('./dom-581e28c5.js'); const key = require('./key-822806f8.js'); /** * Date units */ var units; (function (units) { units["day"] = "day"; units["month"] = "month"; units["year"] = "year"; })(units || (units = {})); /** * Parse date formatting data for a given locale */ function getLocaleFormatData(locale) { let data = [ { unit: units.month, num: "11", placeholder: "mm" }, { unit: units.day, num: "22", placeholder: "dd" }, { unit: units.year, num: "3333", placeholder: "yyyy" }, ]; // create a new localized string from a known date let test = new Date(3333, 10, 22).toLocaleDateString(locale); const buddhist = test.indexOf("3876") > -1; // replace arabic numerals and adjust for buddhist era test = replaceArabicNumerals(test).replace("3876", "3333"); const placeholder = data.reduce((str, d) => str.replace(d.num, d.placeholder), test); // given the localized test string, determine the order of day, month, year const order = data .sort((a, b) => (test.indexOf(a.num) < test.indexOf(b.num) ? -1 : 1)) .map((d) => d.unit); const separator = [". ", ".", "-", "/", "/"].find((char) => test.indexOf(char) > -1); return { order, separator, buddhist, placeholder, }; } /** * Parse numeric units for day, month, and year from a localized string * month starts at 0 (can pass to date constructor) */ function parseDateString(str, locale) { const { separator, order, buddhist } = getLocaleFormatData(locale); const values = replaceArabicNumerals(str) .split(separator) .filter((part) => part !== separator) .map((part) => part.replace(".", "")); return { day: parseInt(values[order.indexOf(units.day)]), month: parseInt(values[order.indexOf(units.month)]) - 1, year: parseInt(values[order.indexOf(units.year)]) - (buddhist ? 543 : 0), }; } /** * Convert eastern arbic numerals and remove right-to-left control marks */ function replaceArabicNumerals(str = "") { return str .replace(/[\u0660-\u0669]/g, (c) => (c.charCodeAt(0) - 0x0660)) .replace(/[\u06f0-\u06f9]/g, (c) => (c.charCodeAt(0) - 0x06f0)) .replace(/[^\x00-\x7F]/g, ""); } /** * Assemble an array of month names for a locale */ function getMonths(locale) { const date = new Date(0, 0, 1); return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map((i) => { date.setMonth(i); return new Intl.DateTimeFormat(locale, { month: "long", }).format(date); }); } /** * Get localized year name for given locale */ function getYear(date, locale) { return new Intl.DateTimeFormat(locale, { year: "numeric" }).format(date); } /** * Generate an array of localized week day names in the correct order */ function getLocalizedWeekdays(locale, format = "short") { const startWeek = []; const endWeek = []; const date = new Date(); for (let w = 1; w < 8; w++) { date.setDate(w); let day = new Intl.DateTimeFormat(locale, { weekday: format, }).format(date); date.getDay() === getFirstDayOfWeek(locale) || startWeek.length > 0 ? startWeek.push(day) : endWeek.push(day); } return [...startWeek, ...endWeek]; } /** * Find the week starting day for a given locale */ function getFirstDayOfWeek(locale) { return firstDayOfWeek[locale.slice(0, 2).toUpperCase()] || 0; } /** * Which day of the week is considered the start in each locale * Sunday starting locales have been omitted. * https://github.com/unicode-cldr/cldr-core/blob/master/supplemental/weekData.json */ const firstDayOfWeek = { AD: 1, AE: 6, AF: 6, AI: 1, AL: 1, AM: 1, AN: 1, AR: 1, AT: 1, AX: 1, AZ: 1, BA: 1, BE: 1, BG: 1, BH: 6, BM: 1, BN: 1, BY: 1, CH: 1, CL: 1, CM: 1, CR: 1, CY: 1, CZ: 1, DE: 1, DJ: 6, DK: 1, DZ: 6, EC: 1, EE: 1, EG: 6, ES: 1, FI: 1, FJ: 1, FO: 1, FR: 1, GB: 1, GE: 1, GF: 1, GP: 1, GR: 1, HR: 1, HU: 1, IE: 1, IQ: 6, IR: 6, IS: 1, IT: 1, JO: 6, KG: 1, KW: 6, KZ: 1, LB: 1, LI: 1, LK: 1, LT: 1, LU: 1, LV: 1, LY: 6, MC: 1, MD: 1, ME: 1, MK: 1, MN: 1, MQ: 1, MV: 5, MY: 1, NL: 1, NO: 1, NZ: 1, OM: 6, PL: 1, QA: 6, RE: 1, RO: 1, RS: 1, RU: 1, SD: 6, SE: 1, SI: 1, SK: 1, SM: 1, SY: 6, TJ: 1, TM: 1, TR: 1, UA: 1, UY: 1, UZ: 1, VA: 1, VN: 1, XK: 1, }; /** * Check if date is within a min and max */ function inRange(date, min, max) { const time = date.getTime(); const afterMin = !(min instanceof Date) || time >= min.getTime(); const beforeMax = !(max instanceof Date) || time <= max.getTime(); return afterMin && beforeMax; } /** * Ensures date is within range, * returns min or max if out of bounds */ function dateFromRange(date, min, max) { if (!(date instanceof Date)) { return null; } const time = date.getTime(); const beforeMin = min instanceof Date && time < min.getTime(); const afterMax = max instanceof Date && time > max.getTime(); if (beforeMin) { return min; } if (afterMax) { return max; } return date; } /** * Parse an iso8601 string (YYYY-mm-dd) into a valid date. * TODO: handle time when time of day UI is added */ function dateFromISO(iso8601) { if (!iso8601 || typeof iso8601 !== "string") { return null; } const d = iso8601.split(/[: T-]/).map(parseFloat); const date = new Date(d[0], (d[1] || 1) - 1, d[2] || 1); if (isNaN(date.getTime())) { console.error(`Invalid ISO 8601 date: "${iso8601}"`); return null; } return date; } /** * Return first portion of ISO string (YYYY-mm-dd) */ function dateToISO(date) { if (date instanceof Date) { return date.toISOString().split("T")[0]; } return ""; } /** * Check if two dates are the same day, month, year */ function sameDate(d1, d2) { return (d1 instanceof Date && d2 instanceof Date && d1.getDate() === d2.getDate() && d1.getMonth() === d2.getMonth() && d1.getFullYear() === d2.getFullYear()); } /** * Get a date one month in the past */ function prevMonth(date) { const month = date.getMonth(); const nextDate = new Date(date); nextDate.setMonth(month - 1); // date doesn't exist in new month, use last day if (month === nextDate.getMonth()) { return new Date(date.getFullYear(), month, 0); } return nextDate; } /** * Get a date one month in the future */ function nextMonth(date) { const month = date.getMonth(); const nextDate = new Date(date); nextDate.setMonth(month + 1); // date doesn't exist in new month, use last day if ((month + 2) % 7 === nextDate.getMonth() % 7) { return new Date(date.getFullYear(), month + 2, 0); } return nextDate; } const calciteDateCss = ":host([hidden]){display:none}:host{display:inline-block;vertical-align:top;width:100%;position:relative;overflow:visible}.slot{display:none}:host([scale=s]){max-width:246px}:host([scale=m]){max-width:288px}:host([scale=l]){max-width:400px}.calendar-icon{color:var(--calcite-ui-text-3);position:absolute;top:50%;margin:-8px 0.75rem;pointer-events:none}.calendar-picker-wrapper{position:absolute;top:100%;background-color:var(--calcite-ui-foreground-1);-webkit-box-shadow:0 0 16px 0 rgba(0, 0, 0, 0.16);box-shadow:0 0 16px 0 rgba(0, 0, 0, 0.16);opacity:0;width:100%;line-height:0;visibility:hidden;overflow:visible;-webkit-transform:translate3d(0, -1.5rem, 0);transform:translate3d(0, -1.5rem, 0);-webkit-transition:all 0.15s ease-in-out;transition:all 0.15s ease-in-out;pointer-events:none;z-index:3}:host([active]){background-color:var(--calcite-ui-foreground-1);border-radius:var(--calcite-border-radius);-webkit-box-shadow:0 0 16px 0 rgba(0, 0, 0, 0.16);box-shadow:0 0 16px 0 rgba(0, 0, 0, 0.16)}:host([active]) .calendar-picker-wrapper{opacity:1;-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);visibility:visible;pointer-events:initial}:host([active]) .date-input-wrapper{border:1px solid var(--calcite-ui-foreground-1);border-bottom:1px solid var(--calcite-ui-border-3)}:host([no-calendar-input]) .calendar-picker-wrapper{position:static;-webkit-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0)}"; const CalciteDatePicker = class { constructor(hostRef) { index.registerInstance(this, hostRef); /** Expand or collapse when calendar does not have input */ this.active = false; /** Localized string for "previous month" */ this.prevMonthLabel = "previous month"; /** Localized string for "next month" */ this.nextMonthLabel = "next month"; /** BCP 47 language tag for desired language and country format */ this.locale = "en-US"; /** Show only calendar popup */ this.noCalendarInput = false; /** specify the scale of the date picker */ this.scale = "m"; //-------------------------------------------------------------------------- // // Private State/Props // //-------------------------------------------------------------------------- this.localeData = getLocaleFormatData(this.locale); this.hasShadow = !!document.head.attachShadow; /** * Update component based on input proxy */ this.syncThisToProxyInput = () => { this.min = this.inputProxy.min; this.max = this.inputProxy.max; const min = dateFromISO(this.min); const max = dateFromISO(this.max); const date = dateFromISO(this.inputProxy.value); this.valueAsDate = dateFromRange(date, min, max); this.value = dateToISO(this.valueAsDate); }; /** * Update input proxy */ this.syncProxyInputToThis = () => { if (this.inputProxy) { this.inputProxy.value = this.value || ""; if (this.min) { this.inputProxy.min = this.min; } if (this.max) { this.inputProxy.max = this.max; } } }; this.calciteDateChange = index.createEvent(this, "calciteDateChange", 7); } //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- focusOutHandler() { this.reset(); } /** * Blur doesn't fire properly when there is no shadow dom (ege/IE11) * Check if the focused element is inside the date picker, if not close */ focusInHandler(e) { if (!this.hasShadow && !this.el.contains(e.srcElement)) { this.reset(); } } keyDownHandler(e) { if (key.getKey(e.key) === "Escape") { this.reset(); } } // -------------------------------------------------------------------------- // // Lifecycle // // -------------------------------------------------------------------------- connectedCallback() { this.setupProxyInput(); } disconnectedCallback() { this.observer.disconnect(); } componentWillRender() { this.syncProxyInputToThis(); } render() { const min = dateFromISO(this.min); const max = dateFromISO(this.max); const date = dateFromRange(this.valueAsDate, min, max); const activeDate = this.getActiveDate(date, min, max); const formattedDate = date ? date.toLocaleDateString(this.locale) : ""; const dir = dom.getElementDir(this.el); return (index.h(index.Host, { role: "application", dir: dir }, index.h("div", { class: "slot" }, index.h("slot", null)), !this.noCalendarInput && (index.h("div", { role: "application" }, index.h("calcite-input", { type: "text", value: formattedDate, placeholder: this.localeData.placeholder, icon: "calendar", onCalciteInputFocus: () => (this.active = true), onCalciteInputChange: (e) => this.input(e.detail.value), onCalciteInputBlur: (e) => this.blur(e.detail), scale: this.scale, "number-button-type": "none" }))), index.h("div", { class: "calendar-picker-wrapper" }, index.h("calcite-date-month-header", { activeDate: activeDate, selectedDate: date || new Date(), prevMonthLabel: this.prevMonthLabel, nextMonthLabel: this.nextMonthLabel, locale: this.locale, min: min, max: max, onCalciteActiveDateChange: (e) => { this.activeDate = new Date(e.detail); }, dir: dir, scale: this.scale }), index.h("calcite-date-month", { min: min, max: max, selectedDate: date, activeDate: activeDate, locale: this.locale, onCalciteDateSelect: (e) => { this.setValue(new Date(e.detail)); this.activeDate = new Date(e.detail); this.calciteDateChange.emit(new Date(e.detail)); this.reset(); }, onCalciteActiveDateChange: (e) => { this.activeDate = new Date(e.detail); }, dir: dir, scale: this.scale })))); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * Register slotted date input proxy, or create one if not provided */ setupProxyInput() { // check for a proxy input this.inputProxy = this.el.querySelector("input"); // if the user didn't pass a proxy input create one for them if (!this.inputProxy) { this.inputProxy = document.createElement("input"); try { this.inputProxy.type = "date"; } catch (e) { this.inputProxy.type = "text"; } this.syncProxyInputToThis(); this.el.appendChild(this.inputProxy); } this.syncThisToProxyInput(); { this.observer = new MutationObserver(this.syncThisToProxyInput); this.observer.observe(this.inputProxy, { attributes: true }); } } /** * Set both iso value and date value and update proxy */ setValue(date) { this.valueAsDate = new Date(date); this.value = date.toISOString().split("T")[0]; this.syncProxyInputToThis(); } /** * Reset active date and close */ reset() { if (this.valueAsDate) { this.activeDate = new Date(this.valueAsDate); } if (!this.noCalendarInput) { this.active = false; } } /** * If inputted string is a valid date, update value/active */ input(value) { const date = this.getDateFromInput(value); if (date) { this.setValue(date); this.activeDate = date; this.calciteDateChange.emit(new Date(date)); } } /** * Clean up invalid date from input on blur */ blur(target) { const date = this.getDateFromInput(target.value); if (!date && this.valueAsDate) { target.value = this.valueAsDate.toLocaleDateString(this.locale); } } /** * Get an active date using the value, or current date as default */ getActiveDate(value, min, max) { return (dateFromRange(this.activeDate, min, max) || value || dateFromRange(new Date(), min, max)); } /** * Find a date from input string * return false if date is invalid, or out of range */ getDateFromInput(value) { const { separator } = this.localeData; const { day, month, year } = parseDateString(value, this.locale); const validDay = day > 0; const validMonth = month > -1; const date = new Date(year, month, day); const validDate = !isNaN(date.getTime()); const validLength = value.split(separator).filter((c) => c).length > 2; const validYear = year.toString().length > 3; if (validDay && validMonth && validDate && validLength && validYear && inRange(date, this.min, this.max)) { return date; } return false; } get el() { return index.getElement(this); } }; CalciteDatePicker.style = calciteDateCss; const calciteDateDayCss = ":host([hidden]){display:none}:host-context([theme=dark]){--calcite-ui-blue-1:#00A0FF;--calcite-ui-blue-2:#0087D7;--calcite-ui-blue-3:#47BBFF;--calcite-ui-green-1:#36DA43;--calcite-ui-green-2:#11AD1D;--calcite-ui-green-3:#44ED51;--calcite-ui-yellow-1:#FFC900;--calcite-ui-yellow-2:#F4B000;--calcite-ui-yellow-3:#FFE24D;--calcite-ui-red-1:#FE583E;--calcite-ui-red-2:#F3381B;--calcite-ui-red-3:#FF7465;--calcite-ui-background:#202020;--calcite-ui-foreground-1:#2b2b2b;--calcite-ui-foreground-2:#353535;--calcite-ui-foreground-3:#404040;--calcite-ui-text-1:#ffffff;--calcite-ui-text-2:#bfbfbf;--calcite-ui-text-3:#9f9f9f;--calcite-ui-border-1:#4a4a4a;--calcite-ui-border-2:#404040;--calcite-ui-border-3:#353535;--calcite-ui-border-4:#757575;--calcite-ui-border-5:#9f9f9f}:host{display:-ms-flexbox;display:flex;-ms-flex-pack:center;justify-content:center;outline:none;color:var(--calcite-ui-text-3);cursor:pointer;width:calc(100% / 7);min-width:0}:host([scale=s]){padding:2px 0px}:host([scale=m]){padding:4px 4px}:host([scale=l]){padding:4px 4px}:host .day{display:-ms-flexbox;display:flex;border-radius:100%;font-size:0.875rem;line-height:1.5;-ms-flex-pack:center;justify-content:center;-ms-flex-align:center;align-items:center;line-height:1;color:var(--calcite-ui-text-3);-webkit-transition:all 150ms ease-in-out;transition:all 150ms ease-in-out;background:none;-webkit-box-shadow:0 0 0 2px transparent, 0 0 0 0px transparent;box-shadow:0 0 0 2px transparent, 0 0 0 0px transparent;opacity:0.4}:host([scale=s]) .day{height:27px;width:27px;font-size:12px}:host([scale=m]) .day{height:30px;width:30px;font-size:14px}:host([scale=l]) .day{height:42px;width:42px;font-size:16px}:host([current-month]) .day{opacity:1}:host([disabled]){cursor:default;pointer-events:none;opacity:0.2}:host(:hover) .day,:host([active]) .day{background-color:var(--calcite-ui-foreground-2);color:var(--calcite-ui-text-1)}:host(:focus) .day{-webkit-box-shadow:0 0 0 2px var(--calcite-ui-foreground-1), 0 0 0 4px var(--calcite-ui-blue-1);box-shadow:0 0 0 2px var(--calcite-ui-foreground-1), 0 0 0 4px var(--calcite-ui-blue-1)}:host([selected]) .day{background-color:var(--calcite-ui-blue-1);color:var(--calcite-ui-foreground-1);font-weight:500}"; const CalciteDateDay = class { constructor(hostRef) { index.registerInstance(this, hostRef); /** Date is outside of range and can't be selected */ this.disabled = false; /** Date is in the current month. */ this.currentMonth = false; /** Date is the current selected date of the picker */ this.selected = false; /** Date is actively in focus for keyboard navigation */ this.active = false; this.calciteDaySelect = index.createEvent(this, "calciteDaySelect", 7); } //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- onClick() { !this.disabled && this.calciteDaySelect.emit(); } keyDownHandler(e) { const key$1 = key.getKey(e.key); if (key$1 === " " || key$1 === "Enter") { !this.disabled && this.calciteDaySelect.emit(); } } //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- render() { const intl = new Intl.NumberFormat(this.locale); return (index.h(index.Host, { role: "gridcell", tabindex: this.selected || this.active ? 0 : -1 }, index.h("span", { class: "day" }, intl.format(this.day)))); } get el() { return index.getElement(this); } }; CalciteDateDay.style = calciteDateDayCss; const calciteDateMonthCss = ":host([hidden]){display:none}:host-context([theme=dark]){--calcite-ui-blue-1:#00A0FF;--calcite-ui-blue-2:#0087D7;--calcite-ui-blue-3:#47BBFF;--calcite-ui-green-1:#36DA43;--calcite-ui-green-2:#11AD1D;--calcite-ui-green-3:#44ED51;--calcite-ui-yellow-1:#FFC900;--calcite-ui-yellow-2:#F4B000;--calcite-ui-yellow-3:#FFE24D;--calcite-ui-red-1:#FE583E;--calcite-ui-red-2:#F3381B;--calcite-ui-red-3:#FF7465;--calcite-ui-background:#202020;--calcite-ui-foreground-1:#2b2b2b;--calcite-ui-foreground-2:#353535;--calcite-ui-foreground-3:#404040;--calcite-ui-text-1:#ffffff;--calcite-ui-text-2:#bfbfbf;--calcite-ui-text-3:#9f9f9f;--calcite-ui-border-1:#4a4a4a;--calcite-ui-border-2:#404040;--calcite-ui-border-3:#353535;--calcite-ui-border-4:#757575;--calcite-ui-border-5:#9f9f9f}.calender{padding-bottom:4px}.week-headers{display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;border-top:1px solid var(--calcite-ui-border-3);padding:0 4px}.week-header{color:var(--calcite-ui-text-3);font-weight:600;width:calc(100% / 7);text-align:center}:host([scale=s]) .week-header{font-size:12px;padding:16px 0 16px 0}:host([scale=m]) .week-header{font-size:12px;padding:24px 0 20px 0}:host([scale=l]) .week-header{font-size:14px;padding:32px 0 24px 0}.week-days{outline:none;display:-ms-flexbox;display:flex;-ms-flex-direction:row;flex-direction:row;padding:0 4px}"; const CalciteDateMonth = class { constructor(hostRef) { index.registerInstance(this, hostRef); /** Date currently active.*/ this.activeDate = new Date(); /** User's language and region as BCP 47 formatted string. */ this.locale = "en-US"; this.calciteDateSelect = index.createEvent(this, "calciteDateSelect", 7); this.calciteActiveDateChange = index.createEvent(this, "calciteActiveDateChange", 7); } //-------------------------------------------------------------------------- // // Event Listeners // //-------------------------------------------------------------------------- keyDownHandler(e) { const isRTL = this.el.dir === "rtl"; switch (key.getKey(e.key)) { case "ArrowUp": e.preventDefault(); this.addDays(-7); break; case "ArrowRight": e.preventDefault(); this.addDays(isRTL ? -1 : 1); break; case "ArrowDown": e.preventDefault(); this.addDays(7); break; case "ArrowLeft": e.preventDefault(); this.addDays(isRTL ? 1 : -1); break; case "PageUp": e.preventDefault(); this.addMonths(-1); break; case "PageDown": e.preventDefault(); this.addMonths(1); break; case "Home": e.preventDefault(); this.activeDate.setDate(1); this.addDays(); break; case "End": e.preventDefault(); this.activeDate.setDate(new Date(this.activeDate.getFullYear(), this.activeDate.getMonth() + 1, 0).getDate()); this.addDays(); break; case "Enter": case " ": e.preventDefault(); this.calciteDateSelect.emit(this.activeDate); break; case "Tab": this.activeFocus = false; } } /** * Once user is not interacting via keyboard, * disable auto focusing of active date */ disableActiveFocus() { this.activeFocus = false; } //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- render() { const month = this.activeDate.getMonth(); const year = this.activeDate.getFullYear(); const startOfWeek = getFirstDayOfWeek(this.locale); const weekDays = getLocalizedWeekdays(this.locale, this.scale === "s" ? "narrow" : "short"); const curMonDays = this.getCurrentMonthDays(month, year); const prevMonDays = this.getPrevMonthdays(month, year, startOfWeek); const nextMonDays = this.getNextMonthDays(month, year, startOfWeek); const days = [ ...prevMonDays.map((day) => { const date = new Date(year, month - 1, day); return (index.h("calcite-date-day", { scale: this.scale, day: day, disabled: !inRange(date, this.min, this.max), selected: sameDate(date, this.selectedDate), onCalciteDaySelect: () => this.calciteDateSelect.emit(date), locale: this.locale })); }), ...curMonDays.map((day) => { const date = new Date(year, month, day); const active = sameDate(date, this.activeDate); return (index.h("calcite-date-day", { scale: this.scale, day: day, disabled: !inRange(date, this.min, this.max), selected: sameDate(date, this.selectedDate), active: active, onCalciteDaySelect: () => this.calciteDateSelect.emit(date), locale: this.locale, ref: (el) => { // when moving via keyboard, focus must be updated on active date if (active && this.activeFocus) { el === null || el === void 0 ? void 0 : el.focus(); } }, "current-month": true })); }), ...nextMonDays.map((day) => { const date = new Date(year, month + 1, day); return (index.h("calcite-date-day", { scale: this.scale, day: day, disabled: !inRange(date, this.min, this.max), selected: sameDate(date, this.selectedDate), onCalciteDaySelect: () => this.calciteDateSelect.emit(date), locale: this.locale })); }), ]; const weeks = []; for (let i = 0; i < days.length; i += 7) { weeks.push(days.slice(i, i + 7)); } return (index.h(index.Host, null, index.h("div", { class: "calender", role: "grid" }, index.h("div", { class: "week-headers", role: "row" }, weekDays.map((weekday) => (index.h("span", { class: "week-header", role: "columnheader" }, weekday)))), weeks.map((days) => (index.h("div", { class: "week-days", role: "row" }, days)))))); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * Add n months to the current month */ addMonths(step) { const nextDate = new Date(this.activeDate); nextDate.setMonth(this.activeDate.getMonth() + step); this.calciteActiveDateChange.emit(dateFromRange(nextDate, this.min, this.max)); this.activeFocus = true; } /** * Add n days to the current date */ addDays(step = 0) { const nextDate = new Date(this.activeDate); nextDate.setDate(this.activeDate.getDate() + step); this.calciteActiveDateChange.emit(dateFromRange(nextDate, this.min, this.max)); this.activeFocus = true; } /** * Get dates for last days of the previous month */ getPrevMonthdays(month, year, startOfWeek) { const lastDate = new Date(year, month, 0); const date = lastDate.getDate(); const day = lastDate.getDay(); const days = []; if (day - 6 === startOfWeek) { return days; } for (let i = lastDate.getDay(); i >= startOfWeek; i--) { days.push(date - i); } return days; } /** * Get dates for the current month */ getCurrentMonthDays(month, year) { const num = new Date(year, month + 1, 0).getDate(); const days = []; for (let i = 0; i < num; i++) { days.push(i + 1); } return days; } /** * Get dates for first days of the next month */ getNextMonthDays(month, year, startOfWeek) { const endDay = new Date(year, month + 1, 0).getDay(); const days = []; if (endDay === (startOfWeek + 6) % 7) { return days; } for (let i = 0; i < (6 - (endDay - startOfWeek)) % 7; i++) { days.push(i + 1); } return days; } get el() { return index.getElement(this); } }; CalciteDateMonth.style = calciteDateMonthCss; const calciteDateMonthHeaderCss = ":host([hidden]){display:none}:host-context([theme=dark]){--calcite-ui-blue-1:#00A0FF;--calcite-ui-blue-2:#0087D7;--calcite-ui-blue-3:#47BBFF;--calcite-ui-green-1:#36DA43;--calcite-ui-green-2:#11AD1D;--calcite-ui-green-3:#44ED51;--calcite-ui-yellow-1:#FFC900;--calcite-ui-yellow-2:#F4B000;--calcite-ui-yellow-3:#FFE24D;--calcite-ui-red-1:#FE583E;--calcite-ui-red-2:#F3381B;--calcite-ui-red-3:#FF7465;--calcite-ui-background:#202020;--calcite-ui-foreground-1:#2b2b2b;--calcite-ui-foreground-2:#353535;--calcite-ui-foreground-3:#404040;--calcite-ui-text-1:#ffffff;--calcite-ui-text-2:#bfbfbf;--calcite-ui-text-3:#9f9f9f;--calcite-ui-border-1:#4a4a4a;--calcite-ui-border-2:#404040;--calcite-ui-border-3:#353535;--calcite-ui-border-4:#757575;--calcite-ui-border-5:#9f9f9f}.header{display:-ms-flexbox;display:flex;-ms-flex-pack:justify;justify-content:space-between}:host([scale=s]) .text{font-size:14px;height:16px;padding:8px 0}:host([scale=m]) .text{font-size:16px;height:16px;padding:16px 0}:host([scale=l]) .text{font-size:18px;padding:16px 0}.chevron{color:var(--calcite-ui-text-2);-ms-flex-positive:0 0 auto;flex-grow:0 0 auto;width:calc(100% / 7);-webkit-box-sizing:content-box;box-sizing:content-box;outline:none;padding:0 4px;margin:0;border:none;background-color:var(--calcite-ui-foreground-1);cursor:pointer;-webkit-transition:all 0.15s ease-in-out;transition:all 0.15s ease-in-out;outline-offset:0;outline-color:transparent;-webkit-transition:outline-offset 100ms ease-in-out, outline-color 100ms ease-in-out;transition:outline-offset 100ms ease-in-out, outline-color 100ms ease-in-out}.chevron:focus{outline:2px solid var(--calcite-ui-blue-1);outline-offset:-2px}.chevron:hover,.chevron:focus{fill:var(--calcite-ui-text-1);background-color:var(--calcite-ui-foreground-2)}.chevron:active{background-color:var(--calcite-ui-foreground-3)}.text{-ms-flex:1 1 auto;flex:1 1 auto;display:-ms-inline-flexbox;display:inline-flex;-ms-flex-pack:center;justify-content:center;line-height:1.25}.month,.year{color:var(--calcite-ui-text-1);background:var(--calcite-ui-foreground-1);font-size:inherit;font-weight:500}.year{font-family:inherit;text-align:center;border:none;width:3em;padding:0;margin:0 8px;outline-offset:0;outline-color:transparent;-webkit-transition:outline-offset 100ms ease-in-out, outline-color 100ms ease-in-out;transition:outline-offset 100ms ease-in-out, outline-color 100ms ease-in-out}.year:hover{-webkit-transition:outline-color 100ms ease-in-out;transition:outline-color 100ms ease-in-out;outline:2px solid var(--calcite-ui-border-2);outline-offset:2px}.year:focus{outline:2px solid var(--calcite-ui-blue-1);outline-offset:2px}"; const CalciteDateMonthHeader = class { constructor(hostRef) { index.registerInstance(this, hostRef); this.calciteActiveDateChange = index.createEvent(this, "calciteActiveDateChange", 7); } //-------------------------------------------------------------------------- // // Lifecycle // //-------------------------------------------------------------------------- render() { const activeMonth = this.activeDate.getMonth(); const localizedMonth = getMonths(this.locale)[activeMonth]; const localizedYear = getYear(this.activeDate, this.locale); const iconScale = this.scale === "l" ? "m" : "s"; const dir = dom.getElementDir(this.el); return (index.h(index.Host, { dir: dir }, index.h("div", { class: "header", "aria-hidden": "true" }, index.h("button", { class: "chevron", "aria-label": this.prevMonthLabel, onClick: () => this.selectPrevMonth() }, index.h("calcite-icon", { icon: "chevron-left", scale: iconScale, mirrored: true, dir: dir })), index.h("div", { class: "text" }, index.h("span", { class: "month", role: "heading" }, localizedMonth), index.h("input", { class: "year", type: "text", inputmode: "numeric", maxlength: "4", minlength: "4", pattern: "\\d*", value: `${localizedYear.slice(-4)}`, onKeyDown: (event) => this.onYearKey(event), onChange: (event) => this.setYear(event.target.value), ref: (el) => (this.yearInput = el) })), index.h("button", { class: "chevron", "aria-label": this.nextMonthLabel, onClick: () => this.selectNextMonth() }, index.h("calcite-icon", { icon: "chevron-right", scale: iconScale, mirrored: true, dir: dir }))))); } //-------------------------------------------------------------------------- // // Private Methods // //-------------------------------------------------------------------------- /** * Set active date to previous month (or min if out of range) */ selectPrevMonth() { const nextDate = prevMonth(this.activeDate); this.calciteActiveDateChange.emit(dateFromRange(nextDate, this.min, this.max)); } /** * Set active date to next month (or max if out of range) */ selectNextMonth() { const nextDate = nextMonth(this.activeDate); this.calciteActiveDateChange.emit(dateFromRange(nextDate, this.min, this.max)); } /** * Increment year on UP/DOWN keys */ onYearKey(e) { const year = e.target.value; switch (key.getKey(e.key)) { case "ArrowDown": e.preventDefault(); this.setYear(year, -1); break; case "ArrowUp": e.preventDefault(); this.setYear(year, 1); break; } } /** * Parse localized year string from input, * set to active if in range */ setYear(localizedYear, increment = 0) { const { min, max, activeDate, locale, yearInput } = this; const parsedYear = parseInt(replaceArabicNumerals(localizedYear)); const length = parsedYear.toString().length; const offset = getLocaleFormatData(locale).buddhist ? 543 : 0; const year = isNaN(parsedYear) ? false : parsedYear - offset + increment; const inRange = year && (!min || min.getFullYear() <= year) && (!max || max.getFullYear() >= year); // if you've supplied a year and it's in range, update active date if (year && inRange && length === localizedYear.length && length > 3) { const nextDate = new Date(activeDate); nextDate.setFullYear(year); const inRangeDate = dateFromRange(nextDate, min, max); this.calciteActiveDateChange.emit(inRangeDate); yearInput.value = getYear(inRangeDate, locale).slice(-4); } else { // leave the current active date and clean up garbage input yearInput.value = getYear(activeDate, locale).slice(-4); } } get el() { return index.getElement(this); } }; CalciteDateMonthHeader.style = calciteDateMonthHeaderCss; exports.calcite_date = CalciteDatePicker; exports.calcite_date_day = CalciteDateDay; exports.calcite_date_month = CalciteDateMonth; exports.calcite_date_month_header = CalciteDateMonthHeader;
module.exports={D:{"11":0.025344,"20":0.0396,"21":0.009504,"22":0.003168,"23":0.001584,"25":0.001584,"26":0.003168,"28":0.001584,"29":0.004752,"31":0.006336,"33":0.009504,"36":0.001584,"37":0.003168,"38":0.003168,"40":0.004752,"42":0.00792,"43":0.066528,"44":0.001584,"45":0.004752,"46":0.004752,"47":0.001584,"48":0.003168,"49":0.121968,"50":0.00792,"51":0.00792,"52":0.006336,"53":0.006336,"54":0.003168,"55":0.069696,"56":0.012672,"57":0.07128,"58":0.076032,"59":0.012672,"60":0.123552,"61":0.02376,"62":0.044352,"63":0.201168,"64":3.657456,"65":2.181168,"66":0.020592,"67":0.00792,_:"4 5 6 7 8 9 10 12 13 14 15 16 17 18 19 24 27 30 32 34 35 39 41 68"},C:{"4":0.01584,"5":0.011088,"6":0.00792,"7":0.003168,"8":0.004752,"9":0.004752,"10":0.004752,"11":0.00792,"12":0.01584,"13":0.014256,"14":0.006336,"15":0.003168,"16":0.009504,"17":0.00792,"18":0.01584,"19":0.009504,"20":0.00792,"21":0.012672,"22":0.003168,"23":0.020592,"24":0.004752,"25":0.006336,"26":0.006336,"27":0.004752,"28":0.004752,"29":0.011088,"30":0.022176,"31":0.009504,"32":0.012672,"33":0.01584,"34":0.02376,"35":0.026928,"36":0.038016,"37":0.011088,"38":0.014256,"39":0.01584,"40":0.01584,"41":0.017424,"42":0.012672,"43":0.096624,"44":0.052272,"45":0.02376,"46":0.01584,"47":0.11088,"48":0.061776,"49":0.041184,"50":0.017424,"51":0.014256,"52":0.117216,"53":0.009504,"54":0.022176,"55":0.01584,"56":0.061776,"57":0.09504,"58":1.460448,"59":1.138896,"60":0.120384,_:"2 3 61","3.5":0.001584,"3.6":0.004752},F:{"12":0.009504,"15":0.003168,"17":0.001584,"18":0.001584,"34":0.001584,"35":0.001584,"36":0.009504,"40":0.00792,"41":0.003168,"42":0.017424,"43":0.014256,"45":0.025344,"46":0.006336,"47":0.004752,"48":0.012672,"49":0.045936,"50":0.091872,"51":0.814176,"52":0.034848,_:"9 11 16 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 37 38 39 44 9.5-9.6 10.5 11.1 11.5","10.0-10.1":0,"10.6":0.00792,"11.6":0.006336,"12.1":0.019008},E:{"4":0.003168,"5":0.001584,"6":0.003168,"7":0.003168,"8":0.020592,"9":0.022176,"10":0.045936,"11":0.323136,_:"0 3.1 3.2 6.1","5.1":0.006336,"7.1":0.00792,"9.1":0.044352,"10.1":0.09504,"11.1":0.014256},G:{"8":0.00198082978085,"3.2":0.000141487841489,"4.0-4.1":0,"4.2-4.3":0.000141487841489,"5.0-5.1":0.0025467811468,"6.0-6.1":0.00198082978085,"7.0-7.1":0.00693290423296,"8.1-8.4":0.0104701002702,"9.0-9.2":0.00792331912339,"9.3":0.0567366244371,"10.0-10.2":0.0565951365956,"10.3":0.13115922906,"11.0-11.2":1.13727926989,_:"11.3"},I:{"3":0,"4":0,_:"62","2.1":0,"2.2":0,"2.3":0,"4.1":0.207662757282,"4.2-4.3":0.632017087379,"4.4":1.78319106796,"4.4.3-4.4.4":1.09700108738},A:{"6":0.00159315606936,"8":0.121079861272,"9":0.0143384046243,"10":0.0366425895954,"11":0.377577988439,_:"7 5.5"},K:{_:"0 10 11 12 11.1 11.5 12.1"},B:{"12":0.06336,"13":0.050688,"14":0.061776,"15":0.053856,"16":0.215424,_:"17"},P:{"4":1.02527703093,"5":0.314688989691,"6.2":0.629377979381},J:{"7":0.008416,"10":0.033664},N:{"10":0.187294254545,"11":0.418657745455},M:{"0":0.29456},Q:{_:"1.2"},O:{"0":18.80976},H:{"0":30.2853230515},L:{"0":25.059392},R:{_:"0"}};
define(["./Cartesian2-697a9954","./Check-f3fec9b0","./when-54335d57","./EllipseGeometry-83e0cc91","./VertexFormat-acf45ede","./Math-737a2579","./GeometryOffsetAttribute-6e5d8e16","./Transforms-251ff661","./RuntimeError-88a32665","./ComponentDatatype-417761a2","./WebGLConstants-4739ce15","./EllipseGeometryLibrary-0f7e8266","./GeometryAttribute-7ca1c9e4","./GeometryAttributes-caa08d6c","./GeometryInstance-1bb3fb4a","./GeometryPipeline-1dd54e44","./AttributeCompression-ab5c33b7","./EncodedCartesian3-0ae9fe5e","./IndexDatatype-c134ea39","./IntersectionTests-3e34a0aa","./Plane-d4cb7bb3"],function(r,e,o,a,n,t,i,s,l,m,d,c,u,p,y,_,h,G,x,f,g){"use strict";function E(e){var t=(e=o.defaultValue(e,o.defaultValue.EMPTY_OBJECT)).radius,e={center:e.center,semiMajorAxis:t,semiMinorAxis:t,ellipsoid:e.ellipsoid,height:e.height,extrudedHeight:e.extrudedHeight,granularity:e.granularity,vertexFormat:e.vertexFormat,stRotation:e.stRotation,shadowVolume:e.shadowVolume};this._ellipseGeometry=new a.EllipseGeometry(e),this._workerName="createCircleGeometry"}E.packedLength=a.EllipseGeometry.packedLength,E.pack=function(e,t,i){return a.EllipseGeometry.pack(e._ellipseGeometry,t,i)};var v=new a.EllipseGeometry({center:new r.Cartesian3,semiMajorAxis:1,semiMinorAxis:1}),w={center:new r.Cartesian3,radius:void 0,ellipsoid:r.Ellipsoid.clone(r.Ellipsoid.UNIT_SPHERE),height:void 0,extrudedHeight:void 0,granularity:void 0,vertexFormat:new n.VertexFormat,stRotation:void 0,semiMajorAxis:void 0,semiMinorAxis:void 0,shadowVolume:void 0};return E.unpack=function(e,t,i){t=a.EllipseGeometry.unpack(e,t,v);return w.center=r.Cartesian3.clone(t._center,w.center),w.ellipsoid=r.Ellipsoid.clone(t._ellipsoid,w.ellipsoid),w.height=t._height,w.extrudedHeight=t._extrudedHeight,w.granularity=t._granularity,w.vertexFormat=n.VertexFormat.clone(t._vertexFormat,w.vertexFormat),w.stRotation=t._stRotation,w.shadowVolume=t._shadowVolume,o.defined(i)?(w.semiMajorAxis=t._semiMajorAxis,w.semiMinorAxis=t._semiMinorAxis,i._ellipseGeometry=new a.EllipseGeometry(w),i):(w.radius=t._semiMajorAxis,new E(w))},E.createGeometry=function(e){return a.EllipseGeometry.createGeometry(e._ellipseGeometry)},E.createShadowVolume=function(e,t,i){var r=e._ellipseGeometry._granularity,o=e._ellipseGeometry._ellipsoid,t=t(r,o),i=i(r,o);return new E({center:e._ellipseGeometry._center,radius:e._ellipseGeometry._semiMajorAxis,ellipsoid:o,stRotation:e._ellipseGeometry._stRotation,granularity:r,extrudedHeight:t,height:i,vertexFormat:n.VertexFormat.POSITION_ONLY,shadowVolume:!0})},Object.defineProperties(E.prototype,{rectangle:{get:function(){return this._ellipseGeometry.rectangle}},textureCoordinateRotationPoints:{get:function(){return this._ellipseGeometry.textureCoordinateRotationPoints}}}),function(e,t){return(e=o.defined(t)?E.unpack(e,t):e)._ellipseGeometry._center=r.Cartesian3.clone(e._ellipseGeometry._center),e._ellipseGeometry._ellipsoid=r.Ellipsoid.clone(e._ellipseGeometry._ellipsoid),E.createGeometry(e)}});
# -*- coding: utf-8 -*- # # Copyright 2021 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. """Utilities for Policy Analyzer API.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.util import apis _API_NAME = 'policyanalyzer' _API_VERSION_V1BETA1 = 'v1beta1' _API_VERSION_V1 = 'v1' def GetClientAndMessages(): # All release tracks map to v1 return apis.GetClientInstance(_API_NAME, _API_VERSION_V1), apis.GetMessagesModule( _API_NAME, _API_VERSION_V1)
""" Quick embed parser """ import discord, re from mantabot.util import emoji COLORRE = re.compile(r'rgb\(\s*([0-9]{1,3})\s*,' r'\s*([0-9]{1,3})\s*,' r'\s*([0-9]{1,3})\s*\)', flags=re.IGNORECASE) class Parser(object): """ Simple parser for dict-based embed descriptions """ title_limit = 256 description_limit = 2048 field_limit = 25 field_name_limit = 256 field_value_limit = 1024 footer_limit = 2048 author_name_limit = 256 def __init__(self, guild=None): self.guild = guild self.emoji_dict = None if guild is None else emoji.build_emoji_dict(guild) def from_dict(self, data, template=None): embed = template or discord.Embed() embed.type = 'rich' for key, value in data.items(): handler = getattr(self, 'parse_%s' % key, None) if handler: handler(embed, key, value) return embed def handle_emojis(self, text): if text is discord.Embed.Empty: return text return emoji.parse_emojis(text, custom=self.emoji_dict) parse_type = setattr parse_url = setattr parse_timestamp = setattr def parse_title(self, embed, key, value): if len(value) > self.title_limit: raise ValueError('title length cannot exceed %s' % self.title_limit) embed.title = value def parse_description(self, embed, key, value): value = self.handle_emojis(value) if len(value) > self.description_limit: raise ValueError('description length cannot exceed %s' % self.description_limit) embed.description = value def parse_color(self, embed, key, value): if isinstance(value, int): embed.colour = value return rgb = COLORRE.fullmatch(value) if rgb: red, green, blue = int(rgb.group(1)), int(rgb.group(2)), int(rgb.group(3)) if red > 255 or green > 255 or blue > 255: raise ValueError('color channel value must be in range [0, 255]') embed.colour = discord.Colour.from_rgb(red, green, blue) return raise ValueError('unrecognized color format') def parse_image(self, embed, key, value): embed.set_image(url=value) def parse_thumbnail(self, embed, key, value): embed.set_thumbnail(url=value) def parse_author(self, embed, key, value): if value: name = self.handle_emojis(value.get('name', discord.Embed.Empty)) if name is not discord.Embed.Empty and len(name) > self.author_name_limit: raise ValueError('author name length cannot exceed %s' % self.author_name_limit) embed.set_author( name=name, url=value.get('url', discord.Embed.Empty), icon_url=value.get('icon_url', discord.Embed.Empty), ) else: embed.set_author() def parse_footer(self, embed, key, value): if value: text = self.handle_emojis(value.get('text', discord.Embed.Empty)) if text is not discord.Embed.Empty and len(text) > self.footer_limit: raise ValueError('footer length cannot exceed %s' % self.footer_limit) embed.set_footer( text=text, icon_url=value.get('icon_url', discord.Embed.Empty), ) else: embed.set_footer() def parse_fields(self, embed, key, value): if len(value) > self.field_limit: raise ValueError('field number cannot exceed %s' % self.field_limit) for field in value: name = self.handle_emojis(field.get('name', discord.Embed.Empty)) value = self.handle_emojis(field.get('value', discord.Embed.Empty)) if name is not discord.Embed.Empty and len(name) > self.field_name_limit: raise ValueError('field name length cannot exceed %s' % self.field_name_limit) if value is not discord.Embed.Empty and len(value) > self.field_value_limit: raise ValueError('field value length cannot exceed %s' % self.field_value_limit) embed.add_field(name=name, value=value, inline=field.get('inline', True))
/* * TokenInfo.js - View * * Handle displaying information about the token (name, supply, currency, etc). */ Ext.define('FW.view.TokenInfo', { extend: 'Ext.Container', xtype: 'fw-tokeninfo', requires:[ 'Ext.Img', 'FW.view.phone.TokenInfo', 'FW.view.tablet.TokenInfo' ], config: { layout: 'card', items:[] }, // Initialize the component initialize: function(){ var me = this; // Setup some aliases me.main = FW.app.getController('Main'); // Add view based on device type me.add({ xclass:'FW.view.' + me.main.deviceType + '.TokenInfo' }); // Now that we have added the correct view, setup some aliases to various components me.tb = me.down('fw-toptoolbar'); me.image = me.down('[itemId=image]'); me.currency = me.down('[itemId=currency]'); me.balance = me.down('[itemId=balance]'); me.description = me.down('[itemId=description]'); me.supply = me.down('[itemId=supply]'); me.price = me.down('[itemId=price]'); me.btc = me.down('[itemId=btc]'); me.divisible = me.down('[itemId=divisible]'); me.locked = me.down('[itemId=locked]'); me.website = me.down('[itemId=website]'); me.issuer = me.down('[itemId=issuer]'); me.owner = me.down('[itemId=owner]'); me.actionBtns = me.down('[itemId=actionButtons]'); me.sendBtn = me.down('[itemId=send]'); me.receiveBtn = me.down('[itemId=receive]'); // Tablet specific fields me.placeholder = me.down('[itemId=placeholder]'); me.information = me.down('[itemId=information]'); // Setup listeners on the buttons to handle user tapping button me.sendBtn.on('tap',function(btn){ me.main.showTool('send', { reset: true, currency: me.getData().currency }); }); // Handle displaying current address and currency in QRCode me.receiveBtn.on('tap',function(btn){ me.main.showTool('receive', { reset: true, asset: me.getData().currency }); }); me.callParent(); }, // Handle updating the view updateView: function(cfg){ var me = this, data = cfg.data; // Store current data so we can easily reference me.setData(data); // Back button if(cfg.back){ me.tb.backBtn.show(); if(typeof cfg.back === 'function') me.tb.onBack = cfg.back; } else { me.tb.backBtn.hide(); } // Handle hiding placeholder and showing currency information if(me.placeholder){ me.placeholder.hide(); me.information.show(); } // Update currency name and image me.image.setSrc('https://counterpartychain.io/content/images/icons/' + data.currency.toLowerCase() + '.png'); me.updateData(data); // Get the basic currency information me.getCurrencyInfo(data); }, // Handle updating view data updateData: function(data){ var me = this, fmt = '0,0'; if(data.divisible) fmt += '.00000000'; // Define balance var bal = numeral(data.amount).format(fmt), btc = 'NA'; // Handle determining the USD price if(typeof FW.TRACKED_PRICES[data.currency] != 'undefined'){ var o = FW.TRACKED_PRICES[data.currency]; bal += ' ($' + numeral(o.USD * data.amount).format('0,0.00') + ')'; data.price = numeral(o.USD).format('0,0.00'); data.btc = numeral(o.BTC).format('0,0.00000000'); } me.description.setValue(data.description); me.currency.setValue((data.currency=='BTC') ? 'BTC (Bitcoin)' : data.currency); me.supply.setValue(numeral(data.supply).format(fmt)); me.divisible.setValue((data.divisible) ? 'True' : 'False'); me.locked.setValue((data.locked) ? 'True' : 'False'); me.website.setValue((data.website) ? data.website : ''); me.issuer.setValue((data.issuer) ? data.issuer : 'NA'); me.owner.setValue((data.owner) ? data.owner : 'NA'); me.balance.setValue(bal); me.price.setValue((data.price) ? '$' + data.price : 'NA'); me.btc.setValue((data.btc) ? data.btc : 'NA'); }, // Handle requesting basic asset information getCurrencyInfo: function(data){ var me = this; // Stash raw currency value, so we can easily me.currencyValue = data.currency; if(data.currency=='BTC'){ me.updateData({ currency: 'BTC', amount: data.amount, supply: '21000000.00000000', website: 'http://bitcoin.org', divisible: true, locked: true, description: 'Bitcoin is digital money' }); } else { var host = (FW.WALLET_NETWORK==2) ? 'testnet.counterpartychain.io' : 'counterpartychain.io'; // Set loading mask on panel to indicate we are loading me.setMasked({ xtype: 'loadmask', cls: 'fw-panel', message: 'Loading Data', showAnimation: 'fadeIn', indicator: true }); // Make request for data on currency me.main.ajaxRequest({ url: 'https://' + host + '/api/asset/' + data.currency, // Success function called when we receive a success response success: function(o){ if(o.success){ var desc = o.description; if(me.main.isUrl(desc)) o.website = desc; if(data.currency=='XCP'){ o.website = 'https://counterparty.io'; o.description = 'Counterparty extends Bitcoin in new and powerful ways.'; } me.updateData(Ext.apply(o,{ amount: data.amount, currency: data.currency })); // Detect any .json urls and request the extra data if(/.json$/.test(desc)) me.getEnhancedCurrencyInfo(desc); } }, // Callback function called on any response callback: function(){ me.setMasked(false); } }); } }, // Handle requesting enhanced currency information getEnhancedCurrencyInfo: function(url){ var me = this; if(!me.main.isUrl(url)) url = 'http://' + url; // Switch http to https if app loaded via https (https->http XHR requests will fail) if(document.location.protocol=='https:') url = url.replace('http://','https://'); me.main.ajaxRequest({ url: url, // Success function called when we receive a success response success: function(o){ // console.log('enhanced info o=',o); if(o.website) me.website.setValue(o.website); // if(o.image) // me.image.setSrc(o.image); } }); } });
from ..base import * import networkx as nx import angr import itertools class AngrCallstackKeyClusterer(Clusterer): def __init__(self, visible=True): super(AngrCallstackKeyClusterer, self).__init__() self.visible = visible def cluster(self, graph): for node in graph.nodes: key = node.obj.callstack_key cluster = graph.get_cluster(key) if not cluster: cluster = graph.create_cluster(key, visible=self.visible) cluster.add_node(node) # merge by jump edges jgraph = nx.DiGraph() for e in graph.edges: if e.src.cluster and e.dst.cluster and e.src.cluster != e.dst.cluster: if e.meta['jumpkind'] == 'Ijk_Boring': jgraph.add_edge(e.src.cluster.key, e.dst.cluster.key) for n in jgraph.nodes(): in_edges = jgraph.in_edges(n) if len(in_edges) == 1: s,t = in_edges[0] scluster = graph.get_cluster(s) for n in graph.nodes: if n.cluster.key == t: n.cluster.remove_node(n) scluster.add_node(n) # build cluster hierarchy cgraph = nx.DiGraph() for e in graph.edges: if e.src.cluster and e.dst.cluster and e.src.cluster != e.dst.cluster: if e.meta['jumpkind'] == 'Ijk_Call': cgraph.add_edge(e.src.cluster.key, e.dst.cluster.key) for n in cgraph.nodes(): in_edges = cgraph.in_edges(n) if len(in_edges) == 1: s,t = in_edges[0] scluster = graph.get_cluster(s) tcluster = graph.get_cluster(t) tcluster.parent = scluster class AngrStructuredClusterer(Clusterer): def __init__(self, struct, remove_unclustered=True): super(AngrStructuredClusterer, self).__init__() self.struct = struct self.block_to_cluster = {} self.seq = itertools.count() self.remove_unclustered = remove_unclustered def build(self, obj, graph, parent_cluster): if type(obj).__name__ == 'GraphRegion': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=repr(obj)) for n in obj.graph.nodes(): self.build(n, graph, cluster) elif type(obj).__name__ == 'MultiNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=repr(obj)) for n in obj.nodes: self.build(n, graph, cluster) elif type(obj).__name__ == 'SequenceNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=repr(obj)) for n in obj.nodes: self.build(n, graph, cluster) elif type(obj).__name__ == 'CodeNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=["CODE NODE 0x%x" % obj.addr] + self._render_condition("Reaching Condition",obj.reaching_condition)) self.build(obj.node, graph, cluster) elif type(obj).__name__ == 'LoopNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=["LOOP NODE 0x%x" % obj.addr] + self._render_condition("Condition",obj.condition)) self.build(obj.sequence_node, graph, cluster) elif type(obj).__name__ == 'ConditionNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=["CONDITION NODE 0x%x" % obj.addr] + self._render_condition("Condition",obj.condition) + self._render_condition("Reaching Condition", obj.reaching_condition)) if obj.true_node: self.build(obj.true_node, graph, cluster) if obj.false_node: self.build(obj.false_node, graph, cluster) elif type(obj).__name__ == 'BreakNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=["BREAK NODE"]) self.build(obj.target, graph, cluster) elif type(obj).__name__ == 'ConditionalBreakNode': cluster = graph.create_cluster(str(self.seq.next()), parent=parent_cluster, label=["CONDITIONAL BREAK NODE"] + self._render_condition("Condition",obj.condition)) self.build(obj.target, graph, cluster) elif type(obj).__name__ == 'Block': self.block_to_cluster[obj] = parent_cluster elif type(obj).__name__ == 'BlockNode': self.block_to_cluster[obj] = parent_cluster elif type(obj).__name__ == 'HookNode': self.block_to_cluster[obj] = parent_cluster elif isinstance(obj, nx.DiGraph): for n in obj.nodes(): self.build(n, graph, parent_cluster) else: print type(obj) import ipdb; ipdb.set_trace() def cluster(self, graph): self.build(self.struct, graph, None) to_remove = [] for n in graph.nodes: if n.obj in self.block_to_cluster: cluster = self.block_to_cluster[n.obj] if cluster: cluster.add_node(n) else: to_remove.append(n) if self.remove_unclustered: for n in to_remove: graph.remove_node(n) @staticmethod def _render_condition(label, condition): if condition is None: return ["%s: None" % label] else: return ["%s:" % label] + AngrStructuredClusterer._render_condition_ast(condition, 1) @staticmethod def _render_condition_ast(condition, level=0): ret = [] if (condition.op == 'And') or (condition.op == 'Or'): ret.append(" "*(level) + condition.op + " (") for arg in condition.args: ret += AngrStructuredClusterer._render_condition_ast(arg, level+1) ret.append(" "*(level) + ")") else: ret.append(" "*level + str(condition)) return ret
const schema = [ { enum: ['bool', 'boolean'], type: 'string', }, ]; const create = (context) => { const longForm = (context.options[0] || 'boolean') === 'boolean'; return { BooleanTypeAnnotation(node) { const diff = node.range[1] - node.range[0]; if (longForm && diff === 4) { context.report({ fix(fixer) { return fixer.replaceText(node, 'boolean'); }, message: 'Use "boolean", not "bool"', node, }); } if (!longForm && diff !== 4) { context.report({ fix(fixer) { return fixer.replaceText(node, 'bool'); }, message: 'Use "bool", not "boolean"', node, }); } }, }; }; export default { create, meta: { fixable: 'code', }, schema, };
var app = angular.module('myapp', ['ui.bootstrap', 'ngResource']); app.factory('empservice', ['$resource', function ($resource) { var url = 'http://myngwebapi.azurewebsites.net/api'; var result = $resource(url + '/employee/:no', { no: '@no' } , { update: { method: 'PUT' } }); return result; }]); app.controller('listctrl', ['empservice', '$uibModal', function (empservice, $uibModal) { var self = this; self.emps = []; self.emps = empservice.query(); self.open = function (itemobj) { $uibModal.open({ animation:true, templateUrl: 'dialog11.html', controller: 'detailctrl as empctrl', resolve: { item: function () { return itemobj }, } }); } }]); app.controller('detailctrl', ['empservice','$uibModalInstance', 'item' , function (empservice, $uibModalInstance, item) { console.log(item); var self = this; self.emp = item; }]);
!function(log, console, enabled){ forEach.call(array(CONSOLE_METHODS), function(key){ log[key] = function(){ if(enabled && key in console)return apply.call(console[key], console, arguments); }; }); $define(GLOBAL + FORCED, {log: assign(log.log, log, { enable: function(){ enabled = true; }, disable: function(){ enabled = false; } })}); }({}, global.console || {}, true);
import { CollapseModel } from "./Collapse"; import { DialogModel } from "./Dialog"; import { HeaderModel } from "./Header"; import { ViewModel } from "./View"; import { StyleModel } from "./Style"; import { FilterModel } from "./Filter"; export { CollapseModel, DialogModel, HeaderModel, ViewModel, StyleModel, FilterModel };
var mbaasApi = require('fh-mbaas-api'); var express = require('express'); var mbaasExpress = mbaasApi.mbaasExpress(); var cors = require('cors'); // list the endpoints which you want to make securable here var securableEndpoints; // fhlint-begin: securable-endpoints securableEndpoints = ['/hello']; // fhlint-end var app = express(); // Enable CORS for all requests app.use(cors()); // Note: the order which we add middleware to Express here is important! app.use('/sys', mbaasExpress.sys(securableEndpoints)); app.use('/mbaas', mbaasExpress.mbaas); // allow serving of static files from the public directory app.use(express.static(__dirname + '/public')); // Note: important that this is added just before your own Routes app.use(mbaasExpress.fhmiddleware()); // fhlint-begin: custom-routes app.use('/hello', require('./lib/hello.js')()); app.use('/database', require('./lib/database.js')()); // fhlint-end // Important that this is last! app.use(mbaasExpress.errorHandler()); var port = process.env.FH_PORT || process.env.OPENSHIFT_NODEJS_PORT || 8001; var host = process.env.OPENSHIFT_NODEJS_IP || '0.0.0.0'; var server = app.listen(port, host, function() { console.log("App started at: " + new Date() + " on port: " + port); });
const axios = require('../../../utils/axios'); const cheerio = require('cheerio'); const url = require('url'); const typelist = ['通知公告', '院所新闻', '教学信息', '学术动态', '学院简报']; const urlList = ['xwdt/tzgg.htm', 'xwdt/ysxw.htm', 'xwdt/jxxx.htm', 'xwdt/xsdt.htm', 'xwdt/xyjb.htm']; const host = 'http://www.mech.sdu.edu.cn/'; module.exports = async (ctx) => { const type = parseInt(ctx.params.type) || 0; const link = url.resolve(host, urlList[type]); const response = await axios.get(link); const $ = cheerio.load(response.data); const list = $('#page_list li a') .map((i, e) => $(e).attr('href')) .get(); const out = await Promise.all( list.filter((e) => e.startsWith('../info') || e.startsWith('http://www.rd.sdu.edu.cn/')).map(async (itemUrl) => { const isFromMech = itemUrl.startsWith('../info'); if (isFromMech) { itemUrl = url.resolve(host, itemUrl.slice('3')); } const cache = await ctx.cache.get(itemUrl); if (cache) { return Promise.resolve(JSON.parse(cache)); } const response = await axios.get(itemUrl); const $ = cheerio.load(response.data); const rawDate = $('#show_info') .text() .split(/\s{4}/); let date = rawDate[0].split(':')[1]; date = date.slice(0, 4) + '-' + date.slice(5, 7) + '-' + date.slice(8, 10) + ' ' + date.slice(11); const single = { title: $('#show_title') .text() .trim(), link: itemUrl, author: '山东大学机械工程学院', description: $('#show_content').html(), pubDate: new Date(date), }; ctx.cache.set(itemUrl, JSON.stringify(single), 24 * 60 * 60); return Promise.resolve(single); }) ); ctx.state.data = { title: `山东大学机械工程学院${typelist[type]}`, link, item: out, }; };
import jwt from bs4 import BeautifulSoup from urllib.parse import urlparse, parse_qs from .api_info import ApiInfo from .exceptions import * def parse_token(url: str) -> tuple: redirect_url = str(url).replace("#", "?") # Patch the URL if 'Lockout' in redirect_url: raise Lockout if 'LoginWith2fa' in redirect_url: raise TwoFactorAuthenticatorEnabled # 2FA enabled! if 'access_token' not in redirect_url: raise InvalidAccountCredentials # Login unsuccessful! parsed_url = urlparse(redirect_url) bearer_token = parse_qs(parsed_url.query)['access_token'][0] # Acquire the bearer token from the URL return bearer_token def decode_token(token: str) -> dict: decoded = jwt.decode(token, options={"verify_signature": False}) # Decode the bearer token return decoded def parse_rvt(html: str) -> str: soup = BeautifulSoup(html, features="html.parser") rvt = soup.find('input', {'name': '__RequestVerificationToken'}).get('value') # Acquire the Request Verification Token return rvt def create_body(username: str, password: str, rvt: str) -> str: body = ApiInfo.BODY.format(name=username, password=password, rvt=rvt) return body def create_twofa_body(twofa_code: str, rvt: str) -> str: body = ApiInfo.TWOFA_BODY.format(twofa_code=twofa_code, rvt=rvt) return body def prompt_2fa() -> str: twofa_code = "" while True: twofa_code = input(debug_text("Authenticator code: ")) if not twofa_code: raise TwoFactorAuthenticatorCancelled if len(twofa_code) >= 6 and len(twofa_code) <= 7: return twofa_code print(debug_text("The Authenticator code must be at least 6 and at max 7 characters long.")) def debug_text(text: str) -> str: signature = "RecNetLogin – " return signature + text
function insert(){"use strict";var e=document.getElementById("assembling"),d=document.getElementById("note-1").cloneNode(!0),n=document.getElementById("supLink1"),t=document.getElementById("note-2").cloneNode(!0),o=document.getElementById("supLink2"),l=document.getElementById("note-3").cloneNode(!0),c=document.getElementById("supLink3"),m=document.getElementById("note-4").cloneNode(!0),i=document.getElementById("supLink4");n.appendChild(d),o.appendChild(t),c.appendChild(l),i.appendChild(m),d.id="clonedNode1",t.id="clonedNode2",l.id="clonedNode3",m.id="clonedNode4",e.classList.add("fs-desktop-vw-10","fs-3_75")}insert();
import Vue from 'vue' import Vuex from 'vuex'; import mutations from "./mutations"; import actions from "./actions"; // 1.安装插件 Vue.use(Vuex) // 2.创建Store对象 const state = { cartList: [] } const store = new Vuex.Store({ state, mutations, actions }) // 3.挂载Vue实例上 export default store
import unittest def bubble_sort(seq): ''' :param seq: :return: seq ordenada Complexidade (Pior Caso) Tempo: O(n^2) Memória: O(1) Complexidade (Melhor Caso - Lista de entrada já está ordenada) Tempo: O(n) Memória: O(1) ''' for i in range(len(seq)-1): if seq == sorted(seq): break for x in range(len(seq)-1): if seq[x] > seq[x+1]: seq[x], seq[x+1] = seq[x+1], seq[x] return seq class OrdenacaoTestes(unittest.TestCase): def teste_lista_vazia(self): self.assertListEqual([], bubble_sort([])) def teste_lista_unitaria(self): self.assertListEqual([1], bubble_sort([1])) def teste_lista_binaria(self): self.assertListEqual([1, 2], bubble_sort([1, 2])) def teste_lista_desordenada(self): self.assertListEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], bubble_sort([9, 7, 1, 8, 5, 3, 6, 4, 2, 0])) if __name__ == '__main__': unittest.main()
""" https://leetcode.com/problems/n-ary-tree-level-order-traversal/ https://leetcode.com/submissions/detail/184433348/ """ """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ from common.n_ary_tree_node import Node class Solution(object): def levelOrder(self, root): """ :type root: Node :rtype: List[List[int]] """ ans = [] def traverse(node, depth): if not node: return if len(ans) < depth: ans.append([]) ans[depth - 1].append(node.val) for child in node.children: traverse(child, depth + 1) traverse(root, 1) return ans import unittest class Test(unittest.TestCase): def test(self): solution = Solution() rootNode1 = Node(1, [ Node(3, [ Node(5, []), Node(6, []) ]), Node(2, []), Node(4, []) ]) self.assertEqual(solution.levelOrder(rootNode1), [ [1], [3, 2, 4], [5, 6] ]) if __name__ == '__main__': unittest.main()
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright IBM Corp. 2016, 2018 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ import PropTypes from 'prop-types'; import React from 'react'; import classNames from 'classnames'; import { settings } from 'carbon-components'; var prefix = settings.prefix; var TabContent = function TabContent(props) { var className = props.className, selected = props.selected, children = props.children, other = _objectWithoutProperties(props, ["className", "selected", "children"]); var tabContentClasses = classNames("".concat(prefix, "--tab-content"), _defineProperty({}, className, className)); return /*#__PURE__*/React.createElement("div", _extends({ role: "tabpanel" }, other, { className: tabContentClasses, selected: selected, hidden: !selected, "aria-live": "polite" }), children); }; TabContent.propTypes = { /** * Pass in content to render inside of the TabContent */ children: PropTypes.node, /** * Provide a className for the tab content container */ className: PropTypes.string, /** * Specify whether the TabContent is selected */ selected: PropTypes.bool }; TabContent.defaultProps = { selected: false }; export default TabContent;
var isObject = require('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var objectToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 8-9 which returns 'object' for typed array and other constructors. var tag = isObject(value) ? objectToString.call(value) : ''; return tag == funcTag || tag == genTag || tag == proxyTag; } module.exports = isFunction;
const test = require('tape') const testCommon = require('./common') const operations = [] // The db must wait for pending operations to finish before closing. This to // prevent segfaults and in the case of compactRange() to prevent hanging. See // https://github.com/Level/leveldown/issues/157 and 32. function testPending (name, expectedCount, fn) { operations.push(fn) test(`close() waits for pending ${name}`, function (t) { const db = testCommon.factory() let count = 0 db.open(function (err) { t.ifError(err, 'no error from open()') db.put('key', 'value', function (err) { t.ifError(err, 'no error from put()') fn(db, function (err) { count++ t.ifError(err, 'no error from operation') }) db.close(function (err) { t.ifError(err, 'no error from close()') t.is(count, expectedCount, 'operation(s) finished before close') t.end() }) }) }) }) } testPending('get()', 1, function (db, next) { db.get('key', next) }) testPending('put()', 1, function (db, next) { db.put('key2', 'value', next) }) testPending('put() with { sync }', 1, function (db, next) { // The sync option makes the operation slower and thus more likely to // cause a segfault (if closing were to happen during the operation). db.put('key2', 'value', { sync: true }, next) }) testPending('del()', 1, function (db, next) { db.del('key', next) }) testPending('del() with { sync }', 1, function (db, next) { db.del('key', { sync: true }, next) }) testPending('batch([])', 1, function (db, next) { db.batch([{ type: 'del', key: 'key' }], next) }) testPending('batch([]) with { sync }', 1, function (db, next) { db.batch([{ type: 'del', key: 'key' }], { sync: true }, next) }) testPending('batch()', 1, function (db, next) { db.batch().del('key').write(next) }) testPending('batch() with { sync }', 1, function (db, next) { db.batch().del('key').write({ sync: true }, next) }) testPending('approximateSize()', 1, function (db, next) { db.approximateSize('a', 'z', next) }) testPending('compactRange()', 1, function (db, next) { db.compactRange('a', 'z', next) }) // Test multiple pending operations, using all of the above. testPending('operations', operations.length, function (db, next) { for (let fn of operations.slice(0, -1)) { fn(db, next) } }) // See https://github.com/Level/leveldown/issues/134 test('iterator() does not segfault if db is not open', function (t) { t.plan(2) const db = testCommon.factory() try { db.iterator() } catch (err) { t.is(err.message, 'cannot call iterator() before open()') } db.close(function (err) { t.ifError(err, 'no close error') }) })
import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.cluster import KMeans # creation de base d'apprentissage X, y = make_blobs( n_samples=150, n_features=2, centers=3, cluster_std=0.5, shuffle=True, random_state=0 ) # visualiser les point avant de classer plt.scatter( X[:, 0], X[:, 1], c='white', marker='o', edgecolor='black', s=50 ) plt.show() #Kmeans km = KMeans( n_clusters=3, init='random', n_init=10, max_iter=300, tol=1e-04, random_state=0 ) y_km = km.fit_predict(X) #représenter les groupes plt.scatter( X[y_km == 0, 0], X[y_km == 0, 1], s=50, c='lightgreen', marker='s', edgecolor='black', label='cluster 1' ) plt.scatter( X[y_km == 1, 0], X[y_km == 1, 1], s=50, c='orange', marker='o', edgecolor='black', label='cluster 2' ) plt.scatter( X[y_km == 2, 0], X[y_km == 2, 1], s=50, c='lightblue', marker='v', edgecolor='black', label='cluster 3' ) # représenter les centres de groupe plt.scatter( km.cluster_centers_[:, 0], km.cluster_centers_[:, 1], s=250, marker='*', c='red', edgecolor='black', label='centroids' ) plt.legend(scatterpoints=1) plt.grid() plt.show() # calculate distortion for a range of number of cluster distortions = [] for i in range(1, 11): km = KMeans( n_clusters=i, init='random', n_init=10, max_iter=300, tol=1e-04, random_state=0 ) km.fit(X) distortions.append(km.inertia_) # plot plt.plot(range(1, 11), distortions, marker='o') plt.xlabel('Number of clusters') plt.ylabel('Distortion') plt.show()
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @flow * @nolint * @format */ // TODO (bvaughn) Remove this file once flowtype/flow-typed/pull/773 is merged type $npm$propTypes$ReactPropsCheckType = ( props: any, propName: string, componentName: string, href?: string, ) => ?Error; declare module 'prop-types' { declare var array: React$PropType$Primitive<Array<any>>; declare var bool: React$PropType$Primitive<boolean>; declare var func: React$PropType$Primitive<Function>; declare var number: React$PropType$Primitive<number>; declare var object: React$PropType$Primitive<Object>; declare var string: React$PropType$Primitive<string>; declare var any: React$PropType$Primitive<any>; declare var arrayOf: React$PropType$ArrayOf; declare var element: React$PropType$Primitive<any>; /* TODO */ declare var instanceOf: React$PropType$InstanceOf; declare var node: React$PropType$Primitive<any>; /* TODO */ declare var objectOf: React$PropType$ObjectOf; declare var oneOf: React$PropType$OneOf; declare var oneOfType: React$PropType$OneOfType; declare var shape: React$PropType$Shape; declare function checkPropTypes<V>( propTypes: $Subtype<{[_: $Keys<V>]: $npm$propTypes$ReactPropsCheckType}>, values: V, location: string, componentName: string, getStack: ?() => ?string, ): void; }
# Copyright 2017, Google LLC 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.""" import pytest from google.cloud import bigquery_datatransfer_v1 from google.cloud.bigquery_datatransfer_v1.proto import datatransfer_pb2 from google.cloud.bigquery_datatransfer_v1.proto import transfer_pb2 from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 from google.protobuf import timestamp_pb2 class MultiCallableStub(object): """Stub for the grpc.UnaryUnaryMultiCallable interface.""" def __init__(self, method, channel_stub): self.method = method self.channel_stub = channel_stub def __call__(self, request, timeout=None, metadata=None, credentials=None): self.channel_stub.requests.append((self.method, request)) response = None if self.channel_stub.responses: response = self.channel_stub.responses.pop() if isinstance(response, Exception): raise response if response: return response class ChannelStub(object): """Stub for the grpc.Channel interface.""" def __init__(self, responses=[]): self.responses = responses self.requests = [] def unary_unary(self, method, request_serializer=None, response_deserializer=None): return MultiCallableStub(method, self) class CustomException(Exception): pass class TestDataTransferServiceClient(object): def test_get_data_source(self): # Setup Expected Response name_2 = 'name2-1052831874' data_source_id = 'dataSourceId-1015796374' display_name = 'displayName1615086568' description = 'description-1724546052' client_id = 'clientId-1904089585' supports_multiple_transfers = True update_deadline_seconds = 991471694 default_schedule = 'defaultSchedule-800168235' supports_custom_schedule = True help_url = 'helpUrl-789431439' default_data_refresh_window_days = -1804935157 manual_runs_disabled = True expected_response = { 'name': name_2, 'data_source_id': data_source_id, 'display_name': display_name, 'description': description, 'client_id': client_id, 'supports_multiple_transfers': supports_multiple_transfers, 'update_deadline_seconds': update_deadline_seconds, 'default_schedule': default_schedule, 'supports_custom_schedule': supports_custom_schedule, 'help_url': help_url, 'default_data_refresh_window_days': default_data_refresh_window_days, 'manual_runs_disabled': manual_runs_disabled } expected_response = datatransfer_pb2.DataSource(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_data_source_path('[PROJECT]', '[LOCATION]', '[DATA_SOURCE]') response = client.get_data_source(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.GetDataSourceRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_get_data_source_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_data_source_path('[PROJECT]', '[LOCATION]', '[DATA_SOURCE]') with pytest.raises(CustomException): client.get_data_source(name) def test_list_data_sources(self): # Setup Expected Response next_page_token = '' data_sources_element = {} data_sources = [data_sources_element] expected_response = { 'next_page_token': next_page_token, 'data_sources': data_sources } expected_response = datatransfer_pb2.ListDataSourcesResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_path('[PROJECT]', '[LOCATION]') paged_list_response = client.list_data_sources(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.data_sources[0] == resources[0] assert len(channel.requests) == 1 expected_request = datatransfer_pb2.ListDataSourcesRequest( parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_data_sources_exception(self): channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_path('[PROJECT]', '[LOCATION]') paged_list_response = client.list_data_sources(parent) with pytest.raises(CustomException): list(paged_list_response) def test_create_transfer_config(self): # Setup Expected Response name = 'name3373707' destination_dataset_id = 'destinationDatasetId1541564179' display_name = 'displayName1615086568' data_source_id = 'dataSourceId-1015796374' schedule = 'schedule-697920873' data_refresh_window_days = 327632845 disabled = True user_id = -147132913 dataset_region = 'datasetRegion959248539' expected_response = { 'name': name, 'destination_dataset_id': destination_dataset_id, 'display_name': display_name, 'data_source_id': data_source_id, 'schedule': schedule, 'data_refresh_window_days': data_refresh_window_days, 'disabled': disabled, 'user_id': user_id, 'dataset_region': dataset_region } expected_response = transfer_pb2.TransferConfig(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_path('[PROJECT]', '[LOCATION]') transfer_config = {} response = client.create_transfer_config(parent, transfer_config) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.CreateTransferConfigRequest( parent=parent, transfer_config=transfer_config) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_create_transfer_config_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_path('[PROJECT]', '[LOCATION]') transfer_config = {} with pytest.raises(CustomException): client.create_transfer_config(parent, transfer_config) def test_update_transfer_config(self): # Setup Expected Response name = 'name3373707' destination_dataset_id = 'destinationDatasetId1541564179' display_name = 'displayName1615086568' data_source_id = 'dataSourceId-1015796374' schedule = 'schedule-697920873' data_refresh_window_days = 327632845 disabled = True user_id = -147132913 dataset_region = 'datasetRegion959248539' expected_response = { 'name': name, 'destination_dataset_id': destination_dataset_id, 'display_name': display_name, 'data_source_id': data_source_id, 'schedule': schedule, 'data_refresh_window_days': data_refresh_window_days, 'disabled': disabled, 'user_id': user_id, 'dataset_region': dataset_region } expected_response = transfer_pb2.TransferConfig(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request transfer_config = {} update_mask = {} response = client.update_transfer_config(transfer_config, update_mask) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.UpdateTransferConfigRequest( transfer_config=transfer_config, update_mask=update_mask) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_update_transfer_config_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request transfer_config = {} update_mask = {} with pytest.raises(CustomException): client.update_transfer_config(transfer_config, update_mask) def test_delete_transfer_config(self): channel = ChannelStub() client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_transfer_config_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') client.delete_transfer_config(name) assert len(channel.requests) == 1 expected_request = datatransfer_pb2.DeleteTransferConfigRequest( name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_delete_transfer_config_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_transfer_config_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') with pytest.raises(CustomException): client.delete_transfer_config(name) def test_get_transfer_config(self): # Setup Expected Response name_2 = 'name2-1052831874' destination_dataset_id = 'destinationDatasetId1541564179' display_name = 'displayName1615086568' data_source_id = 'dataSourceId-1015796374' schedule = 'schedule-697920873' data_refresh_window_days = 327632845 disabled = True user_id = -147132913 dataset_region = 'datasetRegion959248539' expected_response = { 'name': name_2, 'destination_dataset_id': destination_dataset_id, 'display_name': display_name, 'data_source_id': data_source_id, 'schedule': schedule, 'data_refresh_window_days': data_refresh_window_days, 'disabled': disabled, 'user_id': user_id, 'dataset_region': dataset_region } expected_response = transfer_pb2.TransferConfig(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_transfer_config_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') response = client.get_transfer_config(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.GetTransferConfigRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_get_transfer_config_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_transfer_config_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') with pytest.raises(CustomException): client.get_transfer_config(name) def test_list_transfer_configs(self): # Setup Expected Response next_page_token = '' transfer_configs_element = {} transfer_configs = [transfer_configs_element] expected_response = { 'next_page_token': next_page_token, 'transfer_configs': transfer_configs } expected_response = datatransfer_pb2.ListTransferConfigsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_path('[PROJECT]', '[LOCATION]') paged_list_response = client.list_transfer_configs(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.transfer_configs[0] == resources[0] assert len(channel.requests) == 1 expected_request = datatransfer_pb2.ListTransferConfigsRequest( parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_transfer_configs_exception(self): channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_path('[PROJECT]', '[LOCATION]') paged_list_response = client.list_transfer_configs(parent) with pytest.raises(CustomException): list(paged_list_response) def test_schedule_transfer_runs(self): # Setup Expected Response expected_response = {} expected_response = datatransfer_pb2.ScheduleTransferRunsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_transfer_config_path( '[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') start_time = {} end_time = {} response = client.schedule_transfer_runs(parent, start_time, end_time) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.ScheduleTransferRunsRequest( parent=parent, start_time=start_time, end_time=end_time) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_schedule_transfer_runs_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_transfer_config_path( '[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') start_time = {} end_time = {} with pytest.raises(CustomException): client.schedule_transfer_runs(parent, start_time, end_time) def test_get_transfer_run(self): # Setup Expected Response name_2 = 'name2-1052831874' destination_dataset_id = 'destinationDatasetId1541564179' data_source_id = 'dataSourceId-1015796374' user_id = -147132913 schedule = 'schedule-697920873' expected_response = { 'name': name_2, 'destination_dataset_id': destination_dataset_id, 'data_source_id': data_source_id, 'user_id': user_id, 'schedule': schedule } expected_response = transfer_pb2.TransferRun(**expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') response = client.get_transfer_run(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.GetTransferRunRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_get_transfer_run_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') with pytest.raises(CustomException): client.get_transfer_run(name) def test_delete_transfer_run(self): channel = ChannelStub() client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') client.delete_transfer_run(name) assert len(channel.requests) == 1 expected_request = datatransfer_pb2.DeleteTransferRunRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_delete_transfer_run_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') with pytest.raises(CustomException): client.delete_transfer_run(name) def test_list_transfer_runs(self): # Setup Expected Response next_page_token = '' transfer_runs_element = {} transfer_runs = [transfer_runs_element] expected_response = { 'next_page_token': next_page_token, 'transfer_runs': transfer_runs } expected_response = datatransfer_pb2.ListTransferRunsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_transfer_config_path( '[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') paged_list_response = client.list_transfer_runs(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.transfer_runs[0] == resources[0] assert len(channel.requests) == 1 expected_request = datatransfer_pb2.ListTransferRunsRequest( parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_transfer_runs_exception(self): channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_transfer_config_path( '[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]') paged_list_response = client.list_transfer_runs(parent) with pytest.raises(CustomException): list(paged_list_response) def test_list_transfer_logs(self): # Setup Expected Response next_page_token = '' transfer_messages_element = {} transfer_messages = [transfer_messages_element] expected_response = { 'next_page_token': next_page_token, 'transfer_messages': transfer_messages } expected_response = datatransfer_pb2.ListTransferLogsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request parent = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') paged_list_response = client.list_transfer_logs(parent) resources = list(paged_list_response) assert len(resources) == 1 assert expected_response.transfer_messages[0] == resources[0] assert len(channel.requests) == 1 expected_request = datatransfer_pb2.ListTransferLogsRequest( parent=parent) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_list_transfer_logs_exception(self): channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request parent = client.location_run_path('[PROJECT]', '[LOCATION]', '[TRANSFER_CONFIG]', '[RUN]') paged_list_response = client.list_transfer_logs(parent) with pytest.raises(CustomException): list(paged_list_response) def test_check_valid_creds(self): # Setup Expected Response has_valid_creds = False expected_response = {'has_valid_creds': has_valid_creds} expected_response = datatransfer_pb2.CheckValidCredsResponse( **expected_response) # Mock the API response channel = ChannelStub(responses=[expected_response]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup Request name = client.location_data_source_path('[PROJECT]', '[LOCATION]', '[DATA_SOURCE]') response = client.check_valid_creds(name) assert expected_response == response assert len(channel.requests) == 1 expected_request = datatransfer_pb2.CheckValidCredsRequest(name=name) actual_request = channel.requests[0][1] assert expected_request == actual_request def test_check_valid_creds_exception(self): # Mock the API response channel = ChannelStub(responses=[CustomException()]) client = bigquery_datatransfer_v1.DataTransferServiceClient( channel=channel) # Setup request name = client.location_data_source_path('[PROJECT]', '[LOCATION]', '[DATA_SOURCE]') with pytest.raises(CustomException): client.check_valid_creds(name)
/*! jQuery UI - v1.10.4 - 2014-01-17 * http://jqueryui.com * Copyright 2014 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.km={closeText:"ធ្វើ​រួច",prevText:"មុន",nextText:"បន្ទាប់",currentText:"ថ្ងៃ​នេះ",monthNames:["មករា","កុម្ភៈ","មីនា","មេសា","ឧសភា","មិថុនា","កក្កដា","សីហា","កញ្ញា","តុលា","វិច្ឆិកា","ធ្នូ"],monthNamesShort:["មករា","កុម្ភៈ","មីនា","មេសា","ឧសភា","មិថុនា","កក្កដា","សីហា","កញ្ញា","តុលា","វិច្ឆិកា","ធ្នូ"],dayNames:["អាទិត្យ","ចន្ទ","អង្គារ","ពុធ","ព្រហស្បតិ៍","សុក្រ","សៅរ៍"],dayNamesShort:["អា","ច","អ","ពុ","ព្រហ","សុ","សៅ"],dayNamesMin:["អា","ច","អ","ពុ","ព្រហ","សុ","សៅ"],weekHeader:"សប្ដាហ៍",dateFormat:"dd-mm-yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.km)});
var searchData= [ ['modelinvalid_0',['ModelInvalid',['../namespaceGoogle_1_1OrTools_1_1Sat.html#abd593c9e6d551c806d04abc386a505e8aa1cc2f9a5c97bd1133373ebbc79fd554',1,'Google::OrTools::Sat']]] ];
import urllib.parse from django.contrib.auth.models import User from django.test import TestCase from dfirtrack_main.models import Recommendation class RecommendationViewTestCase(TestCase): """recommendation view tests""" @classmethod def setUpTestData(cls): # create object Recommendation.objects.create(recommendation_name='recommendation_1') # create user User.objects.create_user( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) def test_recommendation_list_not_logged_in(self): """test list view""" # create url destination = '/login/?next=' + urllib.parse.quote('/recommendation/', safe='') # get response response = self.client.get('/recommendation/', follow=True) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_list_logged_in(self): """test list view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/') # compare self.assertEqual(response.status_code, 200) def test_recommendation_list_template(self): """test list view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/') # compare self.assertTemplateUsed( response, 'dfirtrack_main/recommendation/recommendation_list.html' ) def test_recommendation_list_get_user_context(self): """test list view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/') # compare self.assertEqual(str(response.context['user']), 'testuser_recommendation') def test_recommendation_list_redirect(self): """test list view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create url destination = urllib.parse.quote('/recommendation/', safe='/') # get response response = self.client.get('/recommendation', follow=True) # compare self.assertRedirects( response, destination, status_code=301, target_status_code=200 ) def test_recommendation_detail_not_logged_in(self): """test detail view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # create url destination = '/login/?next=' + urllib.parse.quote( '/recommendation/' + str(recommendation_1.recommendation_id) + '/', safe='' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/', follow=True, ) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_detail_logged_in(self): """test detail view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/' ) # compare self.assertEqual(response.status_code, 200) def test_recommendation_detail_template(self): """test detail view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/' ) # compare self.assertTemplateUsed( response, 'dfirtrack_main/recommendation/recommendation_detail.html' ) def test_recommendation_detail_get_user_context(self): """test detail view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/' ) # compare self.assertEqual(str(response.context['user']), 'testuser_recommendation') def test_recommendation_detail_redirect(self): """test detail view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create url destination = urllib.parse.quote( '/recommendation/' + str(recommendation_1.recommendation_id) + '/', safe='/' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id), follow=True ) # compare self.assertRedirects( response, destination, status_code=301, target_status_code=200 ) def test_recommendation_add_not_logged_in(self): """test add view""" # create url destination = '/login/?next=' + urllib.parse.quote( '/recommendation/add/', safe='' ) # get response response = self.client.get('/recommendation/add/', follow=True) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_add_logged_in(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add/') # compare self.assertEqual(response.status_code, 200) def test_recommendation_add_template(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add/') # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form.html') def test_recommendation_add_get_user_context(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add/') # compare self.assertEqual(str(response.context['user']), 'testuser_recommendation') def test_recommendation_add_redirect(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create url destination = urllib.parse.quote('/recommendation/add/', safe='/') # get response response = self.client.get('/recommendation/add', follow=True) # compare self.assertRedirects( response, destination, status_code=301, target_status_code=200 ) def test_recommendation_add_post_redirect(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = { 'recommendation_name': 'recommendation_add_post_test', } # get response response = self.client.post('/recommendation/add/', data_dict) # get object recommendation_id = Recommendation.objects.get( recommendation_name='recommendation_add_post_test' ).recommendation_id # create url destination = urllib.parse.quote( '/recommendation/' + str(recommendation_id) + '/', safe='/' ) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_add_post_invalid_reload(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = {} # get response response = self.client.post('/recommendation/add/', data_dict) # compare self.assertEqual(response.status_code, 200) def test_recommendation_add_post_invalid_template(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = {} # get response response = self.client.post('/recommendation/add/', data_dict) # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form.html') def test_recommendation_add_popup_not_logged_in(self): """test add view""" # create url destination = '/login/?next=' + urllib.parse.quote( '/recommendation/add_popup/', safe='' ) # get response response = self.client.get('/recommendation/add_popup/', follow=True) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_add_popup_logged_in(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add_popup/') # compare self.assertEqual(response.status_code, 200) def test_recommendation_add_popup_template(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add_popup/') # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form_popup.html') def test_recommendation_add_popup_get_user_context(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get('/recommendation/add_popup/') # compare self.assertEqual(str(response.context['user']), 'testuser_recommendation') def test_recommendation_add_popup_redirect(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create url destination = urllib.parse.quote('/recommendation/add_popup/', safe='/') # get response response = self.client.get('/recommendation/add_popup', follow=True) # compare self.assertRedirects( response, destination, status_code=301, target_status_code=200 ) def test_recommendation_add_popup_post_redirect(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = { 'recommendation_name': 'recommendation_add_popup_post', } # get response response = self.client.post('/recommendation/add_popup/', data_dict) # compare self.assertEqual(response.status_code, 200) def test_recommendation_add_popup_post_invalid_reload(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = {} # get response response = self.client.post('/recommendation/add_popup/', data_dict) # compare self.assertEqual(response.status_code, 200) def test_recommendation_add_popup_post_invalid_template(self): """test add view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create post data data_dict = {} # get response response = self.client.post('/recommendation/add_popup/', data_dict) # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form_popup.html') def test_recommendation_edit_not_logged_in(self): """test edit view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # create url destination = '/login/?next=' + urllib.parse.quote( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/', safe='', ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/', follow=True, ) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_edit_logged_in(self): """test edit view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/' ) # compare self.assertEqual(response.status_code, 200) def test_recommendation_edit_template(self): """test edit view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/' ) # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form.html') def test_recommendation_edit_get_user_context(self): """test edit view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/' ) # compare self.assertEqual(str(response.context['user']), 'testuser_recommendation') def test_recommendation_edit_redirect(self): """test edit view""" # get object recommendation_1 = Recommendation.objects.get( recommendation_name='recommendation_1' ) # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create url destination = urllib.parse.quote( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/', safe='/', ) # get response response = self.client.get( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit', follow=True, ) # compare self.assertRedirects( response, destination, status_code=301, target_status_code=200 ) def test_recommendation_edit_post_redirect(self): """test edit view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # create object recommendation_1 = Recommendation.objects.create( recommendation_name='recommendation_edit_post_t_1' ) # create post data data_dict = { 'recommendation_name': 'recommendation_edit_post_t_2', } # get response response = self.client.post( '/recommendation/' + str(recommendation_1.recommendation_id) + '/edit/', data_dict, ) # get object recommendation_2 = Recommendation.objects.get( recommendation_name='recommendation_edit_post_t_2' ) # create url destination = urllib.parse.quote( '/recommendation/' + str(recommendation_2.recommendation_id) + '/', safe='/' ) # compare self.assertRedirects( response, destination, status_code=302, target_status_code=200 ) def test_recommendation_edit_post_invalid_reload(self): """test edit view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get object recommendation_id = Recommendation.objects.get( recommendation_name='recommendation_1' ).recommendation_id # create post data data_dict = {} # get response response = self.client.post( '/recommendation/' + str(recommendation_id) + '/edit/', data_dict ) # compare self.assertEqual(response.status_code, 200) def test_recommendation_edit_post_invalid_template(self): """test edit view""" # login testuser self.client.login( username='testuser_recommendation', password='f5n2U59eN7BVi7sM3209' ) # get object recommendation_id = Recommendation.objects.get( recommendation_name='recommendation_1' ).recommendation_id # create post data data_dict = {} # get response response = self.client.post( '/recommendation/' + str(recommendation_id) + '/edit/', data_dict ) # compare self.assertTemplateUsed(response, 'dfirtrack_main/generic_form.html')
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License; * you may not use this file except in compliance with the Elastic License. */ import { registerAcknowledgeRoute } from './register_acknowledge_route'; export function registerActionRoutes(server) { registerAcknowledgeRoute(server); }
/* Highstock JS v9.1.2 (2021-06-16) Indicator series type for Highcharts Stock (c) 2010-2021 Wojciech Chmiel License: www.highcharts.com/license */ 'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/indicators/supertrend",["highcharts","highcharts/modules/stock"],function(g){a(g);a.Highcharts=g;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function g(a,g,n,t){a.hasOwnProperty(g)||(a[g]=t.apply(null,n))}a=a?a._modules:{};g(a,"Stock/Indicators/Supertrend/SupertrendIndicator.js",[a["Core/Color/Palette.js"], a["Core/Series/SeriesRegistry.js"],a["Core/Utilities.js"]],function(a,g,n){function t(a,e,c){return{index:e,close:a.yData[e][c],x:a.xData[e]}}var B=this&&this.__extends||function(){var a=function(e,c){a=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(c,a){c.__proto__=a}||function(c,a){for(var d in a)a.hasOwnProperty(d)&&(c[d]=a[d])};return a(e,c)};return function(e,c){function d(){this.constructor=e}a(e,c);e.prototype=null===c?Object.create(c):(d.prototype=c.prototype,new d)}}(),y= g.seriesTypes,C=y.atr,z=y.sma,A=n.correctFloat,D=n.isArray;y=n.extend;var x=n.merge,E=n.objectEach;n=function(g){function e(){var c=null!==g&&g.apply(this,arguments)||this;c.data=void 0;c.linkedParent=void 0;c.options=void 0;c.points=void 0;return c}B(e,g);e.prototype.init=function(){z.prototype.init.apply(this,arguments);var c=this.options;c.cropThreshold=this.linkedParent.options.cropThreshold-(c.params.period-1)};e.prototype.drawGraph=function(){var c=this,d=c.options,a=c.linkedParent,e=a?a.points: [],g=c.points,n=c.graph,u=g.length,v=e.length-u;v=0<v?v:0;for(var F={options:{gapSize:d.gapSize}},m={top:[],bottom:[],intersect:[]},w={top:{styles:{lineWidth:d.lineWidth,lineColor:d.fallingTrendColor||d.color,dashStyle:d.dashStyle}},bottom:{styles:{lineWidth:d.lineWidth,lineColor:d.risingTrendColor||d.color,dashStyle:d.dashStyle}},intersect:d.changeTrendLine},b,l,f,h,k,p,q,r;u--;)b=g[u],l=g[u-1],f=e[u-1+v],h=e[u-2+v],k=e[u+v],p=e[u+v+1],q=b.options.color,r={x:b.x,plotX:b.plotX,plotY:b.plotY,isNull:!1}, !h&&f&&a.yData[f.index-1]&&(h=t(a,f.index-1,3)),!p&&k&&a.yData[k.index+1]&&(p=t(a,k.index+1,3)),!f&&h&&a.yData[h.index+1]?f=t(a,h.index+1,3):!f&&k&&a.yData[k.index-1]&&(f=t(a,k.index-1,3)),b&&f&&k&&h&&b.x!==f.x&&(b.x===k.x?(h=f,f=k):b.x===h.x?(f=h,h={close:a.yData[f.index-1][3],x:a.xData[f.index-1]}):p&&b.x===p.x&&(f=p,h=k)),l&&h&&f?(k={x:l.x,plotX:l.plotX,plotY:l.plotY,isNull:!1},b.y>=f.close&&l.y>=h.close?(b.color=q||d.fallingTrendColor||d.color,m.top.push(r)):b.y<f.close&&l.y<h.close?(b.color= q||d.risingTrendColor||d.color,m.bottom.push(r)):(m.intersect.push(r),m.intersect.push(k),m.intersect.push(x(k,{isNull:!0})),b.y>=f.close&&l.y<h.close?(b.color=q||d.fallingTrendColor||d.color,l.color=q||d.risingTrendColor||d.color,m.top.push(r),m.top.push(x(k,{isNull:!0}))):b.y<f.close&&l.y>=h.close&&(b.color=q||d.risingTrendColor||d.color,l.color=q||d.fallingTrendColor||d.color,m.bottom.push(r),m.bottom.push(x(k,{isNull:!0}))))):f&&(b.y>=f.close?(b.color=q||d.fallingTrendColor||d.color,m.top.push(r)): (b.color=q||d.risingTrendColor||d.color,m.bottom.push(r)));E(m,function(a,b){c.points=a;c.options=x(w[b].styles,F);c.graph=c["graph"+b+"Line"];z.prototype.drawGraph.call(c);c["graph"+b+"Line"]=c.graph});c.points=g;c.options=d;c.graph=n};e.prototype.getValues=function(a,d){var c=d.period;d=d.multiplier;var e=a.xData,g=a.yData,n=[],u=[],v=[],t=0===c?0:c-1,m=[],w=[],b;if(!(e.length<=c||!D(g[0])||4!==g[0].length||0>c)){a=C.prototype.getValues.call(this,a,{period:c}).yData;for(b=0;b<a.length;b++){var l= g[t+b];var f=g[t+b-1]||[];var h=m[b-1];var k=w[b-1];var p=v[b-1];0===b&&(h=k=p=0);c=A((l[1]+l[2])/2+d*a[b]);var q=A((l[1]+l[2])/2-d*a[b]);m[b]=c<h||f[3]>h?c:h;w[b]=q>k||f[3]<k?q:k;if(p===h&&l[3]<m[b]||p===k&&l[3]<w[b])var r=m[b];else if(p===h&&l[3]>m[b]||p===k&&l[3]>w[b])r=w[b];n.push([e[t+b],r]);u.push(e[t+b]);v.push(r)}return{values:n,xData:u,yData:v}}};e.defaultOptions=x(z.defaultOptions,{params:{index:void 0,multiplier:3,period:10},risingTrendColor:a.positiveColor,fallingTrendColor:a.negativeColor, changeTrendLine:{styles:{lineWidth:1,lineColor:a.neutralColor80,dashStyle:"LongDash"}}});return e}(z);y(n.prototype,{nameBase:"Supertrend",nameComponents:["multiplier","period"],requiredIndicators:["atr"]});g.registerSeriesType("supertrend",n);"";return n});g(a,"masters/indicators/supertrend.src.js",[],function(){})}); //# sourceMappingURL=supertrend.js.map
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule from mmcv.runner import BaseModule class DarknetBottleneck(BaseModule): """The basic bottleneck block used in Darknet. Each ResBlock consists of two ConvModules and the input is added to the final output. Each ConvModule is composed of Conv, BN, and LeakyReLU. The first convLayer has filter size of 1x1 and the second one has the filter size of 3x3. Args: in_channels (int): The input channels of this Module. out_channels (int): The output channels of this Module. expansion (int): The kernel size of the convolution. Default: 0.5 add_identity (bool): Whether to add identity to the out. Default: True use_depthwise (bool): Whether to use depthwise separable convolution. Default: False conv_cfg (dict): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='BN'). act_cfg (dict): Config dict for activation layer. Default: dict(type='Swish'). """ def __init__(self, in_channels, out_channels, expansion=0.5, add_identity=True, use_depthwise=False, conv_cfg=None, norm_cfg=dict(type='BN', momentum=0.03, eps=0.001), act_cfg=dict(type='Swish'), init_cfg=None): super().__init__(init_cfg) hidden_channels = int(out_channels * expansion) conv = DepthwiseSeparableConvModule if use_depthwise else ConvModule self.conv1 = ConvModule( in_channels, hidden_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.conv2 = conv( hidden_channels, out_channels, 3, stride=1, padding=1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.add_identity = \ add_identity and in_channels == out_channels def forward(self, x): identity = x out = self.conv1(x) out = self.conv2(out) if self.add_identity: return out + identity else: return out class CSPLayer(BaseModule): """Cross Stage Partial Layer. Args: in_channels (int): The input channels of the CSP layer. out_channels (int): The output channels of the CSP layer. expand_ratio (float): Ratio to adjust the number of channels of the hidden layer. Default: 0.5 num_blocks (int): Number of blocks. Default: 1 add_identity (bool): Whether to add identity in blocks. Default: True use_depthwise (bool): Whether to depthwise separable convolution in blocks. Default: False conv_cfg (dict, optional): Config dict for convolution layer. Default: None, which means using conv2d. norm_cfg (dict): Config dict for normalization layer. Default: dict(type='BN') act_cfg (dict): Config dict for activation layer. Default: dict(type='Swish') """ def __init__(self, in_channels, out_channels, expand_ratio=0.5, num_blocks=1, add_identity=True, use_depthwise=False, conv_cfg=None, norm_cfg=dict(type='BN', momentum=0.03, eps=0.001), act_cfg=dict(type='Swish'), init_cfg=None): super().__init__(init_cfg) mid_channels = int(out_channels * expand_ratio) self.main_conv = ConvModule( in_channels, mid_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.short_conv = ConvModule( in_channels, mid_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.final_conv = ConvModule( 2 * mid_channels, out_channels, 1, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) self.blocks = nn.Sequential(*[ DarknetBottleneck( mid_channels, mid_channels, 1.0, add_identity, use_depthwise, conv_cfg=conv_cfg, norm_cfg=norm_cfg, act_cfg=act_cfg) for _ in range(num_blocks) ]) def forward(self, x): x_short = self.short_conv(x) x_main = self.main_conv(x) x_main = self.blocks(x_main) x_final = torch.cat((x_main, x_short), dim=1) return self.final_conv(x_final)
var searchData= [ ['audio',['audio',['../namespacemv_1_1constants_1_1audio.html',1,'mv::constants::audio'],['../namespacemv_1_1constants_1_1error_1_1audio.html',1,'mv::constants::error::audio']]], ['banditmachine',['banditMachine',['../namespacemv_1_1constants_1_1error_1_1bandit_machine.html',1,'mv::constants::error']]], ['constants',['constants',['../namespacemv_1_1constants.html',1,'mv']]], ['error',['error',['../namespacemv_1_1constants_1_1error.html',1,'mv::constants']]], ['loader',['loader',['../namespacemv_1_1constants_1_1loader.html',1,'mv::constants']]], ['main',['main',['../main_8cpp.html#a3c04138a5bfe5d72780bb7e82a18e627',1,'main.cpp']]], ['main_2ecpp',['main.cpp',['../main_8cpp.html',1,'']]], ['manage',['manage',['../class_action_forwarder.html#a9a0977b96d99bfb129d3d726950888cd',1,'ActionForwarder']]], ['math',['Math',['../class_math.html',1,'']]], ['math_2ehpp',['Math.hpp',['../_math_8hpp.html',1,'']]], ['mousestate',['mouseState',['../class_scene.html#a2ce3780f0b8caef89e72a2b8fbde3a33',1,'Scene']]], ['move',['move',['../class_proper_body.html#a8ffa871e415da0b558a5776f8aaca08e',1,'ProperBody']]], ['multiplier',['multiplier',['../class_one_armed_bandit.html#a3bd59ee339183ab585e1ce8e2fdfdb0d',1,'OneArmedBandit']]], ['mv',['mv',['../namespacemv.html',1,'']]], ['scene',['scene',['../namespacemv_1_1constants_1_1error_1_1scene.html',1,'mv::constants::error']]], ['textmachine',['textMachine',['../namespacemv_1_1constants_1_1error_1_1text_machine.html',1,'mv::constants::error']]], ['texttypes',['textTypes',['../namespacemv_1_1constants_1_1text_types.html',1,'mv::constants']]], ['texture',['texture',['../namespacemv_1_1constants_1_1texture.html',1,'mv::constants']]], ['ui',['UI',['../namespacemv_1_1constants_1_1error_1_1_u_i.html',1,'mv::constants::error']]] ];
from datavalidation import data_validator, PASS, FAIL, NA, Summary from datavalidation.models import DataValidationMixin from .base import BaseModel class CReturnValues(DataValidationMixin, BaseModel): """ Class Method Data Validator Return Values tests: valid return values for class method validators """ @data_validator @classmethod def returning_result(cls): """ tests: returning PASS/FAIL """ if cls.objects.filter(foobar__gte=10).count() == 0: return PASS return FAIL @data_validator @classmethod def returning_bool(cls): """ tests: returning a bool """ return cls.objects.filter(foobar__gte=10).count() == 0 @data_validator @classmethod def returning_queryset(cls): """ tests: returning a queryset """ return cls.objects.filter(foobar__gte=10) @data_validator @classmethod def returning_list_of_models(cls): """ tests: returning a list """ return list(cls.objects.filter(foobar__gte=10)) @data_validator @classmethod def returning_list_of_model_ids(cls): """ tests: returning a list of ids """ return cls.objects.filter(foobar__gte=10).values_list("id", flat=True) @data_validator @classmethod def returning_summary(cls): return Summary( num_passing=cls.objects.filter(foobar__lt=10).count(), num_na=cls.objects.filter(foobar__isnull=True).count(), failures=cls.objects.filter(foobar__gte=10) ) @data_validator @classmethod def returning_bad_summary(cls): return Summary( failures=True # noqa ) @data_validator @classmethod def returning_na(cls): """ tests: returning NA (exception expected) """ return NA @data_validator @classmethod def returning_none(cls): """ tests: returning None (exception expected) """ return None @data_validator @classmethod def raising_exception(cls): """ tests: raising an exception """ raise ValueError("An Error!")
XSym 0078 a484d093f7fc350b117a180672f9bb59 /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/sre_compile.py
import React, { useState, useEffect } from "react"; import API from "../../utils/API"; import placeholder from './imageplaceholder.png'; import { Input } from "../../components/Form"; import { connect } from "react-redux"; import Nav from "../../components/Nav" import './style.css' //ignore eslint warnings /*eslint-disable */ //create state function SubmitBird({userId}) { const [birdObject, setBirdObject] = useState({}) const [birdObject64, setBirdObject64] = useState(0) const[imgUrl, setImgUrl] = useState("0") const [comment, setComment] = useState({}) const [{alt, src}, setImg] = useState({ src: placeholder, alt: 'Upload an Image' }) const [ currentPosition, setCurrentPosition ] = useState({}); const [gUserName, setGUserName] = useState({}) const handleImg = (e) => { if(e.target.files[0]) { setImg({ src: URL.createObjectURL(e.target.files[0]), alt: e.target.files[0].name }); } setBirdObject([ e.target.files[0] ]) } function loadUser() { // console.log(userId) API.findUser(userId) .then(user => { setGUserName(user.data[0].username) // console.log(user) }) } const success = position => { const userPosition = { lat: position.coords.latitude, lng: position.coords.longitude } setCurrentPosition(userPosition); }; useEffect(() => { navigator.geolocation.getCurrentPosition(success); },[]) useEffect(() => { loadUser() console.log(gUserName) }) useEffect((event) => { if(birdObject64 !== 0){ let base64 = birdObject64.toString() API.submitBird(base64.split(",")[1]).then(res => { // console.log(res) let response = res.data.responses[0].labelAnnotations.filter(desc => desc.description === "Bird") // console.log(response, 26) //IF BIRD DO THIS if(response.length > 0) { getSignedRequest(birdObject[0]) //IF NO BIRD DO THIS }else{ let alert = document.getElementById("alert") alert.textContent = "Sorry no bird was found in this image, please upload another" setInterval(() => { alert.textContent = "" }, 5000); document.getElementById("submitForm").reset(); } }) } },[birdObject64]) //SEND IMAGE ONCE URL HOOK IS SET useEffect((event) => { if (imgUrl !== "0") { // console.log(imgUrl) let data = { 'image': imgUrl, 'username': gUserName, 'userId': userId, 'lat': currentPosition.lat, 'lng': currentPosition.lng, 'comment': comment, } // console.log(userId) console.log(data) API.uploadPost(data) .then(res => console.log(res, "response")) let alert = document.getElementById("alert") alert.textContent = "Upload was a Success!" setInterval(() => { alert.textContent = "" }, 5000); document.getElementById("submitForm").reset(); } },[imgUrl]) //handle hook for image input function handleInputChange(event) { handleImg(event) }; //handle hook for comment input function handleCommentsChange(event) { // console.log(event.target.value) setComment( event.target.value ) } //form submit handling function handleFormSubmit(event) { event.preventDefault(); if(birdObject) { // // console.log (birdObject[0].size); if(parseInt(birdObject[0].size)> 1400000) { let reader = new FileReader(); reader.readAsDataURL(birdObject[0]); reader.onload = function () { setBirdObject64([reader.result]); }; reader.onloadend= function(){ // console.log(birdObject64) // console.log("before") resize(); } }else{ let reader = new FileReader(); reader.readAsDataURL(birdObject[0]); reader.onload = function () { }; reader.onloadend= function(){ console.log("submit") setBirdObject64(reader.result); // console.log(reader.result) // console.log(birdObject64,59) } } } }; //image compression function function resize() { let image = new Image() image.src = birdObject64 image.onload= function(){ let canvas = document.createElement("canvas") canvas.width = image.width/1.7 canvas.height = image.height/1.7 const context = canvas.getContext("2d") context.drawImage(image, 0, 0, canvas.width, canvas.height) setBirdObject64(canvas.toDataURL("image/jpeg", 0.8)) // console.log("after") }} //===S3 STUFF=== //UPLOAD FILE function uploadFile(file, signedRequest, url){ const xhr = new XMLHttpRequest(); xhr.open('PUT', signedRequest); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ setImgUrl(url) } else{ return null } } }; xhr.send(file); } //GET SIGNED REQUEST function getSignedRequest(file){ var timestamp = Date.now() console.log(timestamp) const xhr = new XMLHttpRequest(); xhr.open('GET', `/sign-s3?file-name=${timestamp}${file.name}&file-type=${file.type}`); xhr.onreadystatechange = () => { if(xhr.readyState === 4){ if(xhr.status === 200){ const response = JSON.parse(xhr.responseText); uploadFile(file, response.signedRequest, response.url); } else{ console.log("signedinURLfail"); } } }; xhr.send(); } //===END S3 STUFF=== return ( <div className="submissionContainer"> <div className="formContainer"> <form id={"submitForm"} encType="multipart/form-data"> <h4>Save observations</h4> <Input onChange={handleInputChange} name="image" placeholder="Image (required)" type="file" /> <Input onChange={handleCommentsChange} placeholder="Comment" type="textarea" /> <button onClick={handleFormSubmit} > Submit </button> </form> <div className="form__img-input-container"> <img src={src} alt={alt} className="form-img__img-preview"/> </div> <h4 id={"alert"}></h4> </div> <Nav /> </div> ) } // export default SubmitBird; const mapStateToProps = (state) => { return { isSignedIn: state.auth.isSignedIn, userId: state.auth.userId }; }; export default connect(mapStateToProps)(SubmitBird);
export default { title: 'FN Components/Message Toast', parameters: { description: ` `, components: ['fn-message-toast'] } }; const localStyles = ` <style> .docs-fn-container > .fn-message-toast { margin-bottom: 1rem; } </style> `; export const MessageToast = () => `${localStyles} <div class="docs-fn-container"> <div class="fn-message-toast"> <span class="fn-message-toast__text">Operation failed successfully.</span> </div> <div class="fn-message-toast"> <span class="fn-message-toast__text"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </span> </div> <div class="fn-message-toast"> <span class="fn-message-toast__text fn-message-toast__text--truncate"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </span> </div> <div class="fn-message-toast" style="width: 400px;"> <span class="fn-message-toast__text fn-message-toast__text--truncate"> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." </span> </div> </div> `; MessageToast.parameters = { docs: { iframeHeight: 500, description: { story: `To truncate long text apply the \`.fn-message-toast__text--truncate\` modifier class to the \`.fn-message-toast__text\` base class. <br> You can control the width of the Message Toast with inline styling. For example, by adding \` style="width: 400px;"\` to the parent element with class \`.fn-message-toast\`. ` } } };
import React from 'react'; import DocumentTitle from 'react-document-title'; import exposeRouter from '../components/exposerouter.react'; import {focusInvalidField} from '../../lib/validation'; import {getForm} from '../auth/store'; import {msg} from '../intl/store'; import {updateFormField, login} from '../auth/actions'; require('./login.styl'); class Login extends React.Component { onFormSubmit(e) { e.preventDefault(); const fields = getForm().toJS().fields; login(fields) .then(() => { this.redirectAfterLogin(); }) .catch(focusInvalidField(this)); } redirectAfterLogin() { // TODO: Probably use hard reload for Chrome to remember password. // https://code.google.com/p/chromium/issues/detail?id=43219#c56 const nextPath = this.props.router.getCurrentQuery().nextPath; this.props.router.replaceWith(nextPath || '/'); } render() { const form = getForm().toJS(); return ( <DocumentTitle title={msg('auth.title')}> <div className="login"> <form onSubmit={(e) => this.onFormSubmit(e)}> <fieldset> <legend>{msg('auth.form.legend')}</legend> <input autoFocus="true" disabled={login.pending} name="email" onChange={updateFormField} placeholder={msg('auth.form.placeholder.email')} value={form.fields.email} /><br /> <input disabled={login.pending} name="password" onChange={updateFormField} placeholder={msg('auth.form.placeholder.password')} type="password" value={form.fields.password} /><br /> <button disabled={login.pending} type="submit" >{msg('auth.form.button.login')}</button> {/* <button type="submit">{msg('auth.form.button.signup')}</button> */} {form.error && <span className="error-message">{form.error.message}</span> } <div>{msg('auth.form.hint')}</div> </fieldset> </form> </div> </DocumentTitle> ); } } Login.propTypes = { router: React.PropTypes.func }; export default exposeRouter(Login);
!function(e,a){void 0===mejs.plugins&&(mejs.plugins={},mejs.plugins.silverlight=[],mejs.plugins.silverlight.push({types:[]})),mejs.HtmlMediaElementShim=mejs.HtmlMediaElementShim||{getTypeFromFile:mejs.Utils.getTypeFromFile},void 0===mejs.MediaFeatures&&(mejs.MediaFeatures=mejs.Features),void 0===mejs.Utility&&(mejs.Utility=mejs.Utils);var t=MediaElementPlayer.prototype.init;MediaElementPlayer.prototype.init=function(){this.options.classPrefix="mejs-",this.$media=this.$node=a(this.node),t.call(this)};var i=MediaElementPlayer.prototype._meReady;MediaElementPlayer.prototype._meReady=function(){this.container=a(this.container),this.controls=a(this.controls),this.layers=a(this.layers),i.apply(this,arguments)},MediaElementPlayer.prototype.getElement=function(e){return void 0!==a&&e instanceof a?e[0]:e},MediaElementPlayer.prototype.buildfeatures=function(e,t,i,s){for(var r=["playpause","current","progress","duration","tracks","volume","fullscreen"],l=0,n=this.options.features.length;l<n;l++){var o=this.options.features[l];if(this["build"+o])try{-1===r.indexOf(o)?this["build"+o](e,a(t),a(i),s):this["build"+o](e,t,i,s)}catch(e){console.error("error building "+o,e)}}}}(window,jQuery);
export {default} from './GameBoardContainer';
import axios from 'axios'; const getBasePath = () => { return 'http://localhost:5000'; } export const getOrdersStates = async () => { return await axios.get( `${getBasePath()}/status` ).then(function (response) { return response.data; }).catch(function (error) { return error.response.data; }); }
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[0],{ /***/ "./node_modules/cropperjs/dist/cropper.js": /*!************************************************!*\ !*** ./node_modules/cropperjs/dist/cropper.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("/*!\n * Cropper.js v1.5.7\n * https://fengyuanchen.github.io/cropperjs\n *\n * Copyright 2015-present Chen Fengyuan\n * Released under the MIT license\n *\n * Date: 2020-05-23T05:23:00.081Z\n */\n\n(function (global, factory) {\n true ? module.exports = factory() :\n undefined;\n}(this, (function () { 'use strict';\n\n function _typeof(obj) {\n \"@babel/helpers - typeof\";\n\n if (typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\") {\n _typeof = function (obj) {\n return typeof obj;\n };\n } else {\n _typeof = function (obj) {\n return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj;\n };\n }\n\n return _typeof(obj);\n }\n\n function _classCallCheck(instance, Constructor) {\n if (!(instance instanceof Constructor)) {\n throw new TypeError(\"Cannot call a class as a function\");\n }\n }\n\n function _defineProperties(target, props) {\n for (var i = 0; i < props.length; i++) {\n var descriptor = props[i];\n descriptor.enumerable = descriptor.enumerable || false;\n descriptor.configurable = true;\n if (\"value\" in descriptor) descriptor.writable = true;\n Object.defineProperty(target, descriptor.key, descriptor);\n }\n }\n\n function _createClass(Constructor, protoProps, staticProps) {\n if (protoProps) _defineProperties(Constructor.prototype, protoProps);\n if (staticProps) _defineProperties(Constructor, staticProps);\n return Constructor;\n }\n\n function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n }\n\n function ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n if (enumerableOnly) symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n });\n keys.push.apply(keys, symbols);\n }\n\n return keys;\n }\n\n function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n\n if (i % 2) {\n ownKeys(Object(source), true).forEach(function (key) {\n _defineProperty(target, key, source[key]);\n });\n } else if (Object.getOwnPropertyDescriptors) {\n Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));\n } else {\n ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n }\n\n return target;\n }\n\n function _toConsumableArray(arr) {\n return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread();\n }\n\n function _arrayWithoutHoles(arr) {\n if (Array.isArray(arr)) return _arrayLikeToArray(arr);\n }\n\n function _iterableToArray(iter) {\n if (typeof Symbol !== \"undefined\" && Symbol.iterator in Object(iter)) return Array.from(iter);\n }\n\n function _unsupportedIterableToArray(o, minLen) {\n if (!o) return;\n if (typeof o === \"string\") return _arrayLikeToArray(o, minLen);\n var n = Object.prototype.toString.call(o).slice(8, -1);\n if (n === \"Object\" && o.constructor) n = o.constructor.name;\n if (n === \"Map\" || n === \"Set\") return Array.from(o);\n if (n === \"Arguments\" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);\n }\n\n function _arrayLikeToArray(arr, len) {\n if (len == null || len > arr.length) len = arr.length;\n\n for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];\n\n return arr2;\n }\n\n function _nonIterableSpread() {\n throw new TypeError(\"Invalid attempt to spread non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n }\n\n var IS_BROWSER = typeof window !== 'undefined' && typeof window.document !== 'undefined';\n var WINDOW = IS_BROWSER ? window : {};\n var IS_TOUCH_DEVICE = IS_BROWSER && WINDOW.document.documentElement ? 'ontouchstart' in WINDOW.document.documentElement : false;\n var HAS_POINTER_EVENT = IS_BROWSER ? 'PointerEvent' in WINDOW : false;\n var NAMESPACE = 'cropper'; // Actions\n\n var ACTION_ALL = 'all';\n var ACTION_CROP = 'crop';\n var ACTION_MOVE = 'move';\n var ACTION_ZOOM = 'zoom';\n var ACTION_EAST = 'e';\n var ACTION_WEST = 'w';\n var ACTION_SOUTH = 's';\n var ACTION_NORTH = 'n';\n var ACTION_NORTH_EAST = 'ne';\n var ACTION_NORTH_WEST = 'nw';\n var ACTION_SOUTH_EAST = 'se';\n var ACTION_SOUTH_WEST = 'sw'; // Classes\n\n var CLASS_CROP = \"\".concat(NAMESPACE, \"-crop\");\n var CLASS_DISABLED = \"\".concat(NAMESPACE, \"-disabled\");\n var CLASS_HIDDEN = \"\".concat(NAMESPACE, \"-hidden\");\n var CLASS_HIDE = \"\".concat(NAMESPACE, \"-hide\");\n var CLASS_INVISIBLE = \"\".concat(NAMESPACE, \"-invisible\");\n var CLASS_MODAL = \"\".concat(NAMESPACE, \"-modal\");\n var CLASS_MOVE = \"\".concat(NAMESPACE, \"-move\"); // Data keys\n\n var DATA_ACTION = \"\".concat(NAMESPACE, \"Action\");\n var DATA_PREVIEW = \"\".concat(NAMESPACE, \"Preview\"); // Drag modes\n\n var DRAG_MODE_CROP = 'crop';\n var DRAG_MODE_MOVE = 'move';\n var DRAG_MODE_NONE = 'none'; // Events\n\n var EVENT_CROP = 'crop';\n var EVENT_CROP_END = 'cropend';\n var EVENT_CROP_MOVE = 'cropmove';\n var EVENT_CROP_START = 'cropstart';\n var EVENT_DBLCLICK = 'dblclick';\n var EVENT_TOUCH_START = IS_TOUCH_DEVICE ? 'touchstart' : 'mousedown';\n var EVENT_TOUCH_MOVE = IS_TOUCH_DEVICE ? 'touchmove' : 'mousemove';\n var EVENT_TOUCH_END = IS_TOUCH_DEVICE ? 'touchend touchcancel' : 'mouseup';\n var EVENT_POINTER_DOWN = HAS_POINTER_EVENT ? 'pointerdown' : EVENT_TOUCH_START;\n var EVENT_POINTER_MOVE = HAS_POINTER_EVENT ? 'pointermove' : EVENT_TOUCH_MOVE;\n var EVENT_POINTER_UP = HAS_POINTER_EVENT ? 'pointerup pointercancel' : EVENT_TOUCH_END;\n var EVENT_READY = 'ready';\n var EVENT_RESIZE = 'resize';\n var EVENT_WHEEL = 'wheel';\n var EVENT_ZOOM = 'zoom'; // Mime types\n\n var MIME_TYPE_JPEG = 'image/jpeg'; // RegExps\n\n var REGEXP_ACTIONS = /^e|w|s|n|se|sw|ne|nw|all|crop|move|zoom$/;\n var REGEXP_DATA_URL = /^data:/;\n var REGEXP_DATA_URL_JPEG = /^data:image\\/jpeg;base64,/;\n var REGEXP_TAG_NAME = /^img|canvas$/i; // Misc\n\n var DEFAULTS = {\n // Define the view mode of the cropper\n viewMode: 0,\n // 0, 1, 2, 3\n // Define the dragging mode of the cropper\n dragMode: DRAG_MODE_CROP,\n // 'crop', 'move' or 'none'\n // Define the initial aspect ratio of the crop box\n initialAspectRatio: NaN,\n // Define the aspect ratio of the crop box\n aspectRatio: NaN,\n // An object with the previous cropping result data\n data: null,\n // A selector for adding extra containers to preview\n preview: '',\n // Re-render the cropper when resize the window\n responsive: true,\n // Restore the cropped area after resize the window\n restore: true,\n // Check if the current image is a cross-origin image\n checkCrossOrigin: true,\n // Check the current image's Exif Orientation information\n checkOrientation: true,\n // Show the black modal\n modal: true,\n // Show the dashed lines for guiding\n guides: true,\n // Show the center indicator for guiding\n center: true,\n // Show the white modal to highlight the crop box\n highlight: true,\n // Show the grid background\n background: true,\n // Enable to crop the image automatically when initialize\n autoCrop: true,\n // Define the percentage of automatic cropping area when initializes\n autoCropArea: 0.8,\n // Enable to move the image\n movable: true,\n // Enable to rotate the image\n rotatable: true,\n // Enable to scale the image\n scalable: true,\n // Enable to zoom the image\n zoomable: true,\n // Enable to zoom the image by dragging touch\n zoomOnTouch: true,\n // Enable to zoom the image by wheeling mouse\n zoomOnWheel: true,\n // Define zoom ratio when zoom the image by wheeling mouse\n wheelZoomRatio: 0.1,\n // Enable to move the crop box\n cropBoxMovable: true,\n // Enable to resize the crop box\n cropBoxResizable: true,\n // Toggle drag mode between \"crop\" and \"move\" when click twice on the cropper\n toggleDragModeOnDblclick: true,\n // Size limitation\n minCanvasWidth: 0,\n minCanvasHeight: 0,\n minCropBoxWidth: 0,\n minCropBoxHeight: 0,\n minContainerWidth: 200,\n minContainerHeight: 100,\n // Shortcuts of events\n ready: null,\n cropstart: null,\n cropmove: null,\n cropend: null,\n crop: null,\n zoom: null\n };\n\n var TEMPLATE = '<div class=\"cropper-container\" touch-action=\"none\">' + '<div class=\"cropper-wrap-box\">' + '<div class=\"cropper-canvas\"></div>' + '</div>' + '<div class=\"cropper-drag-box\"></div>' + '<div class=\"cropper-crop-box\">' + '<span class=\"cropper-view-box\"></span>' + '<span class=\"cropper-dashed dashed-h\"></span>' + '<span class=\"cropper-dashed dashed-v\"></span>' + '<span class=\"cropper-center\"></span>' + '<span class=\"cropper-face\"></span>' + '<span class=\"cropper-line line-e\" data-cropper-action=\"e\"></span>' + '<span class=\"cropper-line line-n\" data-cropper-action=\"n\"></span>' + '<span class=\"cropper-line line-w\" data-cropper-action=\"w\"></span>' + '<span class=\"cropper-line line-s\" data-cropper-action=\"s\"></span>' + '<span class=\"cropper-point point-e\" data-cropper-action=\"e\"></span>' + '<span class=\"cropper-point point-n\" data-cropper-action=\"n\"></span>' + '<span class=\"cropper-point point-w\" data-cropper-action=\"w\"></span>' + '<span class=\"cropper-point point-s\" data-cropper-action=\"s\"></span>' + '<span class=\"cropper-point point-ne\" data-cropper-action=\"ne\"></span>' + '<span class=\"cropper-point point-nw\" data-cropper-action=\"nw\"></span>' + '<span class=\"cropper-point point-sw\" data-cropper-action=\"sw\"></span>' + '<span class=\"cropper-point point-se\" data-cropper-action=\"se\"></span>' + '</div>' + '</div>';\n\n /**\n * Check if the given value is not a number.\n */\n\n var isNaN = Number.isNaN || WINDOW.isNaN;\n /**\n * Check if the given value is a number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a number, else `false`.\n */\n\n function isNumber(value) {\n return typeof value === 'number' && !isNaN(value);\n }\n /**\n * Check if the given value is a positive number.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a positive number, else `false`.\n */\n\n var isPositiveNumber = function isPositiveNumber(value) {\n return value > 0 && value < Infinity;\n };\n /**\n * Check if the given value is undefined.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is undefined, else `false`.\n */\n\n function isUndefined(value) {\n return typeof value === 'undefined';\n }\n /**\n * Check if the given value is an object.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is an object, else `false`.\n */\n\n function isObject(value) {\n return _typeof(value) === 'object' && value !== null;\n }\n var hasOwnProperty = Object.prototype.hasOwnProperty;\n /**\n * Check if the given value is a plain object.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a plain object, else `false`.\n */\n\n function isPlainObject(value) {\n if (!isObject(value)) {\n return false;\n }\n\n try {\n var _constructor = value.constructor;\n var prototype = _constructor.prototype;\n return _constructor && prototype && hasOwnProperty.call(prototype, 'isPrototypeOf');\n } catch (error) {\n return false;\n }\n }\n /**\n * Check if the given value is a function.\n * @param {*} value - The value to check.\n * @returns {boolean} Returns `true` if the given value is a function, else `false`.\n */\n\n function isFunction(value) {\n return typeof value === 'function';\n }\n var slice = Array.prototype.slice;\n /**\n * Convert array-like or iterable object to an array.\n * @param {*} value - The value to convert.\n * @returns {Array} Returns a new array.\n */\n\n function toArray(value) {\n return Array.from ? Array.from(value) : slice.call(value);\n }\n /**\n * Iterate the given data.\n * @param {*} data - The data to iterate.\n * @param {Function} callback - The process function for each element.\n * @returns {*} The original data.\n */\n\n function forEach(data, callback) {\n if (data && isFunction(callback)) {\n if (Array.isArray(data) || isNumber(data.length)\n /* array-like */\n ) {\n toArray(data).forEach(function (value, key) {\n callback.call(data, value, key, data);\n });\n } else if (isObject(data)) {\n Object.keys(data).forEach(function (key) {\n callback.call(data, data[key], key, data);\n });\n }\n }\n\n return data;\n }\n /**\n * Extend the given object.\n * @param {*} target - The target object to extend.\n * @param {*} args - The rest objects for merging to the target object.\n * @returns {Object} The extended object.\n */\n\n var assign = Object.assign || function assign(target) {\n for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n if (isObject(target) && args.length > 0) {\n args.forEach(function (arg) {\n if (isObject(arg)) {\n Object.keys(arg).forEach(function (key) {\n target[key] = arg[key];\n });\n }\n });\n }\n\n return target;\n };\n var REGEXP_DECIMALS = /\\.\\d*(?:0|9){12}\\d*$/;\n /**\n * Normalize decimal number.\n * Check out {@link https://0.30000000000000004.com/}\n * @param {number} value - The value to normalize.\n * @param {number} [times=100000000000] - The times for normalizing.\n * @returns {number} Returns the normalized number.\n */\n\n function normalizeDecimalNumber(value) {\n var times = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 100000000000;\n return REGEXP_DECIMALS.test(value) ? Math.round(value * times) / times : value;\n }\n var REGEXP_SUFFIX = /^width|height|left|top|marginLeft|marginTop$/;\n /**\n * Apply styles to the given element.\n * @param {Element} element - The target element.\n * @param {Object} styles - The styles for applying.\n */\n\n function setStyle(element, styles) {\n var style = element.style;\n forEach(styles, function (value, property) {\n if (REGEXP_SUFFIX.test(property) && isNumber(value)) {\n value = \"\".concat(value, \"px\");\n }\n\n style[property] = value;\n });\n }\n /**\n * Check if the given element has a special class.\n * @param {Element} element - The element to check.\n * @param {string} value - The class to search.\n * @returns {boolean} Returns `true` if the special class was found.\n */\n\n function hasClass(element, value) {\n return element.classList ? element.classList.contains(value) : element.className.indexOf(value) > -1;\n }\n /**\n * Add classes to the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be added.\n */\n\n function addClass(element, value) {\n if (!value) {\n return;\n }\n\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n addClass(elem, value);\n });\n return;\n }\n\n if (element.classList) {\n element.classList.add(value);\n return;\n }\n\n var className = element.className.trim();\n\n if (!className) {\n element.className = value;\n } else if (className.indexOf(value) < 0) {\n element.className = \"\".concat(className, \" \").concat(value);\n }\n }\n /**\n * Remove classes from the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be removed.\n */\n\n function removeClass(element, value) {\n if (!value) {\n return;\n }\n\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n removeClass(elem, value);\n });\n return;\n }\n\n if (element.classList) {\n element.classList.remove(value);\n return;\n }\n\n if (element.className.indexOf(value) >= 0) {\n element.className = element.className.replace(value, '');\n }\n }\n /**\n * Add or remove classes from the given element.\n * @param {Element} element - The target element.\n * @param {string} value - The classes to be toggled.\n * @param {boolean} added - Add only.\n */\n\n function toggleClass(element, value, added) {\n if (!value) {\n return;\n }\n\n if (isNumber(element.length)) {\n forEach(element, function (elem) {\n toggleClass(elem, value, added);\n });\n return;\n } // IE10-11 doesn't support the second parameter of `classList.toggle`\n\n\n if (added) {\n addClass(element, value);\n } else {\n removeClass(element, value);\n }\n }\n var REGEXP_CAMEL_CASE = /([a-z\\d])([A-Z])/g;\n /**\n * Transform the given string from camelCase to kebab-case\n * @param {string} value - The value to transform.\n * @returns {string} The transformed value.\n */\n\n function toParamCase(value) {\n return value.replace(REGEXP_CAMEL_CASE, '$1-$2').toLowerCase();\n }\n /**\n * Get data from the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to get.\n * @returns {string} The data value.\n */\n\n function getData(element, name) {\n if (isObject(element[name])) {\n return element[name];\n }\n\n if (element.dataset) {\n return element.dataset[name];\n }\n\n return element.getAttribute(\"data-\".concat(toParamCase(name)));\n }\n /**\n * Set data to the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to set.\n * @param {string} data - The data value.\n */\n\n function setData(element, name, data) {\n if (isObject(data)) {\n element[name] = data;\n } else if (element.dataset) {\n element.dataset[name] = data;\n } else {\n element.setAttribute(\"data-\".concat(toParamCase(name)), data);\n }\n }\n /**\n * Remove data from the given element.\n * @param {Element} element - The target element.\n * @param {string} name - The data key to remove.\n */\n\n function removeData(element, name) {\n if (isObject(element[name])) {\n try {\n delete element[name];\n } catch (error) {\n element[name] = undefined;\n }\n } else if (element.dataset) {\n // #128 Safari not allows to delete dataset property\n try {\n delete element.dataset[name];\n } catch (error) {\n element.dataset[name] = undefined;\n }\n } else {\n element.removeAttribute(\"data-\".concat(toParamCase(name)));\n }\n }\n var REGEXP_SPACES = /\\s\\s*/;\n\n var onceSupported = function () {\n var supported = false;\n\n if (IS_BROWSER) {\n var once = false;\n\n var listener = function listener() {};\n\n var options = Object.defineProperty({}, 'once', {\n get: function get() {\n supported = true;\n return once;\n },\n\n /**\n * This setter can fix a `TypeError` in strict mode\n * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Getter_only}\n * @param {boolean} value - The value to set\n */\n set: function set(value) {\n once = value;\n }\n });\n WINDOW.addEventListener('test', listener, options);\n WINDOW.removeEventListener('test', listener, options);\n }\n\n return supported;\n }();\n /**\n * Remove event listener from the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Function} listener - The event listener.\n * @param {Object} options - The event options.\n */\n\n\n function removeListener(element, type, listener) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var handler = listener;\n type.trim().split(REGEXP_SPACES).forEach(function (event) {\n if (!onceSupported) {\n var listeners = element.listeners;\n\n if (listeners && listeners[event] && listeners[event][listener]) {\n handler = listeners[event][listener];\n delete listeners[event][listener];\n\n if (Object.keys(listeners[event]).length === 0) {\n delete listeners[event];\n }\n\n if (Object.keys(listeners).length === 0) {\n delete element.listeners;\n }\n }\n }\n\n element.removeEventListener(event, handler, options);\n });\n }\n /**\n * Add event listener to the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Function} listener - The event listener.\n * @param {Object} options - The event options.\n */\n\n function addListener(element, type, listener) {\n var options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};\n var _handler = listener;\n type.trim().split(REGEXP_SPACES).forEach(function (event) {\n if (options.once && !onceSupported) {\n var _element$listeners = element.listeners,\n listeners = _element$listeners === void 0 ? {} : _element$listeners;\n\n _handler = function handler() {\n delete listeners[event][listener];\n element.removeEventListener(event, _handler, options);\n\n for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n listener.apply(element, args);\n };\n\n if (!listeners[event]) {\n listeners[event] = {};\n }\n\n if (listeners[event][listener]) {\n element.removeEventListener(event, listeners[event][listener], options);\n }\n\n listeners[event][listener] = _handler;\n element.listeners = listeners;\n }\n\n element.addEventListener(event, _handler, options);\n });\n }\n /**\n * Dispatch event on the target element.\n * @param {Element} element - The event target.\n * @param {string} type - The event type(s).\n * @param {Object} data - The additional event data.\n * @returns {boolean} Indicate if the event is default prevented or not.\n */\n\n function dispatchEvent(element, type, data) {\n var event; // Event and CustomEvent on IE9-11 are global objects, not constructors\n\n if (isFunction(Event) && isFunction(CustomEvent)) {\n event = new CustomEvent(type, {\n detail: data,\n bubbles: true,\n cancelable: true\n });\n } else {\n event = document.createEvent('CustomEvent');\n event.initCustomEvent(type, true, true, data);\n }\n\n return element.dispatchEvent(event);\n }\n /**\n * Get the offset base on the document.\n * @param {Element} element - The target element.\n * @returns {Object} The offset data.\n */\n\n function getOffset(element) {\n var box = element.getBoundingClientRect();\n return {\n left: box.left + (window.pageXOffset - document.documentElement.clientLeft),\n top: box.top + (window.pageYOffset - document.documentElement.clientTop)\n };\n }\n var location = WINDOW.location;\n var REGEXP_ORIGINS = /^(\\w+:)\\/\\/([^:/?#]*):?(\\d*)/i;\n /**\n * Check if the given URL is a cross origin URL.\n * @param {string} url - The target URL.\n * @returns {boolean} Returns `true` if the given URL is a cross origin URL, else `false`.\n */\n\n function isCrossOriginURL(url) {\n var parts = url.match(REGEXP_ORIGINS);\n return parts !== null && (parts[1] !== location.protocol || parts[2] !== location.hostname || parts[3] !== location.port);\n }\n /**\n * Add timestamp to the given URL.\n * @param {string} url - The target URL.\n * @returns {string} The result URL.\n */\n\n function addTimestamp(url) {\n var timestamp = \"timestamp=\".concat(new Date().getTime());\n return url + (url.indexOf('?') === -1 ? '?' : '&') + timestamp;\n }\n /**\n * Get transforms base on the given object.\n * @param {Object} obj - The target object.\n * @returns {string} A string contains transform values.\n */\n\n function getTransforms(_ref) {\n var rotate = _ref.rotate,\n scaleX = _ref.scaleX,\n scaleY = _ref.scaleY,\n translateX = _ref.translateX,\n translateY = _ref.translateY;\n var values = [];\n\n if (isNumber(translateX) && translateX !== 0) {\n values.push(\"translateX(\".concat(translateX, \"px)\"));\n }\n\n if (isNumber(translateY) && translateY !== 0) {\n values.push(\"translateY(\".concat(translateY, \"px)\"));\n } // Rotate should come first before scale to match orientation transform\n\n\n if (isNumber(rotate) && rotate !== 0) {\n values.push(\"rotate(\".concat(rotate, \"deg)\"));\n }\n\n if (isNumber(scaleX) && scaleX !== 1) {\n values.push(\"scaleX(\".concat(scaleX, \")\"));\n }\n\n if (isNumber(scaleY) && scaleY !== 1) {\n values.push(\"scaleY(\".concat(scaleY, \")\"));\n }\n\n var transform = values.length ? values.join(' ') : 'none';\n return {\n WebkitTransform: transform,\n msTransform: transform,\n transform: transform\n };\n }\n /**\n * Get the max ratio of a group of pointers.\n * @param {string} pointers - The target pointers.\n * @returns {number} The result ratio.\n */\n\n function getMaxZoomRatio(pointers) {\n var pointers2 = _objectSpread2({}, pointers);\n\n var ratios = [];\n forEach(pointers, function (pointer, pointerId) {\n delete pointers2[pointerId];\n forEach(pointers2, function (pointer2) {\n var x1 = Math.abs(pointer.startX - pointer2.startX);\n var y1 = Math.abs(pointer.startY - pointer2.startY);\n var x2 = Math.abs(pointer.endX - pointer2.endX);\n var y2 = Math.abs(pointer.endY - pointer2.endY);\n var z1 = Math.sqrt(x1 * x1 + y1 * y1);\n var z2 = Math.sqrt(x2 * x2 + y2 * y2);\n var ratio = (z2 - z1) / z1;\n ratios.push(ratio);\n });\n });\n ratios.sort(function (a, b) {\n return Math.abs(a) < Math.abs(b);\n });\n return ratios[0];\n }\n /**\n * Get a pointer from an event object.\n * @param {Object} event - The target event object.\n * @param {boolean} endOnly - Indicates if only returns the end point coordinate or not.\n * @returns {Object} The result pointer contains start and/or end point coordinates.\n */\n\n function getPointer(_ref2, endOnly) {\n var pageX = _ref2.pageX,\n pageY = _ref2.pageY;\n var end = {\n endX: pageX,\n endY: pageY\n };\n return endOnly ? end : _objectSpread2({\n startX: pageX,\n startY: pageY\n }, end);\n }\n /**\n * Get the center point coordinate of a group of pointers.\n * @param {Object} pointers - The target pointers.\n * @returns {Object} The center point coordinate.\n */\n\n function getPointersCenter(pointers) {\n var pageX = 0;\n var pageY = 0;\n var count = 0;\n forEach(pointers, function (_ref3) {\n var startX = _ref3.startX,\n startY = _ref3.startY;\n pageX += startX;\n pageY += startY;\n count += 1;\n });\n pageX /= count;\n pageY /= count;\n return {\n pageX: pageX,\n pageY: pageY\n };\n }\n /**\n * Get the max sizes in a rectangle under the given aspect ratio.\n * @param {Object} data - The original sizes.\n * @param {string} [type='contain'] - The adjust type.\n * @returns {Object} The result sizes.\n */\n\n function getAdjustedSizes(_ref4) // or 'cover'\n {\n var aspectRatio = _ref4.aspectRatio,\n height = _ref4.height,\n width = _ref4.width;\n var type = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'contain';\n var isValidWidth = isPositiveNumber(width);\n var isValidHeight = isPositiveNumber(height);\n\n if (isValidWidth && isValidHeight) {\n var adjustedWidth = height * aspectRatio;\n\n if (type === 'contain' && adjustedWidth > width || type === 'cover' && adjustedWidth < width) {\n height = width / aspectRatio;\n } else {\n width = height * aspectRatio;\n }\n } else if (isValidWidth) {\n height = width / aspectRatio;\n } else if (isValidHeight) {\n width = height * aspectRatio;\n }\n\n return {\n width: width,\n height: height\n };\n }\n /**\n * Get the new sizes of a rectangle after rotated.\n * @param {Object} data - The original sizes.\n * @returns {Object} The result sizes.\n */\n\n function getRotatedSizes(_ref5) {\n var width = _ref5.width,\n height = _ref5.height,\n degree = _ref5.degree;\n degree = Math.abs(degree) % 180;\n\n if (degree === 90) {\n return {\n width: height,\n height: width\n };\n }\n\n var arc = degree % 90 * Math.PI / 180;\n var sinArc = Math.sin(arc);\n var cosArc = Math.cos(arc);\n var newWidth = width * cosArc + height * sinArc;\n var newHeight = width * sinArc + height * cosArc;\n return degree > 90 ? {\n width: newHeight,\n height: newWidth\n } : {\n width: newWidth,\n height: newHeight\n };\n }\n /**\n * Get a canvas which drew the given image.\n * @param {HTMLImageElement} image - The image for drawing.\n * @param {Object} imageData - The image data.\n * @param {Object} canvasData - The canvas data.\n * @param {Object} options - The options.\n * @returns {HTMLCanvasElement} The result canvas.\n */\n\n function getSourceCanvas(image, _ref6, _ref7, _ref8) {\n var imageAspectRatio = _ref6.aspectRatio,\n imageNaturalWidth = _ref6.naturalWidth,\n imageNaturalHeight = _ref6.naturalHeight,\n _ref6$rotate = _ref6.rotate,\n rotate = _ref6$rotate === void 0 ? 0 : _ref6$rotate,\n _ref6$scaleX = _ref6.scaleX,\n scaleX = _ref6$scaleX === void 0 ? 1 : _ref6$scaleX,\n _ref6$scaleY = _ref6.scaleY,\n scaleY = _ref6$scaleY === void 0 ? 1 : _ref6$scaleY;\n var aspectRatio = _ref7.aspectRatio,\n naturalWidth = _ref7.naturalWidth,\n naturalHeight = _ref7.naturalHeight;\n var _ref8$fillColor = _ref8.fillColor,\n fillColor = _ref8$fillColor === void 0 ? 'transparent' : _ref8$fillColor,\n _ref8$imageSmoothingE = _ref8.imageSmoothingEnabled,\n imageSmoothingEnabled = _ref8$imageSmoothingE === void 0 ? true : _ref8$imageSmoothingE,\n _ref8$imageSmoothingQ = _ref8.imageSmoothingQuality,\n imageSmoothingQuality = _ref8$imageSmoothingQ === void 0 ? 'low' : _ref8$imageSmoothingQ,\n _ref8$maxWidth = _ref8.maxWidth,\n maxWidth = _ref8$maxWidth === void 0 ? Infinity : _ref8$maxWidth,\n _ref8$maxHeight = _ref8.maxHeight,\n maxHeight = _ref8$maxHeight === void 0 ? Infinity : _ref8$maxHeight,\n _ref8$minWidth = _ref8.minWidth,\n minWidth = _ref8$minWidth === void 0 ? 0 : _ref8$minWidth,\n _ref8$minHeight = _ref8.minHeight,\n minHeight = _ref8$minHeight === void 0 ? 0 : _ref8$minHeight;\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n var maxSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: maxWidth,\n height: maxHeight\n });\n var minSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: minWidth,\n height: minHeight\n }, 'cover');\n var width = Math.min(maxSizes.width, Math.max(minSizes.width, naturalWidth));\n var height = Math.min(maxSizes.height, Math.max(minSizes.height, naturalHeight)); // Note: should always use image's natural sizes for drawing as\n // imageData.naturalWidth === canvasData.naturalHeight when rotate % 180 === 90\n\n var destMaxSizes = getAdjustedSizes({\n aspectRatio: imageAspectRatio,\n width: maxWidth,\n height: maxHeight\n });\n var destMinSizes = getAdjustedSizes({\n aspectRatio: imageAspectRatio,\n width: minWidth,\n height: minHeight\n }, 'cover');\n var destWidth = Math.min(destMaxSizes.width, Math.max(destMinSizes.width, imageNaturalWidth));\n var destHeight = Math.min(destMaxSizes.height, Math.max(destMinSizes.height, imageNaturalHeight));\n var params = [-destWidth / 2, -destHeight / 2, destWidth, destHeight];\n canvas.width = normalizeDecimalNumber(width);\n canvas.height = normalizeDecimalNumber(height);\n context.fillStyle = fillColor;\n context.fillRect(0, 0, width, height);\n context.save();\n context.translate(width / 2, height / 2);\n context.rotate(rotate * Math.PI / 180);\n context.scale(scaleX, scaleY);\n context.imageSmoothingEnabled = imageSmoothingEnabled;\n context.imageSmoothingQuality = imageSmoothingQuality;\n context.drawImage.apply(context, [image].concat(_toConsumableArray(params.map(function (param) {\n return Math.floor(normalizeDecimalNumber(param));\n }))));\n context.restore();\n return canvas;\n }\n var fromCharCode = String.fromCharCode;\n /**\n * Get string from char code in data view.\n * @param {DataView} dataView - The data view for read.\n * @param {number} start - The start index.\n * @param {number} length - The read length.\n * @returns {string} The read result.\n */\n\n function getStringFromCharCode(dataView, start, length) {\n var str = '';\n length += start;\n\n for (var i = start; i < length; i += 1) {\n str += fromCharCode(dataView.getUint8(i));\n }\n\n return str;\n }\n var REGEXP_DATA_URL_HEAD = /^data:.*,/;\n /**\n * Transform Data URL to array buffer.\n * @param {string} dataURL - The Data URL to transform.\n * @returns {ArrayBuffer} The result array buffer.\n */\n\n function dataURLToArrayBuffer(dataURL) {\n var base64 = dataURL.replace(REGEXP_DATA_URL_HEAD, '');\n var binary = atob(base64);\n var arrayBuffer = new ArrayBuffer(binary.length);\n var uint8 = new Uint8Array(arrayBuffer);\n forEach(uint8, function (value, i) {\n uint8[i] = binary.charCodeAt(i);\n });\n return arrayBuffer;\n }\n /**\n * Transform array buffer to Data URL.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to transform.\n * @param {string} mimeType - The mime type of the Data URL.\n * @returns {string} The result Data URL.\n */\n\n function arrayBufferToDataURL(arrayBuffer, mimeType) {\n var chunks = []; // Chunk Typed Array for better performance (#435)\n\n var chunkSize = 8192;\n var uint8 = new Uint8Array(arrayBuffer);\n\n while (uint8.length > 0) {\n // XXX: Babel's `toConsumableArray` helper will throw error in IE or Safari 9\n // eslint-disable-next-line prefer-spread\n chunks.push(fromCharCode.apply(null, toArray(uint8.subarray(0, chunkSize))));\n uint8 = uint8.subarray(chunkSize);\n }\n\n return \"data:\".concat(mimeType, \";base64,\").concat(btoa(chunks.join('')));\n }\n /**\n * Get orientation value from given array buffer.\n * @param {ArrayBuffer} arrayBuffer - The array buffer to read.\n * @returns {number} The read orientation value.\n */\n\n function resetAndGetOrientation(arrayBuffer) {\n var dataView = new DataView(arrayBuffer);\n var orientation; // Ignores range error when the image does not have correct Exif information\n\n try {\n var littleEndian;\n var app1Start;\n var ifdStart; // Only handle JPEG image (start by 0xFFD8)\n\n if (dataView.getUint8(0) === 0xFF && dataView.getUint8(1) === 0xD8) {\n var length = dataView.byteLength;\n var offset = 2;\n\n while (offset + 1 < length) {\n if (dataView.getUint8(offset) === 0xFF && dataView.getUint8(offset + 1) === 0xE1) {\n app1Start = offset;\n break;\n }\n\n offset += 1;\n }\n }\n\n if (app1Start) {\n var exifIDCode = app1Start + 4;\n var tiffOffset = app1Start + 10;\n\n if (getStringFromCharCode(dataView, exifIDCode, 4) === 'Exif') {\n var endianness = dataView.getUint16(tiffOffset);\n littleEndian = endianness === 0x4949;\n\n if (littleEndian || endianness === 0x4D4D\n /* bigEndian */\n ) {\n if (dataView.getUint16(tiffOffset + 2, littleEndian) === 0x002A) {\n var firstIFDOffset = dataView.getUint32(tiffOffset + 4, littleEndian);\n\n if (firstIFDOffset >= 0x00000008) {\n ifdStart = tiffOffset + firstIFDOffset;\n }\n }\n }\n }\n }\n\n if (ifdStart) {\n var _length = dataView.getUint16(ifdStart, littleEndian);\n\n var _offset;\n\n var i;\n\n for (i = 0; i < _length; i += 1) {\n _offset = ifdStart + i * 12 + 2;\n\n if (dataView.getUint16(_offset, littleEndian) === 0x0112\n /* Orientation */\n ) {\n // 8 is the offset of the current tag's value\n _offset += 8; // Get the original orientation value\n\n orientation = dataView.getUint16(_offset, littleEndian); // Override the orientation with its default value\n\n dataView.setUint16(_offset, 1, littleEndian);\n break;\n }\n }\n }\n } catch (error) {\n orientation = 1;\n }\n\n return orientation;\n }\n /**\n * Parse Exif Orientation value.\n * @param {number} orientation - The orientation to parse.\n * @returns {Object} The parsed result.\n */\n\n function parseOrientation(orientation) {\n var rotate = 0;\n var scaleX = 1;\n var scaleY = 1;\n\n switch (orientation) {\n // Flip horizontal\n case 2:\n scaleX = -1;\n break;\n // Rotate left 180°\n\n case 3:\n rotate = -180;\n break;\n // Flip vertical\n\n case 4:\n scaleY = -1;\n break;\n // Flip vertical and rotate right 90°\n\n case 5:\n rotate = 90;\n scaleY = -1;\n break;\n // Rotate right 90°\n\n case 6:\n rotate = 90;\n break;\n // Flip horizontal and rotate right 90°\n\n case 7:\n rotate = 90;\n scaleX = -1;\n break;\n // Rotate left 90°\n\n case 8:\n rotate = -90;\n break;\n }\n\n return {\n rotate: rotate,\n scaleX: scaleX,\n scaleY: scaleY\n };\n }\n\n var render = {\n render: function render() {\n this.initContainer();\n this.initCanvas();\n this.initCropBox();\n this.renderCanvas();\n\n if (this.cropped) {\n this.renderCropBox();\n }\n },\n initContainer: function initContainer() {\n var element = this.element,\n options = this.options,\n container = this.container,\n cropper = this.cropper;\n addClass(cropper, CLASS_HIDDEN);\n removeClass(element, CLASS_HIDDEN);\n var containerData = {\n width: Math.max(container.offsetWidth, Number(options.minContainerWidth) || 200),\n height: Math.max(container.offsetHeight, Number(options.minContainerHeight) || 100)\n };\n this.containerData = containerData;\n setStyle(cropper, {\n width: containerData.width,\n height: containerData.height\n });\n addClass(element, CLASS_HIDDEN);\n removeClass(cropper, CLASS_HIDDEN);\n },\n // Canvas (image wrapper)\n initCanvas: function initCanvas() {\n var containerData = this.containerData,\n imageData = this.imageData;\n var viewMode = this.options.viewMode;\n var rotated = Math.abs(imageData.rotate) % 180 === 90;\n var naturalWidth = rotated ? imageData.naturalHeight : imageData.naturalWidth;\n var naturalHeight = rotated ? imageData.naturalWidth : imageData.naturalHeight;\n var aspectRatio = naturalWidth / naturalHeight;\n var canvasWidth = containerData.width;\n var canvasHeight = containerData.height;\n\n if (containerData.height * aspectRatio > containerData.width) {\n if (viewMode === 3) {\n canvasWidth = containerData.height * aspectRatio;\n } else {\n canvasHeight = containerData.width / aspectRatio;\n }\n } else if (viewMode === 3) {\n canvasHeight = containerData.width / aspectRatio;\n } else {\n canvasWidth = containerData.height * aspectRatio;\n }\n\n var canvasData = {\n aspectRatio: aspectRatio,\n naturalWidth: naturalWidth,\n naturalHeight: naturalHeight,\n width: canvasWidth,\n height: canvasHeight\n };\n canvasData.left = (containerData.width - canvasWidth) / 2;\n canvasData.top = (containerData.height - canvasHeight) / 2;\n canvasData.oldLeft = canvasData.left;\n canvasData.oldTop = canvasData.top;\n this.canvasData = canvasData;\n this.limited = viewMode === 1 || viewMode === 2;\n this.limitCanvas(true, true);\n this.initialImageData = assign({}, imageData);\n this.initialCanvasData = assign({}, canvasData);\n },\n limitCanvas: function limitCanvas(sizeLimited, positionLimited) {\n var options = this.options,\n containerData = this.containerData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var viewMode = options.viewMode;\n var aspectRatio = canvasData.aspectRatio;\n var cropped = this.cropped && cropBoxData;\n\n if (sizeLimited) {\n var minCanvasWidth = Number(options.minCanvasWidth) || 0;\n var minCanvasHeight = Number(options.minCanvasHeight) || 0;\n\n if (viewMode > 1) {\n minCanvasWidth = Math.max(minCanvasWidth, containerData.width);\n minCanvasHeight = Math.max(minCanvasHeight, containerData.height);\n\n if (viewMode === 3) {\n if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n minCanvasWidth = minCanvasHeight * aspectRatio;\n } else {\n minCanvasHeight = minCanvasWidth / aspectRatio;\n }\n }\n } else if (viewMode > 0) {\n if (minCanvasWidth) {\n minCanvasWidth = Math.max(minCanvasWidth, cropped ? cropBoxData.width : 0);\n } else if (minCanvasHeight) {\n minCanvasHeight = Math.max(minCanvasHeight, cropped ? cropBoxData.height : 0);\n } else if (cropped) {\n minCanvasWidth = cropBoxData.width;\n minCanvasHeight = cropBoxData.height;\n\n if (minCanvasHeight * aspectRatio > minCanvasWidth) {\n minCanvasWidth = minCanvasHeight * aspectRatio;\n } else {\n minCanvasHeight = minCanvasWidth / aspectRatio;\n }\n }\n }\n\n var _getAdjustedSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: minCanvasWidth,\n height: minCanvasHeight\n });\n\n minCanvasWidth = _getAdjustedSizes.width;\n minCanvasHeight = _getAdjustedSizes.height;\n canvasData.minWidth = minCanvasWidth;\n canvasData.minHeight = minCanvasHeight;\n canvasData.maxWidth = Infinity;\n canvasData.maxHeight = Infinity;\n }\n\n if (positionLimited) {\n if (viewMode > (cropped ? 0 : 1)) {\n var newCanvasLeft = containerData.width - canvasData.width;\n var newCanvasTop = containerData.height - canvasData.height;\n canvasData.minLeft = Math.min(0, newCanvasLeft);\n canvasData.minTop = Math.min(0, newCanvasTop);\n canvasData.maxLeft = Math.max(0, newCanvasLeft);\n canvasData.maxTop = Math.max(0, newCanvasTop);\n\n if (cropped && this.limited) {\n canvasData.minLeft = Math.min(cropBoxData.left, cropBoxData.left + (cropBoxData.width - canvasData.width));\n canvasData.minTop = Math.min(cropBoxData.top, cropBoxData.top + (cropBoxData.height - canvasData.height));\n canvasData.maxLeft = cropBoxData.left;\n canvasData.maxTop = cropBoxData.top;\n\n if (viewMode === 2) {\n if (canvasData.width >= containerData.width) {\n canvasData.minLeft = Math.min(0, newCanvasLeft);\n canvasData.maxLeft = Math.max(0, newCanvasLeft);\n }\n\n if (canvasData.height >= containerData.height) {\n canvasData.minTop = Math.min(0, newCanvasTop);\n canvasData.maxTop = Math.max(0, newCanvasTop);\n }\n }\n }\n } else {\n canvasData.minLeft = -canvasData.width;\n canvasData.minTop = -canvasData.height;\n canvasData.maxLeft = containerData.width;\n canvasData.maxTop = containerData.height;\n }\n }\n },\n renderCanvas: function renderCanvas(changed, transformed) {\n var canvasData = this.canvasData,\n imageData = this.imageData;\n\n if (transformed) {\n var _getRotatedSizes = getRotatedSizes({\n width: imageData.naturalWidth * Math.abs(imageData.scaleX || 1),\n height: imageData.naturalHeight * Math.abs(imageData.scaleY || 1),\n degree: imageData.rotate || 0\n }),\n naturalWidth = _getRotatedSizes.width,\n naturalHeight = _getRotatedSizes.height;\n\n var width = canvasData.width * (naturalWidth / canvasData.naturalWidth);\n var height = canvasData.height * (naturalHeight / canvasData.naturalHeight);\n canvasData.left -= (width - canvasData.width) / 2;\n canvasData.top -= (height - canvasData.height) / 2;\n canvasData.width = width;\n canvasData.height = height;\n canvasData.aspectRatio = naturalWidth / naturalHeight;\n canvasData.naturalWidth = naturalWidth;\n canvasData.naturalHeight = naturalHeight;\n this.limitCanvas(true, false);\n }\n\n if (canvasData.width > canvasData.maxWidth || canvasData.width < canvasData.minWidth) {\n canvasData.left = canvasData.oldLeft;\n }\n\n if (canvasData.height > canvasData.maxHeight || canvasData.height < canvasData.minHeight) {\n canvasData.top = canvasData.oldTop;\n }\n\n canvasData.width = Math.min(Math.max(canvasData.width, canvasData.minWidth), canvasData.maxWidth);\n canvasData.height = Math.min(Math.max(canvasData.height, canvasData.minHeight), canvasData.maxHeight);\n this.limitCanvas(false, true);\n canvasData.left = Math.min(Math.max(canvasData.left, canvasData.minLeft), canvasData.maxLeft);\n canvasData.top = Math.min(Math.max(canvasData.top, canvasData.minTop), canvasData.maxTop);\n canvasData.oldLeft = canvasData.left;\n canvasData.oldTop = canvasData.top;\n setStyle(this.canvas, assign({\n width: canvasData.width,\n height: canvasData.height\n }, getTransforms({\n translateX: canvasData.left,\n translateY: canvasData.top\n })));\n this.renderImage(changed);\n\n if (this.cropped && this.limited) {\n this.limitCropBox(true, true);\n }\n },\n renderImage: function renderImage(changed) {\n var canvasData = this.canvasData,\n imageData = this.imageData;\n var width = imageData.naturalWidth * (canvasData.width / canvasData.naturalWidth);\n var height = imageData.naturalHeight * (canvasData.height / canvasData.naturalHeight);\n assign(imageData, {\n width: width,\n height: height,\n left: (canvasData.width - width) / 2,\n top: (canvasData.height - height) / 2\n });\n setStyle(this.image, assign({\n width: imageData.width,\n height: imageData.height\n }, getTransforms(assign({\n translateX: imageData.left,\n translateY: imageData.top\n }, imageData))));\n\n if (changed) {\n this.output();\n }\n },\n initCropBox: function initCropBox() {\n var options = this.options,\n canvasData = this.canvasData;\n var aspectRatio = options.aspectRatio || options.initialAspectRatio;\n var autoCropArea = Number(options.autoCropArea) || 0.8;\n var cropBoxData = {\n width: canvasData.width,\n height: canvasData.height\n };\n\n if (aspectRatio) {\n if (canvasData.height * aspectRatio > canvasData.width) {\n cropBoxData.height = cropBoxData.width / aspectRatio;\n } else {\n cropBoxData.width = cropBoxData.height * aspectRatio;\n }\n }\n\n this.cropBoxData = cropBoxData;\n this.limitCropBox(true, true); // Initialize auto crop area\n\n cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight); // The width/height of auto crop area must large than \"minWidth/Height\"\n\n cropBoxData.width = Math.max(cropBoxData.minWidth, cropBoxData.width * autoCropArea);\n cropBoxData.height = Math.max(cropBoxData.minHeight, cropBoxData.height * autoCropArea);\n cropBoxData.left = canvasData.left + (canvasData.width - cropBoxData.width) / 2;\n cropBoxData.top = canvasData.top + (canvasData.height - cropBoxData.height) / 2;\n cropBoxData.oldLeft = cropBoxData.left;\n cropBoxData.oldTop = cropBoxData.top;\n this.initialCropBoxData = assign({}, cropBoxData);\n },\n limitCropBox: function limitCropBox(sizeLimited, positionLimited) {\n var options = this.options,\n containerData = this.containerData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData,\n limited = this.limited;\n var aspectRatio = options.aspectRatio;\n\n if (sizeLimited) {\n var minCropBoxWidth = Number(options.minCropBoxWidth) || 0;\n var minCropBoxHeight = Number(options.minCropBoxHeight) || 0;\n var maxCropBoxWidth = limited ? Math.min(containerData.width, canvasData.width, canvasData.width + canvasData.left, containerData.width - canvasData.left) : containerData.width;\n var maxCropBoxHeight = limited ? Math.min(containerData.height, canvasData.height, canvasData.height + canvasData.top, containerData.height - canvasData.top) : containerData.height; // The min/maxCropBoxWidth/Height must be less than container's width/height\n\n minCropBoxWidth = Math.min(minCropBoxWidth, containerData.width);\n minCropBoxHeight = Math.min(minCropBoxHeight, containerData.height);\n\n if (aspectRatio) {\n if (minCropBoxWidth && minCropBoxHeight) {\n if (minCropBoxHeight * aspectRatio > minCropBoxWidth) {\n minCropBoxHeight = minCropBoxWidth / aspectRatio;\n } else {\n minCropBoxWidth = minCropBoxHeight * aspectRatio;\n }\n } else if (minCropBoxWidth) {\n minCropBoxHeight = minCropBoxWidth / aspectRatio;\n } else if (minCropBoxHeight) {\n minCropBoxWidth = minCropBoxHeight * aspectRatio;\n }\n\n if (maxCropBoxHeight * aspectRatio > maxCropBoxWidth) {\n maxCropBoxHeight = maxCropBoxWidth / aspectRatio;\n } else {\n maxCropBoxWidth = maxCropBoxHeight * aspectRatio;\n }\n } // The minWidth/Height must be less than maxWidth/Height\n\n\n cropBoxData.minWidth = Math.min(minCropBoxWidth, maxCropBoxWidth);\n cropBoxData.minHeight = Math.min(minCropBoxHeight, maxCropBoxHeight);\n cropBoxData.maxWidth = maxCropBoxWidth;\n cropBoxData.maxHeight = maxCropBoxHeight;\n }\n\n if (positionLimited) {\n if (limited) {\n cropBoxData.minLeft = Math.max(0, canvasData.left);\n cropBoxData.minTop = Math.max(0, canvasData.top);\n cropBoxData.maxLeft = Math.min(containerData.width, canvasData.left + canvasData.width) - cropBoxData.width;\n cropBoxData.maxTop = Math.min(containerData.height, canvasData.top + canvasData.height) - cropBoxData.height;\n } else {\n cropBoxData.minLeft = 0;\n cropBoxData.minTop = 0;\n cropBoxData.maxLeft = containerData.width - cropBoxData.width;\n cropBoxData.maxTop = containerData.height - cropBoxData.height;\n }\n }\n },\n renderCropBox: function renderCropBox() {\n var options = this.options,\n containerData = this.containerData,\n cropBoxData = this.cropBoxData;\n\n if (cropBoxData.width > cropBoxData.maxWidth || cropBoxData.width < cropBoxData.minWidth) {\n cropBoxData.left = cropBoxData.oldLeft;\n }\n\n if (cropBoxData.height > cropBoxData.maxHeight || cropBoxData.height < cropBoxData.minHeight) {\n cropBoxData.top = cropBoxData.oldTop;\n }\n\n cropBoxData.width = Math.min(Math.max(cropBoxData.width, cropBoxData.minWidth), cropBoxData.maxWidth);\n cropBoxData.height = Math.min(Math.max(cropBoxData.height, cropBoxData.minHeight), cropBoxData.maxHeight);\n this.limitCropBox(false, true);\n cropBoxData.left = Math.min(Math.max(cropBoxData.left, cropBoxData.minLeft), cropBoxData.maxLeft);\n cropBoxData.top = Math.min(Math.max(cropBoxData.top, cropBoxData.minTop), cropBoxData.maxTop);\n cropBoxData.oldLeft = cropBoxData.left;\n cropBoxData.oldTop = cropBoxData.top;\n\n if (options.movable && options.cropBoxMovable) {\n // Turn to move the canvas when the crop box is equal to the container\n setData(this.face, DATA_ACTION, cropBoxData.width >= containerData.width && cropBoxData.height >= containerData.height ? ACTION_MOVE : ACTION_ALL);\n }\n\n setStyle(this.cropBox, assign({\n width: cropBoxData.width,\n height: cropBoxData.height\n }, getTransforms({\n translateX: cropBoxData.left,\n translateY: cropBoxData.top\n })));\n\n if (this.cropped && this.limited) {\n this.limitCanvas(true, true);\n }\n\n if (!this.disabled) {\n this.output();\n }\n },\n output: function output() {\n this.preview();\n dispatchEvent(this.element, EVENT_CROP, this.getData());\n }\n };\n\n var preview = {\n initPreview: function initPreview() {\n var element = this.element,\n crossOrigin = this.crossOrigin;\n var preview = this.options.preview;\n var url = crossOrigin ? this.crossOriginUrl : this.url;\n var alt = element.alt || 'The image to preview';\n var image = document.createElement('img');\n\n if (crossOrigin) {\n image.crossOrigin = crossOrigin;\n }\n\n image.src = url;\n image.alt = alt;\n this.viewBox.appendChild(image);\n this.viewBoxImage = image;\n\n if (!preview) {\n return;\n }\n\n var previews = preview;\n\n if (typeof preview === 'string') {\n previews = element.ownerDocument.querySelectorAll(preview);\n } else if (preview.querySelector) {\n previews = [preview];\n }\n\n this.previews = previews;\n forEach(previews, function (el) {\n var img = document.createElement('img'); // Save the original size for recover\n\n setData(el, DATA_PREVIEW, {\n width: el.offsetWidth,\n height: el.offsetHeight,\n html: el.innerHTML\n });\n\n if (crossOrigin) {\n img.crossOrigin = crossOrigin;\n }\n\n img.src = url;\n img.alt = alt;\n /**\n * Override img element styles\n * Add `display:block` to avoid margin top issue\n * Add `height:auto` to override `height` attribute on IE8\n * (Occur only when margin-top <= -height)\n */\n\n img.style.cssText = 'display:block;' + 'width:100%;' + 'height:auto;' + 'min-width:0!important;' + 'min-height:0!important;' + 'max-width:none!important;' + 'max-height:none!important;' + 'image-orientation:0deg!important;\"';\n el.innerHTML = '';\n el.appendChild(img);\n });\n },\n resetPreview: function resetPreview() {\n forEach(this.previews, function (element) {\n var data = getData(element, DATA_PREVIEW);\n setStyle(element, {\n width: data.width,\n height: data.height\n });\n element.innerHTML = data.html;\n removeData(element, DATA_PREVIEW);\n });\n },\n preview: function preview() {\n var imageData = this.imageData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var cropBoxWidth = cropBoxData.width,\n cropBoxHeight = cropBoxData.height;\n var width = imageData.width,\n height = imageData.height;\n var left = cropBoxData.left - canvasData.left - imageData.left;\n var top = cropBoxData.top - canvasData.top - imageData.top;\n\n if (!this.cropped || this.disabled) {\n return;\n }\n\n setStyle(this.viewBoxImage, assign({\n width: width,\n height: height\n }, getTransforms(assign({\n translateX: -left,\n translateY: -top\n }, imageData))));\n forEach(this.previews, function (element) {\n var data = getData(element, DATA_PREVIEW);\n var originalWidth = data.width;\n var originalHeight = data.height;\n var newWidth = originalWidth;\n var newHeight = originalHeight;\n var ratio = 1;\n\n if (cropBoxWidth) {\n ratio = originalWidth / cropBoxWidth;\n newHeight = cropBoxHeight * ratio;\n }\n\n if (cropBoxHeight && newHeight > originalHeight) {\n ratio = originalHeight / cropBoxHeight;\n newWidth = cropBoxWidth * ratio;\n newHeight = originalHeight;\n }\n\n setStyle(element, {\n width: newWidth,\n height: newHeight\n });\n setStyle(element.getElementsByTagName('img')[0], assign({\n width: width * ratio,\n height: height * ratio\n }, getTransforms(assign({\n translateX: -left * ratio,\n translateY: -top * ratio\n }, imageData))));\n });\n }\n };\n\n var events = {\n bind: function bind() {\n var element = this.element,\n options = this.options,\n cropper = this.cropper;\n\n if (isFunction(options.cropstart)) {\n addListener(element, EVENT_CROP_START, options.cropstart);\n }\n\n if (isFunction(options.cropmove)) {\n addListener(element, EVENT_CROP_MOVE, options.cropmove);\n }\n\n if (isFunction(options.cropend)) {\n addListener(element, EVENT_CROP_END, options.cropend);\n }\n\n if (isFunction(options.crop)) {\n addListener(element, EVENT_CROP, options.crop);\n }\n\n if (isFunction(options.zoom)) {\n addListener(element, EVENT_ZOOM, options.zoom);\n }\n\n addListener(cropper, EVENT_POINTER_DOWN, this.onCropStart = this.cropStart.bind(this));\n\n if (options.zoomable && options.zoomOnWheel) {\n addListener(cropper, EVENT_WHEEL, this.onWheel = this.wheel.bind(this), {\n passive: false,\n capture: true\n });\n }\n\n if (options.toggleDragModeOnDblclick) {\n addListener(cropper, EVENT_DBLCLICK, this.onDblclick = this.dblclick.bind(this));\n }\n\n addListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove = this.cropMove.bind(this));\n addListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd = this.cropEnd.bind(this));\n\n if (options.responsive) {\n addListener(window, EVENT_RESIZE, this.onResize = this.resize.bind(this));\n }\n },\n unbind: function unbind() {\n var element = this.element,\n options = this.options,\n cropper = this.cropper;\n\n if (isFunction(options.cropstart)) {\n removeListener(element, EVENT_CROP_START, options.cropstart);\n }\n\n if (isFunction(options.cropmove)) {\n removeListener(element, EVENT_CROP_MOVE, options.cropmove);\n }\n\n if (isFunction(options.cropend)) {\n removeListener(element, EVENT_CROP_END, options.cropend);\n }\n\n if (isFunction(options.crop)) {\n removeListener(element, EVENT_CROP, options.crop);\n }\n\n if (isFunction(options.zoom)) {\n removeListener(element, EVENT_ZOOM, options.zoom);\n }\n\n removeListener(cropper, EVENT_POINTER_DOWN, this.onCropStart);\n\n if (options.zoomable && options.zoomOnWheel) {\n removeListener(cropper, EVENT_WHEEL, this.onWheel, {\n passive: false,\n capture: true\n });\n }\n\n if (options.toggleDragModeOnDblclick) {\n removeListener(cropper, EVENT_DBLCLICK, this.onDblclick);\n }\n\n removeListener(element.ownerDocument, EVENT_POINTER_MOVE, this.onCropMove);\n removeListener(element.ownerDocument, EVENT_POINTER_UP, this.onCropEnd);\n\n if (options.responsive) {\n removeListener(window, EVENT_RESIZE, this.onResize);\n }\n }\n };\n\n var handlers = {\n resize: function resize() {\n if (this.disabled) {\n return;\n }\n\n var options = this.options,\n container = this.container,\n containerData = this.containerData;\n var ratio = container.offsetWidth / containerData.width; // Resize when width changed or height changed\n\n if (ratio !== 1 || container.offsetHeight !== containerData.height) {\n var canvasData;\n var cropBoxData;\n\n if (options.restore) {\n canvasData = this.getCanvasData();\n cropBoxData = this.getCropBoxData();\n }\n\n this.render();\n\n if (options.restore) {\n this.setCanvasData(forEach(canvasData, function (n, i) {\n canvasData[i] = n * ratio;\n }));\n this.setCropBoxData(forEach(cropBoxData, function (n, i) {\n cropBoxData[i] = n * ratio;\n }));\n }\n }\n },\n dblclick: function dblclick() {\n if (this.disabled || this.options.dragMode === DRAG_MODE_NONE) {\n return;\n }\n\n this.setDragMode(hasClass(this.dragBox, CLASS_CROP) ? DRAG_MODE_MOVE : DRAG_MODE_CROP);\n },\n wheel: function wheel(event) {\n var _this = this;\n\n var ratio = Number(this.options.wheelZoomRatio) || 0.1;\n var delta = 1;\n\n if (this.disabled) {\n return;\n }\n\n event.preventDefault(); // Limit wheel speed to prevent zoom too fast (#21)\n\n if (this.wheeling) {\n return;\n }\n\n this.wheeling = true;\n setTimeout(function () {\n _this.wheeling = false;\n }, 50);\n\n if (event.deltaY) {\n delta = event.deltaY > 0 ? 1 : -1;\n } else if (event.wheelDelta) {\n delta = -event.wheelDelta / 120;\n } else if (event.detail) {\n delta = event.detail > 0 ? 1 : -1;\n }\n\n this.zoom(-delta * ratio, event);\n },\n cropStart: function cropStart(event) {\n var buttons = event.buttons,\n button = event.button;\n\n if (this.disabled // Handle mouse event and pointer event and ignore touch event\n || (event.type === 'mousedown' || event.type === 'pointerdown' && event.pointerType === 'mouse') && ( // No primary button (Usually the left button)\n isNumber(buttons) && buttons !== 1 || isNumber(button) && button !== 0 // Open context menu\n || event.ctrlKey)) {\n return;\n }\n\n var options = this.options,\n pointers = this.pointers;\n var action;\n\n if (event.changedTouches) {\n // Handle touch event\n forEach(event.changedTouches, function (touch) {\n pointers[touch.identifier] = getPointer(touch);\n });\n } else {\n // Handle mouse event and pointer event\n pointers[event.pointerId || 0] = getPointer(event);\n }\n\n if (Object.keys(pointers).length > 1 && options.zoomable && options.zoomOnTouch) {\n action = ACTION_ZOOM;\n } else {\n action = getData(event.target, DATA_ACTION);\n }\n\n if (!REGEXP_ACTIONS.test(action)) {\n return;\n }\n\n if (dispatchEvent(this.element, EVENT_CROP_START, {\n originalEvent: event,\n action: action\n }) === false) {\n return;\n } // This line is required for preventing page zooming in iOS browsers\n\n\n event.preventDefault();\n this.action = action;\n this.cropping = false;\n\n if (action === ACTION_CROP) {\n this.cropping = true;\n addClass(this.dragBox, CLASS_MODAL);\n }\n },\n cropMove: function cropMove(event) {\n var action = this.action;\n\n if (this.disabled || !action) {\n return;\n }\n\n var pointers = this.pointers;\n event.preventDefault();\n\n if (dispatchEvent(this.element, EVENT_CROP_MOVE, {\n originalEvent: event,\n action: action\n }) === false) {\n return;\n }\n\n if (event.changedTouches) {\n forEach(event.changedTouches, function (touch) {\n // The first parameter should not be undefined (#432)\n assign(pointers[touch.identifier] || {}, getPointer(touch, true));\n });\n } else {\n assign(pointers[event.pointerId || 0] || {}, getPointer(event, true));\n }\n\n this.change(event);\n },\n cropEnd: function cropEnd(event) {\n if (this.disabled) {\n return;\n }\n\n var action = this.action,\n pointers = this.pointers;\n\n if (event.changedTouches) {\n forEach(event.changedTouches, function (touch) {\n delete pointers[touch.identifier];\n });\n } else {\n delete pointers[event.pointerId || 0];\n }\n\n if (!action) {\n return;\n }\n\n event.preventDefault();\n\n if (!Object.keys(pointers).length) {\n this.action = '';\n }\n\n if (this.cropping) {\n this.cropping = false;\n toggleClass(this.dragBox, CLASS_MODAL, this.cropped && this.options.modal);\n }\n\n dispatchEvent(this.element, EVENT_CROP_END, {\n originalEvent: event,\n action: action\n });\n }\n };\n\n var change = {\n change: function change(event) {\n var options = this.options,\n canvasData = this.canvasData,\n containerData = this.containerData,\n cropBoxData = this.cropBoxData,\n pointers = this.pointers;\n var action = this.action;\n var aspectRatio = options.aspectRatio;\n var left = cropBoxData.left,\n top = cropBoxData.top,\n width = cropBoxData.width,\n height = cropBoxData.height;\n var right = left + width;\n var bottom = top + height;\n var minLeft = 0;\n var minTop = 0;\n var maxWidth = containerData.width;\n var maxHeight = containerData.height;\n var renderable = true;\n var offset; // Locking aspect ratio in \"free mode\" by holding shift key\n\n if (!aspectRatio && event.shiftKey) {\n aspectRatio = width && height ? width / height : 1;\n }\n\n if (this.limited) {\n minLeft = cropBoxData.minLeft;\n minTop = cropBoxData.minTop;\n maxWidth = minLeft + Math.min(containerData.width, canvasData.width, canvasData.left + canvasData.width);\n maxHeight = minTop + Math.min(containerData.height, canvasData.height, canvasData.top + canvasData.height);\n }\n\n var pointer = pointers[Object.keys(pointers)[0]];\n var range = {\n x: pointer.endX - pointer.startX,\n y: pointer.endY - pointer.startY\n };\n\n var check = function check(side) {\n switch (side) {\n case ACTION_EAST:\n if (right + range.x > maxWidth) {\n range.x = maxWidth - right;\n }\n\n break;\n\n case ACTION_WEST:\n if (left + range.x < minLeft) {\n range.x = minLeft - left;\n }\n\n break;\n\n case ACTION_NORTH:\n if (top + range.y < minTop) {\n range.y = minTop - top;\n }\n\n break;\n\n case ACTION_SOUTH:\n if (bottom + range.y > maxHeight) {\n range.y = maxHeight - bottom;\n }\n\n break;\n }\n };\n\n switch (action) {\n // Move crop box\n case ACTION_ALL:\n left += range.x;\n top += range.y;\n break;\n // Resize crop box\n\n case ACTION_EAST:\n if (range.x >= 0 && (right >= maxWidth || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n renderable = false;\n break;\n }\n\n check(ACTION_EAST);\n width += range.x;\n\n if (width < 0) {\n action = ACTION_WEST;\n width = -width;\n left -= width;\n }\n\n if (aspectRatio) {\n height = width / aspectRatio;\n top += (cropBoxData.height - height) / 2;\n }\n\n break;\n\n case ACTION_NORTH:\n if (range.y <= 0 && (top <= minTop || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n renderable = false;\n break;\n }\n\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n\n if (height < 0) {\n action = ACTION_SOUTH;\n height = -height;\n top -= height;\n }\n\n if (aspectRatio) {\n width = height * aspectRatio;\n left += (cropBoxData.width - width) / 2;\n }\n\n break;\n\n case ACTION_WEST:\n if (range.x <= 0 && (left <= minLeft || aspectRatio && (top <= minTop || bottom >= maxHeight))) {\n renderable = false;\n break;\n }\n\n check(ACTION_WEST);\n width -= range.x;\n left += range.x;\n\n if (width < 0) {\n action = ACTION_EAST;\n width = -width;\n left -= width;\n }\n\n if (aspectRatio) {\n height = width / aspectRatio;\n top += (cropBoxData.height - height) / 2;\n }\n\n break;\n\n case ACTION_SOUTH:\n if (range.y >= 0 && (bottom >= maxHeight || aspectRatio && (left <= minLeft || right >= maxWidth))) {\n renderable = false;\n break;\n }\n\n check(ACTION_SOUTH);\n height += range.y;\n\n if (height < 0) {\n action = ACTION_NORTH;\n height = -height;\n top -= height;\n }\n\n if (aspectRatio) {\n width = height * aspectRatio;\n left += (cropBoxData.width - width) / 2;\n }\n\n break;\n\n case ACTION_NORTH_EAST:\n if (aspectRatio) {\n if (range.y <= 0 && (top <= minTop || right >= maxWidth)) {\n renderable = false;\n break;\n }\n\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n width = height * aspectRatio;\n } else {\n check(ACTION_NORTH);\n check(ACTION_EAST);\n\n if (range.x >= 0) {\n if (right < maxWidth) {\n width += range.x;\n } else if (range.y <= 0 && top <= minTop) {\n renderable = false;\n }\n } else {\n width += range.x;\n }\n\n if (range.y <= 0) {\n if (top > minTop) {\n height -= range.y;\n top += range.y;\n }\n } else {\n height -= range.y;\n top += range.y;\n }\n }\n\n if (width < 0 && height < 0) {\n action = ACTION_SOUTH_WEST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_NORTH_WEST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_SOUTH_EAST;\n height = -height;\n top -= height;\n }\n\n break;\n\n case ACTION_NORTH_WEST:\n if (aspectRatio) {\n if (range.y <= 0 && (top <= minTop || left <= minLeft)) {\n renderable = false;\n break;\n }\n\n check(ACTION_NORTH);\n height -= range.y;\n top += range.y;\n width = height * aspectRatio;\n left += cropBoxData.width - width;\n } else {\n check(ACTION_NORTH);\n check(ACTION_WEST);\n\n if (range.x <= 0) {\n if (left > minLeft) {\n width -= range.x;\n left += range.x;\n } else if (range.y <= 0 && top <= minTop) {\n renderable = false;\n }\n } else {\n width -= range.x;\n left += range.x;\n }\n\n if (range.y <= 0) {\n if (top > minTop) {\n height -= range.y;\n top += range.y;\n }\n } else {\n height -= range.y;\n top += range.y;\n }\n }\n\n if (width < 0 && height < 0) {\n action = ACTION_SOUTH_EAST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_NORTH_EAST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_SOUTH_WEST;\n height = -height;\n top -= height;\n }\n\n break;\n\n case ACTION_SOUTH_WEST:\n if (aspectRatio) {\n if (range.x <= 0 && (left <= minLeft || bottom >= maxHeight)) {\n renderable = false;\n break;\n }\n\n check(ACTION_WEST);\n width -= range.x;\n left += range.x;\n height = width / aspectRatio;\n } else {\n check(ACTION_SOUTH);\n check(ACTION_WEST);\n\n if (range.x <= 0) {\n if (left > minLeft) {\n width -= range.x;\n left += range.x;\n } else if (range.y >= 0 && bottom >= maxHeight) {\n renderable = false;\n }\n } else {\n width -= range.x;\n left += range.x;\n }\n\n if (range.y >= 0) {\n if (bottom < maxHeight) {\n height += range.y;\n }\n } else {\n height += range.y;\n }\n }\n\n if (width < 0 && height < 0) {\n action = ACTION_NORTH_EAST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_SOUTH_EAST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_NORTH_WEST;\n height = -height;\n top -= height;\n }\n\n break;\n\n case ACTION_SOUTH_EAST:\n if (aspectRatio) {\n if (range.x >= 0 && (right >= maxWidth || bottom >= maxHeight)) {\n renderable = false;\n break;\n }\n\n check(ACTION_EAST);\n width += range.x;\n height = width / aspectRatio;\n } else {\n check(ACTION_SOUTH);\n check(ACTION_EAST);\n\n if (range.x >= 0) {\n if (right < maxWidth) {\n width += range.x;\n } else if (range.y >= 0 && bottom >= maxHeight) {\n renderable = false;\n }\n } else {\n width += range.x;\n }\n\n if (range.y >= 0) {\n if (bottom < maxHeight) {\n height += range.y;\n }\n } else {\n height += range.y;\n }\n }\n\n if (width < 0 && height < 0) {\n action = ACTION_NORTH_WEST;\n height = -height;\n width = -width;\n top -= height;\n left -= width;\n } else if (width < 0) {\n action = ACTION_SOUTH_WEST;\n width = -width;\n left -= width;\n } else if (height < 0) {\n action = ACTION_NORTH_EAST;\n height = -height;\n top -= height;\n }\n\n break;\n // Move canvas\n\n case ACTION_MOVE:\n this.move(range.x, range.y);\n renderable = false;\n break;\n // Zoom canvas\n\n case ACTION_ZOOM:\n this.zoom(getMaxZoomRatio(pointers), event);\n renderable = false;\n break;\n // Create crop box\n\n case ACTION_CROP:\n if (!range.x || !range.y) {\n renderable = false;\n break;\n }\n\n offset = getOffset(this.cropper);\n left = pointer.startX - offset.left;\n top = pointer.startY - offset.top;\n width = cropBoxData.minWidth;\n height = cropBoxData.minHeight;\n\n if (range.x > 0) {\n action = range.y > 0 ? ACTION_SOUTH_EAST : ACTION_NORTH_EAST;\n } else if (range.x < 0) {\n left -= width;\n action = range.y > 0 ? ACTION_SOUTH_WEST : ACTION_NORTH_WEST;\n }\n\n if (range.y < 0) {\n top -= height;\n } // Show the crop box if is hidden\n\n\n if (!this.cropped) {\n removeClass(this.cropBox, CLASS_HIDDEN);\n this.cropped = true;\n\n if (this.limited) {\n this.limitCropBox(true, true);\n }\n }\n\n break;\n }\n\n if (renderable) {\n cropBoxData.width = width;\n cropBoxData.height = height;\n cropBoxData.left = left;\n cropBoxData.top = top;\n this.action = action;\n this.renderCropBox();\n } // Override\n\n\n forEach(pointers, function (p) {\n p.startX = p.endX;\n p.startY = p.endY;\n });\n }\n };\n\n var methods = {\n // Show the crop box manually\n crop: function crop() {\n if (this.ready && !this.cropped && !this.disabled) {\n this.cropped = true;\n this.limitCropBox(true, true);\n\n if (this.options.modal) {\n addClass(this.dragBox, CLASS_MODAL);\n }\n\n removeClass(this.cropBox, CLASS_HIDDEN);\n this.setCropBoxData(this.initialCropBoxData);\n }\n\n return this;\n },\n // Reset the image and crop box to their initial states\n reset: function reset() {\n if (this.ready && !this.disabled) {\n this.imageData = assign({}, this.initialImageData);\n this.canvasData = assign({}, this.initialCanvasData);\n this.cropBoxData = assign({}, this.initialCropBoxData);\n this.renderCanvas();\n\n if (this.cropped) {\n this.renderCropBox();\n }\n }\n\n return this;\n },\n // Clear the crop box\n clear: function clear() {\n if (this.cropped && !this.disabled) {\n assign(this.cropBoxData, {\n left: 0,\n top: 0,\n width: 0,\n height: 0\n });\n this.cropped = false;\n this.renderCropBox();\n this.limitCanvas(true, true); // Render canvas after crop box rendered\n\n this.renderCanvas();\n removeClass(this.dragBox, CLASS_MODAL);\n addClass(this.cropBox, CLASS_HIDDEN);\n }\n\n return this;\n },\n\n /**\n * Replace the image's src and rebuild the cropper\n * @param {string} url - The new URL.\n * @param {boolean} [hasSameSize] - Indicate if the new image has the same size as the old one.\n * @returns {Cropper} this\n */\n replace: function replace(url) {\n var hasSameSize = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;\n\n if (!this.disabled && url) {\n if (this.isImg) {\n this.element.src = url;\n }\n\n if (hasSameSize) {\n this.url = url;\n this.image.src = url;\n\n if (this.ready) {\n this.viewBoxImage.src = url;\n forEach(this.previews, function (element) {\n element.getElementsByTagName('img')[0].src = url;\n });\n }\n } else {\n if (this.isImg) {\n this.replaced = true;\n }\n\n this.options.data = null;\n this.uncreate();\n this.load(url);\n }\n }\n\n return this;\n },\n // Enable (unfreeze) the cropper\n enable: function enable() {\n if (this.ready && this.disabled) {\n this.disabled = false;\n removeClass(this.cropper, CLASS_DISABLED);\n }\n\n return this;\n },\n // Disable (freeze) the cropper\n disable: function disable() {\n if (this.ready && !this.disabled) {\n this.disabled = true;\n addClass(this.cropper, CLASS_DISABLED);\n }\n\n return this;\n },\n\n /**\n * Destroy the cropper and remove the instance from the image\n * @returns {Cropper} this\n */\n destroy: function destroy() {\n var element = this.element;\n\n if (!element[NAMESPACE]) {\n return this;\n }\n\n element[NAMESPACE] = undefined;\n\n if (this.isImg && this.replaced) {\n element.src = this.originalUrl;\n }\n\n this.uncreate();\n return this;\n },\n\n /**\n * Move the canvas with relative offsets\n * @param {number} offsetX - The relative offset distance on the x-axis.\n * @param {number} [offsetY=offsetX] - The relative offset distance on the y-axis.\n * @returns {Cropper} this\n */\n move: function move(offsetX) {\n var offsetY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : offsetX;\n var _this$canvasData = this.canvasData,\n left = _this$canvasData.left,\n top = _this$canvasData.top;\n return this.moveTo(isUndefined(offsetX) ? offsetX : left + Number(offsetX), isUndefined(offsetY) ? offsetY : top + Number(offsetY));\n },\n\n /**\n * Move the canvas to an absolute point\n * @param {number} x - The x-axis coordinate.\n * @param {number} [y=x] - The y-axis coordinate.\n * @returns {Cropper} this\n */\n moveTo: function moveTo(x) {\n var y = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : x;\n var canvasData = this.canvasData;\n var changed = false;\n x = Number(x);\n y = Number(y);\n\n if (this.ready && !this.disabled && this.options.movable) {\n if (isNumber(x)) {\n canvasData.left = x;\n changed = true;\n }\n\n if (isNumber(y)) {\n canvasData.top = y;\n changed = true;\n }\n\n if (changed) {\n this.renderCanvas(true);\n }\n }\n\n return this;\n },\n\n /**\n * Zoom the canvas with a relative ratio\n * @param {number} ratio - The target ratio.\n * @param {Event} _originalEvent - The original event if any.\n * @returns {Cropper} this\n */\n zoom: function zoom(ratio, _originalEvent) {\n var canvasData = this.canvasData;\n ratio = Number(ratio);\n\n if (ratio < 0) {\n ratio = 1 / (1 - ratio);\n } else {\n ratio = 1 + ratio;\n }\n\n return this.zoomTo(canvasData.width * ratio / canvasData.naturalWidth, null, _originalEvent);\n },\n\n /**\n * Zoom the canvas to an absolute ratio\n * @param {number} ratio - The target ratio.\n * @param {Object} pivot - The zoom pivot point coordinate.\n * @param {Event} _originalEvent - The original event if any.\n * @returns {Cropper} this\n */\n zoomTo: function zoomTo(ratio, pivot, _originalEvent) {\n var options = this.options,\n canvasData = this.canvasData;\n var width = canvasData.width,\n height = canvasData.height,\n naturalWidth = canvasData.naturalWidth,\n naturalHeight = canvasData.naturalHeight;\n ratio = Number(ratio);\n\n if (ratio >= 0 && this.ready && !this.disabled && options.zoomable) {\n var newWidth = naturalWidth * ratio;\n var newHeight = naturalHeight * ratio;\n\n if (dispatchEvent(this.element, EVENT_ZOOM, {\n ratio: ratio,\n oldRatio: width / naturalWidth,\n originalEvent: _originalEvent\n }) === false) {\n return this;\n }\n\n if (_originalEvent) {\n var pointers = this.pointers;\n var offset = getOffset(this.cropper);\n var center = pointers && Object.keys(pointers).length ? getPointersCenter(pointers) : {\n pageX: _originalEvent.pageX,\n pageY: _originalEvent.pageY\n }; // Zoom from the triggering point of the event\n\n canvasData.left -= (newWidth - width) * ((center.pageX - offset.left - canvasData.left) / width);\n canvasData.top -= (newHeight - height) * ((center.pageY - offset.top - canvasData.top) / height);\n } else if (isPlainObject(pivot) && isNumber(pivot.x) && isNumber(pivot.y)) {\n canvasData.left -= (newWidth - width) * ((pivot.x - canvasData.left) / width);\n canvasData.top -= (newHeight - height) * ((pivot.y - canvasData.top) / height);\n } else {\n // Zoom from the center of the canvas\n canvasData.left -= (newWidth - width) / 2;\n canvasData.top -= (newHeight - height) / 2;\n }\n\n canvasData.width = newWidth;\n canvasData.height = newHeight;\n this.renderCanvas(true);\n }\n\n return this;\n },\n\n /**\n * Rotate the canvas with a relative degree\n * @param {number} degree - The rotate degree.\n * @returns {Cropper} this\n */\n rotate: function rotate(degree) {\n return this.rotateTo((this.imageData.rotate || 0) + Number(degree));\n },\n\n /**\n * Rotate the canvas to an absolute degree\n * @param {number} degree - The rotate degree.\n * @returns {Cropper} this\n */\n rotateTo: function rotateTo(degree) {\n degree = Number(degree);\n\n if (isNumber(degree) && this.ready && !this.disabled && this.options.rotatable) {\n this.imageData.rotate = degree % 360;\n this.renderCanvas(true, true);\n }\n\n return this;\n },\n\n /**\n * Scale the image on the x-axis.\n * @param {number} scaleX - The scale ratio on the x-axis.\n * @returns {Cropper} this\n */\n scaleX: function scaleX(_scaleX) {\n var scaleY = this.imageData.scaleY;\n return this.scale(_scaleX, isNumber(scaleY) ? scaleY : 1);\n },\n\n /**\n * Scale the image on the y-axis.\n * @param {number} scaleY - The scale ratio on the y-axis.\n * @returns {Cropper} this\n */\n scaleY: function scaleY(_scaleY) {\n var scaleX = this.imageData.scaleX;\n return this.scale(isNumber(scaleX) ? scaleX : 1, _scaleY);\n },\n\n /**\n * Scale the image\n * @param {number} scaleX - The scale ratio on the x-axis.\n * @param {number} [scaleY=scaleX] - The scale ratio on the y-axis.\n * @returns {Cropper} this\n */\n scale: function scale(scaleX) {\n var scaleY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : scaleX;\n var imageData = this.imageData;\n var transformed = false;\n scaleX = Number(scaleX);\n scaleY = Number(scaleY);\n\n if (this.ready && !this.disabled && this.options.scalable) {\n if (isNumber(scaleX)) {\n imageData.scaleX = scaleX;\n transformed = true;\n }\n\n if (isNumber(scaleY)) {\n imageData.scaleY = scaleY;\n transformed = true;\n }\n\n if (transformed) {\n this.renderCanvas(true, true);\n }\n }\n\n return this;\n },\n\n /**\n * Get the cropped area position and size data (base on the original image)\n * @param {boolean} [rounded=false] - Indicate if round the data values or not.\n * @returns {Object} The result cropped data.\n */\n getData: function getData() {\n var rounded = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;\n var options = this.options,\n imageData = this.imageData,\n canvasData = this.canvasData,\n cropBoxData = this.cropBoxData;\n var data;\n\n if (this.ready && this.cropped) {\n data = {\n x: cropBoxData.left - canvasData.left,\n y: cropBoxData.top - canvasData.top,\n width: cropBoxData.width,\n height: cropBoxData.height\n };\n var ratio = imageData.width / imageData.naturalWidth;\n forEach(data, function (n, i) {\n data[i] = n / ratio;\n });\n\n if (rounded) {\n // In case rounding off leads to extra 1px in right or bottom border\n // we should round the top-left corner and the dimension (#343).\n var bottom = Math.round(data.y + data.height);\n var right = Math.round(data.x + data.width);\n data.x = Math.round(data.x);\n data.y = Math.round(data.y);\n data.width = right - data.x;\n data.height = bottom - data.y;\n }\n } else {\n data = {\n x: 0,\n y: 0,\n width: 0,\n height: 0\n };\n }\n\n if (options.rotatable) {\n data.rotate = imageData.rotate || 0;\n }\n\n if (options.scalable) {\n data.scaleX = imageData.scaleX || 1;\n data.scaleY = imageData.scaleY || 1;\n }\n\n return data;\n },\n\n /**\n * Set the cropped area position and size with new data\n * @param {Object} data - The new data.\n * @returns {Cropper} this\n */\n setData: function setData(data) {\n var options = this.options,\n imageData = this.imageData,\n canvasData = this.canvasData;\n var cropBoxData = {};\n\n if (this.ready && !this.disabled && isPlainObject(data)) {\n var transformed = false;\n\n if (options.rotatable) {\n if (isNumber(data.rotate) && data.rotate !== imageData.rotate) {\n imageData.rotate = data.rotate;\n transformed = true;\n }\n }\n\n if (options.scalable) {\n if (isNumber(data.scaleX) && data.scaleX !== imageData.scaleX) {\n imageData.scaleX = data.scaleX;\n transformed = true;\n }\n\n if (isNumber(data.scaleY) && data.scaleY !== imageData.scaleY) {\n imageData.scaleY = data.scaleY;\n transformed = true;\n }\n }\n\n if (transformed) {\n this.renderCanvas(true, true);\n }\n\n var ratio = imageData.width / imageData.naturalWidth;\n\n if (isNumber(data.x)) {\n cropBoxData.left = data.x * ratio + canvasData.left;\n }\n\n if (isNumber(data.y)) {\n cropBoxData.top = data.y * ratio + canvasData.top;\n }\n\n if (isNumber(data.width)) {\n cropBoxData.width = data.width * ratio;\n }\n\n if (isNumber(data.height)) {\n cropBoxData.height = data.height * ratio;\n }\n\n this.setCropBoxData(cropBoxData);\n }\n\n return this;\n },\n\n /**\n * Get the container size data.\n * @returns {Object} The result container data.\n */\n getContainerData: function getContainerData() {\n return this.ready ? assign({}, this.containerData) : {};\n },\n\n /**\n * Get the image position and size data.\n * @returns {Object} The result image data.\n */\n getImageData: function getImageData() {\n return this.sized ? assign({}, this.imageData) : {};\n },\n\n /**\n * Get the canvas position and size data.\n * @returns {Object} The result canvas data.\n */\n getCanvasData: function getCanvasData() {\n var canvasData = this.canvasData;\n var data = {};\n\n if (this.ready) {\n forEach(['left', 'top', 'width', 'height', 'naturalWidth', 'naturalHeight'], function (n) {\n data[n] = canvasData[n];\n });\n }\n\n return data;\n },\n\n /**\n * Set the canvas position and size with new data.\n * @param {Object} data - The new canvas data.\n * @returns {Cropper} this\n */\n setCanvasData: function setCanvasData(data) {\n var canvasData = this.canvasData;\n var aspectRatio = canvasData.aspectRatio;\n\n if (this.ready && !this.disabled && isPlainObject(data)) {\n if (isNumber(data.left)) {\n canvasData.left = data.left;\n }\n\n if (isNumber(data.top)) {\n canvasData.top = data.top;\n }\n\n if (isNumber(data.width)) {\n canvasData.width = data.width;\n canvasData.height = data.width / aspectRatio;\n } else if (isNumber(data.height)) {\n canvasData.height = data.height;\n canvasData.width = data.height * aspectRatio;\n }\n\n this.renderCanvas(true);\n }\n\n return this;\n },\n\n /**\n * Get the crop box position and size data.\n * @returns {Object} The result crop box data.\n */\n getCropBoxData: function getCropBoxData() {\n var cropBoxData = this.cropBoxData;\n var data;\n\n if (this.ready && this.cropped) {\n data = {\n left: cropBoxData.left,\n top: cropBoxData.top,\n width: cropBoxData.width,\n height: cropBoxData.height\n };\n }\n\n return data || {};\n },\n\n /**\n * Set the crop box position and size with new data.\n * @param {Object} data - The new crop box data.\n * @returns {Cropper} this\n */\n setCropBoxData: function setCropBoxData(data) {\n var cropBoxData = this.cropBoxData;\n var aspectRatio = this.options.aspectRatio;\n var widthChanged;\n var heightChanged;\n\n if (this.ready && this.cropped && !this.disabled && isPlainObject(data)) {\n if (isNumber(data.left)) {\n cropBoxData.left = data.left;\n }\n\n if (isNumber(data.top)) {\n cropBoxData.top = data.top;\n }\n\n if (isNumber(data.width) && data.width !== cropBoxData.width) {\n widthChanged = true;\n cropBoxData.width = data.width;\n }\n\n if (isNumber(data.height) && data.height !== cropBoxData.height) {\n heightChanged = true;\n cropBoxData.height = data.height;\n }\n\n if (aspectRatio) {\n if (widthChanged) {\n cropBoxData.height = cropBoxData.width / aspectRatio;\n } else if (heightChanged) {\n cropBoxData.width = cropBoxData.height * aspectRatio;\n }\n }\n\n this.renderCropBox();\n }\n\n return this;\n },\n\n /**\n * Get a canvas drawn the cropped image.\n * @param {Object} [options={}] - The config options.\n * @returns {HTMLCanvasElement} - The result canvas.\n */\n getCroppedCanvas: function getCroppedCanvas() {\n var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n\n if (!this.ready || !window.HTMLCanvasElement) {\n return null;\n }\n\n var canvasData = this.canvasData;\n var source = getSourceCanvas(this.image, this.imageData, canvasData, options); // Returns the source canvas if it is not cropped.\n\n if (!this.cropped) {\n return source;\n }\n\n var _this$getData = this.getData(),\n initialX = _this$getData.x,\n initialY = _this$getData.y,\n initialWidth = _this$getData.width,\n initialHeight = _this$getData.height;\n\n var ratio = source.width / Math.floor(canvasData.naturalWidth);\n\n if (ratio !== 1) {\n initialX *= ratio;\n initialY *= ratio;\n initialWidth *= ratio;\n initialHeight *= ratio;\n }\n\n var aspectRatio = initialWidth / initialHeight;\n var maxSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.maxWidth || Infinity,\n height: options.maxHeight || Infinity\n });\n var minSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.minWidth || 0,\n height: options.minHeight || 0\n }, 'cover');\n\n var _getAdjustedSizes = getAdjustedSizes({\n aspectRatio: aspectRatio,\n width: options.width || (ratio !== 1 ? source.width : initialWidth),\n height: options.height || (ratio !== 1 ? source.height : initialHeight)\n }),\n width = _getAdjustedSizes.width,\n height = _getAdjustedSizes.height;\n\n width = Math.min(maxSizes.width, Math.max(minSizes.width, width));\n height = Math.min(maxSizes.height, Math.max(minSizes.height, height));\n var canvas = document.createElement('canvas');\n var context = canvas.getContext('2d');\n canvas.width = normalizeDecimalNumber(width);\n canvas.height = normalizeDecimalNumber(height);\n context.fillStyle = options.fillColor || 'transparent';\n context.fillRect(0, 0, width, height);\n var _options$imageSmoothi = options.imageSmoothingEnabled,\n imageSmoothingEnabled = _options$imageSmoothi === void 0 ? true : _options$imageSmoothi,\n imageSmoothingQuality = options.imageSmoothingQuality;\n context.imageSmoothingEnabled = imageSmoothingEnabled;\n\n if (imageSmoothingQuality) {\n context.imageSmoothingQuality = imageSmoothingQuality;\n } // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D.drawImage\n\n\n var sourceWidth = source.width;\n var sourceHeight = source.height; // Source canvas parameters\n\n var srcX = initialX;\n var srcY = initialY;\n var srcWidth;\n var srcHeight; // Destination canvas parameters\n\n var dstX;\n var dstY;\n var dstWidth;\n var dstHeight;\n\n if (srcX <= -initialWidth || srcX > sourceWidth) {\n srcX = 0;\n srcWidth = 0;\n dstX = 0;\n dstWidth = 0;\n } else if (srcX <= 0) {\n dstX = -srcX;\n srcX = 0;\n srcWidth = Math.min(sourceWidth, initialWidth + srcX);\n dstWidth = srcWidth;\n } else if (srcX <= sourceWidth) {\n dstX = 0;\n srcWidth = Math.min(initialWidth, sourceWidth - srcX);\n dstWidth = srcWidth;\n }\n\n if (srcWidth <= 0 || srcY <= -initialHeight || srcY > sourceHeight) {\n srcY = 0;\n srcHeight = 0;\n dstY = 0;\n dstHeight = 0;\n } else if (srcY <= 0) {\n dstY = -srcY;\n srcY = 0;\n srcHeight = Math.min(sourceHeight, initialHeight + srcY);\n dstHeight = srcHeight;\n } else if (srcY <= sourceHeight) {\n dstY = 0;\n srcHeight = Math.min(initialHeight, sourceHeight - srcY);\n dstHeight = srcHeight;\n }\n\n var params = [srcX, srcY, srcWidth, srcHeight]; // Avoid \"IndexSizeError\"\n\n if (dstWidth > 0 && dstHeight > 0) {\n var scale = width / initialWidth;\n params.push(dstX * scale, dstY * scale, dstWidth * scale, dstHeight * scale);\n } // All the numerical parameters should be integer for `drawImage`\n // https://github.com/fengyuanchen/cropper/issues/476\n\n\n context.drawImage.apply(context, [source].concat(_toConsumableArray(params.map(function (param) {\n return Math.floor(normalizeDecimalNumber(param));\n }))));\n return canvas;\n },\n\n /**\n * Change the aspect ratio of the crop box.\n * @param {number} aspectRatio - The new aspect ratio.\n * @returns {Cropper} this\n */\n setAspectRatio: function setAspectRatio(aspectRatio) {\n var options = this.options;\n\n if (!this.disabled && !isUndefined(aspectRatio)) {\n // 0 -> NaN\n options.aspectRatio = Math.max(0, aspectRatio) || NaN;\n\n if (this.ready) {\n this.initCropBox();\n\n if (this.cropped) {\n this.renderCropBox();\n }\n }\n }\n\n return this;\n },\n\n /**\n * Change the drag mode.\n * @param {string} mode - The new drag mode.\n * @returns {Cropper} this\n */\n setDragMode: function setDragMode(mode) {\n var options = this.options,\n dragBox = this.dragBox,\n face = this.face;\n\n if (this.ready && !this.disabled) {\n var croppable = mode === DRAG_MODE_CROP;\n var movable = options.movable && mode === DRAG_MODE_MOVE;\n mode = croppable || movable ? mode : DRAG_MODE_NONE;\n options.dragMode = mode;\n setData(dragBox, DATA_ACTION, mode);\n toggleClass(dragBox, CLASS_CROP, croppable);\n toggleClass(dragBox, CLASS_MOVE, movable);\n\n if (!options.cropBoxMovable) {\n // Sync drag mode to crop box when it is not movable\n setData(face, DATA_ACTION, mode);\n toggleClass(face, CLASS_CROP, croppable);\n toggleClass(face, CLASS_MOVE, movable);\n }\n }\n\n return this;\n }\n };\n\n var AnotherCropper = WINDOW.Cropper;\n\n var Cropper = /*#__PURE__*/function () {\n /**\n * Create a new Cropper.\n * @param {Element} element - The target element for cropping.\n * @param {Object} [options={}] - The configuration options.\n */\n function Cropper(element) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n _classCallCheck(this, Cropper);\n\n if (!element || !REGEXP_TAG_NAME.test(element.tagName)) {\n throw new Error('The first argument is required and must be an <img> or <canvas> element.');\n }\n\n this.element = element;\n this.options = assign({}, DEFAULTS, isPlainObject(options) && options);\n this.cropped = false;\n this.disabled = false;\n this.pointers = {};\n this.ready = false;\n this.reloading = false;\n this.replaced = false;\n this.sized = false;\n this.sizing = false;\n this.init();\n }\n\n _createClass(Cropper, [{\n key: \"init\",\n value: function init() {\n var element = this.element;\n var tagName = element.tagName.toLowerCase();\n var url;\n\n if (element[NAMESPACE]) {\n return;\n }\n\n element[NAMESPACE] = this;\n\n if (tagName === 'img') {\n this.isImg = true; // e.g.: \"img/picture.jpg\"\n\n url = element.getAttribute('src') || '';\n this.originalUrl = url; // Stop when it's a blank image\n\n if (!url) {\n return;\n } // e.g.: \"https://example.com/img/picture.jpg\"\n\n\n url = element.src;\n } else if (tagName === 'canvas' && window.HTMLCanvasElement) {\n url = element.toDataURL();\n }\n\n this.load(url);\n }\n }, {\n key: \"load\",\n value: function load(url) {\n var _this = this;\n\n if (!url) {\n return;\n }\n\n this.url = url;\n this.imageData = {};\n var element = this.element,\n options = this.options;\n\n if (!options.rotatable && !options.scalable) {\n options.checkOrientation = false;\n } // Only IE10+ supports Typed Arrays\n\n\n if (!options.checkOrientation || !window.ArrayBuffer) {\n this.clone();\n return;\n } // Detect the mime type of the image directly if it is a Data URL\n\n\n if (REGEXP_DATA_URL.test(url)) {\n // Read ArrayBuffer from Data URL of JPEG images directly for better performance\n if (REGEXP_DATA_URL_JPEG.test(url)) {\n this.read(dataURLToArrayBuffer(url));\n } else {\n // Only a JPEG image may contains Exif Orientation information,\n // the rest types of Data URLs are not necessary to check orientation at all.\n this.clone();\n }\n\n return;\n } // 1. Detect the mime type of the image by a XMLHttpRequest.\n // 2. Load the image as ArrayBuffer for reading orientation if its a JPEG image.\n\n\n var xhr = new XMLHttpRequest();\n var clone = this.clone.bind(this);\n this.reloading = true;\n this.xhr = xhr; // 1. Cross origin requests are only supported for protocol schemes:\n // http, https, data, chrome, chrome-extension.\n // 2. Access to XMLHttpRequest from a Data URL will be blocked by CORS policy\n // in some browsers as IE11 and Safari.\n\n xhr.onabort = clone;\n xhr.onerror = clone;\n xhr.ontimeout = clone;\n\n xhr.onprogress = function () {\n // Abort the request directly if it not a JPEG image for better performance\n if (xhr.getResponseHeader('content-type') !== MIME_TYPE_JPEG) {\n xhr.abort();\n }\n };\n\n xhr.onload = function () {\n _this.read(xhr.response);\n };\n\n xhr.onloadend = function () {\n _this.reloading = false;\n _this.xhr = null;\n }; // Bust cache when there is a \"crossOrigin\" property to avoid browser cache error\n\n\n if (options.checkCrossOrigin && isCrossOriginURL(url) && element.crossOrigin) {\n url = addTimestamp(url);\n }\n\n xhr.open('GET', url);\n xhr.responseType = 'arraybuffer';\n xhr.withCredentials = element.crossOrigin === 'use-credentials';\n xhr.send();\n }\n }, {\n key: \"read\",\n value: function read(arrayBuffer) {\n var options = this.options,\n imageData = this.imageData; // Reset the orientation value to its default value 1\n // as some iOS browsers will render image with its orientation\n\n var orientation = resetAndGetOrientation(arrayBuffer);\n var rotate = 0;\n var scaleX = 1;\n var scaleY = 1;\n\n if (orientation > 1) {\n // Generate a new URL which has the default orientation value\n this.url = arrayBufferToDataURL(arrayBuffer, MIME_TYPE_JPEG);\n\n var _parseOrientation = parseOrientation(orientation);\n\n rotate = _parseOrientation.rotate;\n scaleX = _parseOrientation.scaleX;\n scaleY = _parseOrientation.scaleY;\n }\n\n if (options.rotatable) {\n imageData.rotate = rotate;\n }\n\n if (options.scalable) {\n imageData.scaleX = scaleX;\n imageData.scaleY = scaleY;\n }\n\n this.clone();\n }\n }, {\n key: \"clone\",\n value: function clone() {\n var element = this.element,\n url = this.url;\n var crossOrigin = element.crossOrigin;\n var crossOriginUrl = url;\n\n if (this.options.checkCrossOrigin && isCrossOriginURL(url)) {\n if (!crossOrigin) {\n crossOrigin = 'anonymous';\n } // Bust cache when there is not a \"crossOrigin\" property (#519)\n\n\n crossOriginUrl = addTimestamp(url);\n }\n\n this.crossOrigin = crossOrigin;\n this.crossOriginUrl = crossOriginUrl;\n var image = document.createElement('img');\n\n if (crossOrigin) {\n image.crossOrigin = crossOrigin;\n }\n\n image.src = crossOriginUrl || url;\n image.alt = element.alt || 'The image to crop';\n this.image = image;\n image.onload = this.start.bind(this);\n image.onerror = this.stop.bind(this);\n addClass(image, CLASS_HIDE);\n element.parentNode.insertBefore(image, element.nextSibling);\n }\n }, {\n key: \"start\",\n value: function start() {\n var _this2 = this;\n\n var image = this.image;\n image.onload = null;\n image.onerror = null;\n this.sizing = true; // Match all browsers that use WebKit as the layout engine in iOS devices,\n // such as Safari for iOS, Chrome for iOS, and in-app browsers.\n\n var isIOSWebKit = WINDOW.navigator && /(?:iPad|iPhone|iPod).*?AppleWebKit/i.test(WINDOW.navigator.userAgent);\n\n var done = function done(naturalWidth, naturalHeight) {\n assign(_this2.imageData, {\n naturalWidth: naturalWidth,\n naturalHeight: naturalHeight,\n aspectRatio: naturalWidth / naturalHeight\n });\n _this2.sizing = false;\n _this2.sized = true;\n\n _this2.build();\n }; // Most modern browsers (excepts iOS WebKit)\n\n\n if (image.naturalWidth && !isIOSWebKit) {\n done(image.naturalWidth, image.naturalHeight);\n return;\n }\n\n var sizingImage = document.createElement('img');\n var body = document.body || document.documentElement;\n this.sizingImage = sizingImage;\n\n sizingImage.onload = function () {\n done(sizingImage.width, sizingImage.height);\n\n if (!isIOSWebKit) {\n body.removeChild(sizingImage);\n }\n };\n\n sizingImage.src = image.src; // iOS WebKit will convert the image automatically\n // with its orientation once append it into DOM (#279)\n\n if (!isIOSWebKit) {\n sizingImage.style.cssText = 'left:0;' + 'max-height:none!important;' + 'max-width:none!important;' + 'min-height:0!important;' + 'min-width:0!important;' + 'opacity:0;' + 'position:absolute;' + 'top:0;' + 'z-index:-1;';\n body.appendChild(sizingImage);\n }\n }\n }, {\n key: \"stop\",\n value: function stop() {\n var image = this.image;\n image.onload = null;\n image.onerror = null;\n image.parentNode.removeChild(image);\n this.image = null;\n }\n }, {\n key: \"build\",\n value: function build() {\n if (!this.sized || this.ready) {\n return;\n }\n\n var element = this.element,\n options = this.options,\n image = this.image; // Create cropper elements\n\n var container = element.parentNode;\n var template = document.createElement('div');\n template.innerHTML = TEMPLATE;\n var cropper = template.querySelector(\".\".concat(NAMESPACE, \"-container\"));\n var canvas = cropper.querySelector(\".\".concat(NAMESPACE, \"-canvas\"));\n var dragBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-drag-box\"));\n var cropBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-crop-box\"));\n var face = cropBox.querySelector(\".\".concat(NAMESPACE, \"-face\"));\n this.container = container;\n this.cropper = cropper;\n this.canvas = canvas;\n this.dragBox = dragBox;\n this.cropBox = cropBox;\n this.viewBox = cropper.querySelector(\".\".concat(NAMESPACE, \"-view-box\"));\n this.face = face;\n canvas.appendChild(image); // Hide the original image\n\n addClass(element, CLASS_HIDDEN); // Inserts the cropper after to the current image\n\n container.insertBefore(cropper, element.nextSibling); // Show the image if is hidden\n\n if (!this.isImg) {\n removeClass(image, CLASS_HIDE);\n }\n\n this.initPreview();\n this.bind();\n options.initialAspectRatio = Math.max(0, options.initialAspectRatio) || NaN;\n options.aspectRatio = Math.max(0, options.aspectRatio) || NaN;\n options.viewMode = Math.max(0, Math.min(3, Math.round(options.viewMode))) || 0;\n addClass(cropBox, CLASS_HIDDEN);\n\n if (!options.guides) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-dashed\")), CLASS_HIDDEN);\n }\n\n if (!options.center) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-center\")), CLASS_HIDDEN);\n }\n\n if (options.background) {\n addClass(cropper, \"\".concat(NAMESPACE, \"-bg\"));\n }\n\n if (!options.highlight) {\n addClass(face, CLASS_INVISIBLE);\n }\n\n if (options.cropBoxMovable) {\n addClass(face, CLASS_MOVE);\n setData(face, DATA_ACTION, ACTION_ALL);\n }\n\n if (!options.cropBoxResizable) {\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-line\")), CLASS_HIDDEN);\n addClass(cropBox.getElementsByClassName(\"\".concat(NAMESPACE, \"-point\")), CLASS_HIDDEN);\n }\n\n this.render();\n this.ready = true;\n this.setDragMode(options.dragMode);\n\n if (options.autoCrop) {\n this.crop();\n }\n\n this.setData(options.data);\n\n if (isFunction(options.ready)) {\n addListener(element, EVENT_READY, options.ready, {\n once: true\n });\n }\n\n dispatchEvent(element, EVENT_READY);\n }\n }, {\n key: \"unbuild\",\n value: function unbuild() {\n if (!this.ready) {\n return;\n }\n\n this.ready = false;\n this.unbind();\n this.resetPreview();\n this.cropper.parentNode.removeChild(this.cropper);\n removeClass(this.element, CLASS_HIDDEN);\n }\n }, {\n key: \"uncreate\",\n value: function uncreate() {\n if (this.ready) {\n this.unbuild();\n this.ready = false;\n this.cropped = false;\n } else if (this.sizing) {\n this.sizingImage.onload = null;\n this.sizing = false;\n this.sized = false;\n } else if (this.reloading) {\n this.xhr.onabort = null;\n this.xhr.abort();\n } else if (this.image) {\n this.stop();\n }\n }\n /**\n * Get the no conflict cropper class.\n * @returns {Cropper} The cropper class.\n */\n\n }], [{\n key: \"noConflict\",\n value: function noConflict() {\n window.Cropper = AnotherCropper;\n return Cropper;\n }\n /**\n * Change the default options.\n * @param {Object} options - The new default options.\n */\n\n }, {\n key: \"setDefaults\",\n value: function setDefaults(options) {\n assign(DEFAULTS, isPlainObject(options) && options);\n }\n }]);\n\n return Cropper;\n }();\n\n assign(Cropper.prototype, render, preview, events, handlers, change, methods);\n\n return Cropper;\n\n})));\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvY3JvcHBlcmpzL2Rpc3QvY3JvcHBlci5qcz9iYWI0Il0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ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gICAgIGxpdHRsZUVuZGlhbiA9IGVuZGlhbm5lc3MgPT09IDB4NDk0OTtcblxuICAgICAgICAgIGlmIChsaXR0bGVFbmRpYW4gfHwgZW5kaWFubmVzcyA9PT0gMHg0RDREXG4gICAgICAgICAgLyogYmlnRW5kaWFuICovXG4gICAgICAgICAgKSB7XG4gICAgICAgICAgICAgIGlmIChkYXRhVmlldy5nZXRVaW50MTYodGlmZk9mZnNldCArIDIsIGxpdHRsZUVuZGlhbikgPT09IDB4MDAyQSkge1xuICAgICAgICAgICAgICAgIHZhciBmaXJzdElGRE9mZnNldCA9IGRhdGFWaWV3LmdldFVpbnQzMih0aWZmT2Zmc2V0ICsgNCwgbGl0dGxlRW5kaWFuKTtcblxuICAgICAgICAgICAgICAgIGlmIChmaXJzdElGRE9mZnNldCA+PSAweDAwMDAwMDA4KSB7XG4gICAgICAgICAgICAgICAgICBpZmRTdGFydCA9IHRpZmZPZmZzZXQgKyBmaXJzdElGRE9mZnNldDtcbiAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH1cbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICBpZiAoaWZkU3RhcnQpIHtcbiAgICAgICAgdmFyIF9sZW5ndGggPSBkYXRhVmlldy5nZXRVaW50MTYoaWZkU3RhcnQsIGxpdHRsZUVuZGlhbik7XG5cbiAgICAgICAgdmFyIF9vZmZzZXQ7XG5cbiAgICAgICAgdmFyIGk7XG5cbiAgICAgICAgZm9yIChpID0gMDsgaSA8IF9sZW5ndGg7IGkgKz0gMSkge1xuICAgICAgICAgIF9vZmZzZXQgPSBpZmRTdGFydCArIGkgKiAxMiArIDI7XG5cbiAgICAgICAgICBpZiAoZGF0YVZpZXcuZ2V0VWludDE2KF9vZmZzZXQsIGxpdHRsZUVuZGlhbikgPT09IDB4MDExMlxuICAgICAgICAgIC8qIE9yaWVudGF0aW9uICovXG4gICAgICAgICAgKSB7XG4gICAgICAgICAgICAgIC8vIDggaXMgd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IHtcbiAgICAgICAgICB0aGlzLnNldENhbnZhc0RhdGEoZm9yRWFjaChjYW52YXNEYXRhLCBmdW5jdGlvbiAobiwgaSkge1xuICAgICAgICAgICAgY2FudmFzRGF0YVtpXSA9IG4gKiByYXRpbztcbiAgICAgICAgICB9KSk7XG4gICAgICAgICAgdGhpcy5zZXRDcm9wQm94RGF0YShmb3JFYWNoKGNyb3BCb3hEYXRhLCBmdW5jdGlvbiAobiwgaSkge1xuICAgICAgICAgICAgY3JvcEJveERhdGFbaV0gPSBuICogcmF0aW87XG4gICAgICAgICAgfSkpO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfSxcbiAgICBkYmxjbGljazogZnVuY3Rpb24gZGJsY2xpY2soKSB7XG4gICAgICBpZiAodGhpcy5kaXNhYmxlZCB8fCB0aGlzLm9wdGlvbnMuZHJhZ01vZGUgPT09IERSQUdfTU9ERV9OT05FKSB7XG4gICAgICAgIHJldHVybjtcbiAgICAgIH1cblxuICAgICAgdGhpcy5zZXREcmFnTW9kZShoYXNDbGFzcyh0aGlzLmRyYWdCb3gsIENMQVNTX0NST1ApID8gRFJBR19NT0RFX01PVkUgOiBEUkFHX01PREVfQ1JPUCk7XG4gICAgfSxcbiAgICB3aGVlbDogZnVuY3Rpb24gd2hlZWwoZXZlbnQpIHtcbiAgICAgIHZhciBfdGhpcyA9IHRoaXM7XG5cbiAgICAgIHZhciByYXRpbyA9IE51bWJlcih0aGlzLm9wdGlvbnMud2hlZWxab29tUmF0aW8pIHx8IDAuMTtcbiAgICAgIHZhciBkZWx0YSA9IDE7XG5cbiAgICAgIGlmICh0aGlzLmRpc2FibGVkKSB7XG4gICAgICAgIHJldHVybjtcbiAgICAgIH1cblxuICAgICAgZXZlbnQucHJldmVudERlZmF1bHQoKTsgLy8gTGltaXQgd2hlZWwgc3BlZWQgdG8gcHJldmVudCB6b29tIHRvbyBmYXN0ICgjMjEpXG5cbiAgICAgIGlmICh0aGlzLndoZWVsaW5nKSB7XG4gICAgICAgIH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2YXIgcG9pbnRlciA9IHBvaW50ZXJzW09iamVjdC5rZXlzKHBvaW50ZXJzKVswXV07XG4gICAgICB2YXIgcmFuZ2UgPSB7XG4gICAgICAgIHg6IHBvaW50ZXIuZW5kWCAtIHBvaW50ZXIuc3RhcnRYLFxuICAgICAgICB5OiBwb2ludGVyLmVuZFkgLSBwb2ludGVyLnN0YXJ0WVxuICAgICAgfTtcblxuICAgICAgdmFyIGNoZWNrID0gZnVuY3Rpb24gY2hlY2soc2lkZSkge1xuICAgICAgICBzd2l0Y2ggKHNpZGUpIHtcbiAgICAgICAgICBjYXNlIEFDVElPTl9FQVNUOlxuICAgICAgICAgICAgaWYgKHJpZ2h0ICsgcmFuZ2UueCA+IG1heFdpZHRoKSB7XG4gICAgICAgICAgICAgIHJhbmdlLnggPSBtYXhXaWR0aCAtIHJpZ2h0O1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBicmVhaztcblxuICAgICAgICAgIGNhc2UgQUNUSU9OX1dFU1Q6XG4gICAgICAgICAgICBpZiAobGVmdCArIHJhbmdlLnggPCBtaW5MZWZ0KSB7XG4gICAgICAgICAgICAgIHJhbmdlLnggPSBtaW5MZWZ0IC0gbGVmdDtcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgICBjYXNlIEFDVElPTl9OT1JUSDpcbiAgICAgICAgICAgIGlmICh0b3AgKyByYW5nZS55IDwgbWluVG9wKSB7XG4gICAgICAgICAgICAgIHJhbmdlLnkgPSBtaW5Ub3AgLSB0b3A7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGJyZWFrO1xuXG4gICAgICAgICAgY2FzZSBBQ1RJT05fU09VVEg6XG4gICAgICAgICAgICBpZiAoYm90dG9tICsgcmFuZ2UueSA+IG1heEhlaWdodCkge1xuICAgICAgICAgICAgICByYW5nZS55ID0gbWF4SGVpZ2h0IC0gYm90dG9tO1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBicmVhaztcbiAgICAgICAgfVxuICAgICAgfTtcblxuICAgICAgc3dpdGNoIChhY3Rpb24pIHtcbiAgICAgICAgLy8gTW92ZSBjcm9wIGJveFxuICAgICAgICBjYXNlIEFDVElPTl9BTEw6XG4gICAgICAgICAgbGVmdCArPSByYW5nZS54O1xuICAgICAgICAgIHRvcCArPSByYW5nZS55O1xuICAgICAgICAgIGJyZWFrO1xuICAgICAgICAvLyBSZXNpemUgY3JvcCBib3hcblxuICAgICAgICBjYXNlIEFDVElPTl9FQVNUOlxuICAgICAgICAgIGlmIChyYW5nZS54ID49IDAgJiYgKHJpZ2h0ID49IG1heFdpZHRoIHx8IGFzcGVjdFJhdGlvICYmICh0b3AgPD0gbWluVG9wIHx8IGJvdHRvbSA+PSBtYXhIZWlnaHQpKSkge1xuICAgICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgY2hlY2soQUNUSU9OX0VBU1QpO1xuICAgICAgICAgIHdpZHRoICs9IHJhbmdlLng7XG5cbiAgICAgICAgICBpZiAod2lkdGggPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fV0VTVDtcbiAgICAgICAgICAgIHdpZHRoID0gLXdpZHRoO1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBpZiAoYXNwZWN0UmF0aW8pIHtcbiAgICAgICAgICAgIGhlaWdodCA9IHdpZHRoIC8gYXNwZWN0UmF0aW87XG4gICAgICAgICAgICB0b3AgKz0gKGNyb3BCb3hEYXRhLmhlaWdodCAtIGhlaWdodCkgLyAyO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGJyZWFrO1xuXG4gICAgICAgIGNhc2UgQUNUSU9OX05PUlRIOlxuICAgICAgICAgIGlmIChyYW5nZS55IDw9IDAgJiYgKHRvcCA8PSBtaW5Ub3AgfHwgYXNwZWN0UmF0aW8gJiYgKGxlZnQgPD0gbWluTGVmdCB8fCByaWdodCA+PSBtYXhXaWR0aCkpKSB7XG4gICAgICAgICAgICByZW5kZXJhYmxlID0gZmFsc2U7XG4gICAgICAgICAgICBicmVhaztcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBjaGVjayhBQ1RJT05fTk9SVEgpO1xuICAgICAgICAgIGhlaWdodCAtPSByYW5nZS55O1xuICAgICAgICAgIHRvcCArPSByYW5nZS55O1xuXG4gICAgICAgICAgaWYgKGhlaWdodCA8IDApIHtcbiAgICAgICAgICAgIGFjdGlvbiA9IEFDVElPTl9TT1VUSDtcbiAgICAgICAgICAgIGhlaWdodCA9IC1oZWlnaHQ7XG4gICAgICAgICAgICB0b3AgLT0gaGVpZ2h0O1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmIChhc3BlY3RSYXRpbykge1xuICAgICAgICAgICAgd2lkdGggPSBoZWlnaHQgKiBhc3BlY3RSYXRpbztcbiAgICAgICAgICAgIGxlZnQgKz0gKGNyb3BCb3hEYXRhLndpZHRoIC0gd2lkdGgpIC8gMjtcbiAgICAgICAgICB9XG5cbiAgICAgICAgICBicmVhaztcblxuICAgICAgICBjYXNlIEFDVElPTl9XRVNUOlxuICAgICAgICAgIGlmIChyYW5nZS54IDw9IDAgJiYgKGxlZnQgPD0gbWluTGVmdCB8fCBhc3BlY3RSYXRpbyAmJiAodG9wIDw9IG1pblRvcCB8fCBib3R0b20gPj0gbWF4SGVpZ2h0KSkpIHtcbiAgICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGNoZWNrKEFDVElPTl9XRVNUKTtcbiAgICAgICAgICB3aWR0aCAtPSByYW5nZS54O1xuICAgICAgICAgIGxlZnQgKz0gcmFuZ2UueDtcblxuICAgICAgICAgIGlmICh3aWR0aCA8IDApIHtcbiAgICAgICAgICAgIGFjdGlvbiA9IEFDVElPTl9FQVNUO1xuICAgICAgICAgICAgd2lkdGggPSAtd2lkdGg7XG4gICAgICAgICAgICBsZWZ0IC09IHdpZHRoO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmIChhc3BlY3RSYXRpbykge1xuICAgICAgICAgICAgaGVpZ2h0ID0gd2lkdGggLyBhc3BlY3RSYXRpbztcbiAgICAgICAgICAgIHRvcCArPSAoY3JvcEJveERhdGEuaGVpZ2h0IC0gaGVpZ2h0KSAvIDI7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgY2FzZSBBQ1RJT05fU09VVEg6XG4gICAgICAgICAgaWYgKHJhbmdlLnkgPj0gMCAmJiAoYm90dG9tID49IG1heEhlaWdodCB8fCBhc3BlY3RSYXRpbyAmJiAobGVmdCA8PSBtaW5MZWZ0IHx8IHJpZ2h0ID49IG1heFdpZHRoKSkpIHtcbiAgICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGNoZWNrKEFDVElPTl9TT1VUSCk7XG4gICAgICAgICAgaGVpZ2h0ICs9IHJhbmdlLnk7XG5cbiAgICAgICAgICBpZiAoaGVpZ2h0IDwgMCkge1xuICAgICAgICAgICAgYWN0aW9uID0gQUNUSU9OX05PUlRIO1xuICAgICAgICAgICAgaGVpZ2h0ID0gLWhlaWdodDtcbiAgICAgICAgICAgIHRvcCAtPSBoZWlnaHQ7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKGFzcGVjdFJhdGlvKSB7XG4gICAgICAgICAgICB3aWR0aCA9IGhlaWdodCAqIGFzcGVjdFJhdGlvO1xuICAgICAgICAgICAgbGVmdCArPSAoY3JvcEJveERhdGEud2lkdGggLSB3aWR0aCkgLyAyO1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGJyZWFrO1xuXG4gICAgICAgIGNhc2UgQUNUSU9OX05PUlRIX0VBU1Q6XG4gICAgICAgICAgaWYgKGFzcGVjdFJhdGlvKSB7XG4gICAgICAgICAgICBpZiAocmFuZ2UueSA8PSAwICYmICh0b3AgPD0gbWluVG9wIHx8IHJpZ2h0ID49IG1heFdpZHRoKSkge1xuICAgICAgICAgICAgICByZW5kZXJhYmxlID0gZmFsc2U7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBjaGVjayhBQ1RJT05fTk9SVEgpO1xuICAgICAgICAgICAgaGVpZ2h0IC09IHJhbmdlLnk7XG4gICAgICAgICAgICB0b3AgKz0gcmFuZ2UueTtcbiAgICAgICAgICAgIHdpZHRoID0gaGVpZ2h0ICogYXNwZWN0UmF0aW87XG4gICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgIGNoZWNrKEFDVElPTl9OT1JUSCk7XG4gICAgICAgICAgICBjaGVjayhBQ1RJT05fRUFTVCk7XG5cbiAgICAgICAgICAgIGlmIChyYW5nZS54ID49IDApIHtcbiAgICAgICAgICAgICAgaWYgKHJpZ2h0IDwgbWF4V2lkdGgpIHtcbiAgICAgICAgICAgICAgICB3aWR0aCArPSByYW5nZS54O1xuICAgICAgICAgICAgICB9IGVsc2UgaWYgKHJhbmdlLnkgPD0gMCAmJiB0b3AgPD0gbWluVG9wKSB7XG4gICAgICAgICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICB3aWR0aCArPSByYW5nZS54O1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBpZiAocmFuZ2UueSA8PSAwKSB7XG4gICAgICAgICAgICAgIGlmICh0b3AgPiBtaW5Ub3ApIHtcbiAgICAgICAgICAgICAgICBoZWlnaHQgLT0gcmFuZ2UueTtcbiAgICAgICAgICAgICAgICB0b3AgKz0gcmFuZ2UueTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgaGVpZ2h0IC09IHJhbmdlLnk7XG4gICAgICAgICAgICAgIHRvcCArPSByYW5nZS55O1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmICh3aWR0aCA8IDAgJiYgaGVpZ2h0IDwgMCkge1xuICAgICAgICAgICAgYWN0aW9uID0gQUNUSU9OX1NPVVRIX1dFU1Q7XG4gICAgICAgICAgICBoZWlnaHQgPSAtaGVpZ2h0O1xuICAgICAgICAgICAgd2lkdGggPSAtd2lkdGg7XG4gICAgICAgICAgICB0b3AgLT0gaGVpZ2h0O1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICB9IGVsc2UgaWYgKHdpZHRoIDwgMCkge1xuICAgICAgICAgICAgYWN0aW9uID0gQUNUSU9OX05PUlRIX1dFU1Q7XG4gICAgICAgICAgICB3aWR0aCA9IC13aWR0aDtcbiAgICAgICAgICAgIGxlZnQgLT0gd2lkdGg7XG4gICAgICAgICAgfSBlbHNlIGlmIChoZWlnaHQgPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fU09VVEhfRUFTVDtcbiAgICAgICAgICAgIGhlaWdodCA9IC1oZWlnaHQ7XG4gICAgICAgICAgICB0b3AgLT0gaGVpZ2h0O1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGJyZWFrO1xuXG4gICAgICAgIGNhc2UgQUNUSU9OX05PUlRIX1dFU1Q6XG4gICAgICAgICAgaWYgKGFzcGVjdFJhdGlvKSB7XG4gICAgICAgICAgICBpZiAocmFuZ2UueSA8PSAwICYmICh0b3AgPD0gbWluVG9wIHx8IGxlZnQgPD0gbWluTGVmdCkpIHtcbiAgICAgICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgICAgICBicmVhaztcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgY2hlY2soQUNUSU9OX05PUlRIKTtcbiAgICAgICAgICAgIGhlaWdodCAtPSByYW5nZS55O1xuICAgICAgICAgICAgdG9wICs9IHJhbmdlLnk7XG4gICAgICAgICAgICB3aWR0aCA9IGhlaWdodCAqIGFzcGVjdFJhdGlvO1xuICAgICAgICAgICAgbGVmdCArPSBjcm9wQm94RGF0YS53aWR0aCAtIHdpZHRoO1xuICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICBjaGVjayhBQ1RJT05fTk9SVEgpO1xuICAgICAgICAgICAgY2hlY2soQUNUSU9OX1dFU1QpO1xuXG4gICAgICAgICAgICBpZiAocmFuZ2UueCA8PSAwKSB7XG4gICAgICAgICAgICAgIGlmIChsZWZ0ID4gbWluTGVmdCkge1xuICAgICAgICAgICAgICAgIHdpZHRoIC09IHJhbmdlLng7XG4gICAgICAgICAgICAgICAgbGVmdCArPSByYW5nZS54O1xuICAgICAgICAgICAgICB9IGVsc2UgaWYgKHJhbmdlLnkgPD0gMCAmJiB0b3AgPD0gbWluVG9wKSB7XG4gICAgICAgICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICB3aWR0aCAtPSByYW5nZS54O1xuICAgICAgICAgICAgICBsZWZ0ICs9IHJhbmdlLng7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGlmIChyYW5nZS55IDw9IDApIHtcbiAgICAgICAgICAgICAgaWYgKHRvcCA+IG1pblRvcCkge1xuICAgICAgICAgICAgICAgIGhlaWdodCAtPSByYW5nZS55O1xuICAgICAgICAgICAgICAgIHRvcCArPSByYW5nZS55O1xuICAgICAgICAgICAgICB9XG4gICAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgICBoZWlnaHQgLT0gcmFuZ2UueTtcbiAgICAgICAgICAgICAgdG9wICs9IHJhbmdlLnk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHdpZHRoIDwgMCAmJiBoZWlnaHQgPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fU09VVEhfRUFTVDtcbiAgICAgICAgICAgIGhlaWdodCA9IC1oZWlnaHQ7XG4gICAgICAgICAgICB3aWR0aCA9IC13aWR0aDtcbiAgICAgICAgICAgIHRvcCAtPSBoZWlnaHQ7XG4gICAgICAgICAgICBsZWZ0IC09IHdpZHRoO1xuICAgICAgICAgIH0gZWxzZSBpZiAod2lkdGggPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fTk9SVEhfRUFTVDtcbiAgICAgICAgICAgIHdpZHRoID0gLXdpZHRoO1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICB9IGVsc2UgaWYgKGhlaWdodCA8IDApIHtcbiAgICAgICAgICAgIGFjdGlvbiA9IEFDVElPTl9TT1VUSF9XRVNUO1xuICAgICAgICAgICAgaGVpZ2h0ID0gLWhlaWdodDtcbiAgICAgICAgICAgIHRvcCAtPSBoZWlnaHQ7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgY2FzZSBBQ1RJT05fU09VVEhfV0VTVDpcbiAgICAgICAgICBpZiAoYXNwZWN0UmF0aW8pIHtcbiAgICAgICAgICAgIGlmIChyYW5nZS54IDw9IDAgJiYgKGxlZnQgPD0gbWluTGVmdCB8fCBib3R0b20gPj0gbWF4SGVpZ2h0KSkge1xuICAgICAgICAgICAgICByZW5kZXJhYmxlID0gZmFsc2U7XG4gICAgICAgICAgICAgIGJyZWFrO1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBjaGVjayhBQ1RJT05fV0VTVCk7XG4gICAgICAgICAgICB3aWR0aCAtPSByYW5nZS54O1xuICAgICAgICAgICAgbGVmdCArPSByYW5nZS54O1xuICAgICAgICAgICAgaGVpZ2h0ID0gd2lkdGggLyBhc3BlY3RSYXRpbztcbiAgICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgY2hlY2soQUNUSU9OX1NPVVRIKTtcbiAgICAgICAgICAgIGNoZWNrKEFDVElPTl9XRVNUKTtcblxuICAgICAgICAgICAgaWYgKHJhbmdlLnggPD0gMCkge1xuICAgICAgICAgICAgICBpZiAobGVmdCA+IG1pbkxlZnQpIHtcbiAgICAgICAgICAgICAgICB3aWR0aCAtPSByYW5nZS54O1xuICAgICAgICAgICAgICAgIGxlZnQgKz0gcmFuZ2UueDtcbiAgICAgICAgICAgICAgfSBlbHNlIGlmIChyYW5nZS55ID49IDAgJiYgYm90dG9tID49IG1heEhlaWdodCkge1xuICAgICAgICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgd2lkdGggLT0gcmFuZ2UueDtcbiAgICAgICAgICAgICAgbGVmdCArPSByYW5nZS54O1xuICAgICAgICAgICAgfVxuXG4gICAgICAgICAgICBpZiAocmFuZ2UueSA+PSAwKSB7XG4gICAgICAgICAgICAgIGlmIChib3R0b20gPCBtYXhIZWlnaHQpIHtcbiAgICAgICAgICAgICAgICBoZWlnaHQgKz0gcmFuZ2UueTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgaGVpZ2h0ICs9IHJhbmdlLnk7XG4gICAgICAgICAgICB9XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgaWYgKHdpZHRoIDwgMCAmJiBoZWlnaHQgPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fTk9SVEhfRUFTVDtcbiAgICAgICAgICAgIGhlaWdodCA9IC1oZWlnaHQ7XG4gICAgICAgICAgICB3aWR0aCA9IC13aWR0aDtcbiAgICAgICAgICAgIHRvcCAtPSBoZWlnaHQ7XG4gICAgICAgICAgICBsZWZ0IC09IHdpZHRoO1xuICAgICAgICAgIH0gZWxzZSBpZiAod2lkdGggPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fU09VVEhfRUFTVDtcbiAgICAgICAgICAgIHdpZHRoID0gLXdpZHRoO1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICB9IGVsc2UgaWYgKGhlaWdodCA8IDApIHtcbiAgICAgICAgICAgIGFjdGlvbiA9IEFDVElPTl9OT1JUSF9XRVNUO1xuICAgICAgICAgICAgaGVpZ2h0ID0gLWhlaWdodDtcbiAgICAgICAgICAgIHRvcCAtPSBoZWlnaHQ7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgYnJlYWs7XG5cbiAgICAgICAgY2FzZSBBQ1RJT05fU09VVEhfRUFTVDpcbiAgICAgICAgICBpZiAoYXNwZWN0UmF0aW8pIHtcbiAgICAgICAgICAgIGlmIChyYW5nZS54ID49IDAgJiYgKHJpZ2h0ID49IG1heFdpZHRoIHx8IGJvdHRvbSA+PSBtYXhIZWlnaHQpKSB7XG4gICAgICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgICB9XG5cbiAgICAgICAgICAgIGNoZWNrKEFDVElPTl9FQVNUKTtcbiAgICAgICAgICAgIHdpZHRoICs9IHJhbmdlLng7XG4gICAgICAgICAgICBoZWlnaHQgPSB3aWR0aCAvIGFzcGVjdFJhdGlvO1xuICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICBjaGVjayhBQ1RJT05fU09VVEgpO1xuICAgICAgICAgICAgY2hlY2soQUNUSU9OX0VBU1QpO1xuXG4gICAgICAgICAgICBpZiAocmFuZ2UueCA+PSAwKSB7XG4gICAgICAgICAgICAgIGlmIChyaWdodCA8IG1heFdpZHRoKSB7XG4gICAgICAgICAgICAgICAgd2lkdGggKz0gcmFuZ2UueDtcbiAgICAgICAgICAgICAgfSBlbHNlIGlmIChyYW5nZS55ID49IDAgJiYgYm90dG9tID49IG1heEhlaWdodCkge1xuICAgICAgICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICAgICAgd2lkdGggKz0gcmFuZ2UueDtcbiAgICAgICAgICAgIH1cblxuICAgICAgICAgICAgaWYgKHJhbmdlLnkgPj0gMCkge1xuICAgICAgICAgICAgICBpZiAoYm90dG9tIDwgbWF4SGVpZ2h0KSB7XG4gICAgICAgICAgICAgICAgaGVpZ2h0ICs9IHJhbmdlLnk7XG4gICAgICAgICAgICAgIH1cbiAgICAgICAgICAgIH0gZWxzZSB7XG4gICAgICAgICAgICAgIGhlaWdodCArPSByYW5nZS55O1xuICAgICAgICAgICAgfVxuICAgICAgICAgIH1cblxuICAgICAgICAgIGlmICh3aWR0aCA8IDAgJiYgaGVpZ2h0IDwgMCkge1xuICAgICAgICAgICAgYWN0aW9uID0gQUNUSU9OX05PUlRIX1dFU1Q7XG4gICAgICAgICAgICBoZWlnaHQgPSAtaGVpZ2h0O1xuICAgICAgICAgICAgd2lkdGggPSAtd2lkdGg7XG4gICAgICAgICAgICB0b3AgLT0gaGVpZ2h0O1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICB9IGVsc2UgaWYgKHdpZHRoIDwgMCkge1xuICAgICAgICAgICAgYWN0aW9uID0gQUNUSU9OX1NPVVRIX1dFU1Q7XG4gICAgICAgICAgICB3aWR0aCA9IC13aWR0aDtcbiAgICAgICAgICAgIGxlZnQgLT0gd2lkdGg7XG4gICAgICAgICAgfSBlbHNlIGlmIChoZWlnaHQgPCAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSBBQ1RJT05fTk9SVEhfRUFTVDtcbiAgICAgICAgICAgIGhlaWdodCA9IC1oZWlnaHQ7XG4gICAgICAgICAgICB0b3AgLT0gaGVpZ2h0O1xuICAgICAgICAgIH1cblxuICAgICAgICAgIGJyZWFrO1xuICAgICAgICAvLyBNb3ZlIGNhbnZhc1xuXG4gICAgICAgIGNhc2UgQUNUSU9OX01PVkU6XG4gICAgICAgICAgdGhpcy5tb3ZlKHJhbmdlLngsIHJhbmdlLnkpO1xuICAgICAgICAgIHJlbmRlcmFibGUgPSBmYWxzZTtcbiAgICAgICAgICBicmVhaztcbiAgICAgICAgLy8gWm9vbSBjYW52YXNcblxuICAgICAgICBjYXNlIEFDVElPTl9aT09NOlxuICAgICAgICAgIHRoaXMuem9vbShnZXRNYXhab29tUmF0aW8ocG9pbnRlcnMpLCBldmVudCk7XG4gICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgIGJyZWFrO1xuICAgICAgICAvLyBDcmVhdGUgY3JvcCBib3hcblxuICAgICAgICBjYXNlIEFDVElPTl9DUk9QOlxuICAgICAgICAgIGlmICghcmFuZ2UueCB8fCAhcmFuZ2UueSkge1xuICAgICAgICAgICAgcmVuZGVyYWJsZSA9IGZhbHNlO1xuICAgICAgICAgICAgYnJlYWs7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgb2Zmc2V0ID0gZ2V0T2Zmc2V0KHRoaXMuY3JvcHBlcik7XG4gICAgICAgICAgbGVmdCA9IHBvaW50ZXIuc3RhcnRYIC0gb2Zmc2V0LmxlZnQ7XG4gICAgICAgICAgdG9wID0gcG9pbnRlci5zdGFydFkgLSBvZmZzZXQudG9wO1xuICAgICAgICAgIHdpZHRoID0gY3JvcEJveERhdGEubWluV2lkdGg7XG4gICAgICAgICAgaGVpZ2h0ID0gY3JvcEJveERhdGEubWluSGVpZ2h0O1xuXG4gICAgICAgICAgaWYgKHJhbmdlLnggPiAwKSB7XG4gICAgICAgICAgICBhY3Rpb24gPSByYW5nZS55ID4gMCA/IEFDVElPTl9TT1VUSF9FQVNUIDogQUNUSU9OX05PUlRIX0VBU1Q7XG4gICAgICAgICAgfSBlbHNlIGlmIChyYW5nZS54IDwgMCkge1xuICAgICAgICAgICAgbGVmdCAtPSB3aWR0aDtcbiAgICAgICAgICAgIGFjdG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uXG4gICAgICogQHJldHVybnMge0Nyb3BwZXJ9IHRoaXNcbiAgICAgKi9cbiAgICByZXBsYWNlOiBmdW5jdGlvbiByZXBsYWNlKHVybCkge1xuICAgICAgdmFyIGhhc1NhbWVTaXplID0gYXJndW1lbnRzLmxlbmd0aCA+IDEgJiYgYXJndW1lbnRzWzFdICE9PSB1bmRlZmluZWQgPyBhcmd1bWVudHNbMV0gOiBmYWxzZTtcblxuICAgICAgaWYgKCF0aGlzLmRpc2FibGVkICYmIHVybCkge1xuICAgICAgICBpZiAodGhpcy5pc0ltZykge1xuICAgICAgICAgIHRoaXMuZWxlbWVudC5zcmMgPSB1cmw7XG4gICAgICAgIH1cblxuICAgICAgICBpZiAoaGFzU2FtZVNpemUpIHtcbiAgICAgICAgICB0aGlzLnVybCA9IHVybDtcbiAgICAgICAgICB0aGlzLmltYWdlLnNyYyA9IHVybDtcblxuICAgICAgICAgIGlmICh0aGlzLnJlYWR5KSB7XG4gICAgICAgICAgICB0aGlzLnZpZXdCb3hJbWFnZS5zcmMgPSB1cmw7XG4gICAgICAgICAgICBmb3JFYWNoKHRoaXMucHJldmlld3MsIGZ1bmN0aW9uIChlbGVtZW50KSB7XG4gICAgICAgICAgICAgIGVsZW1lbnQuZ2V0RWxlbWVudHNCeVRhZ05hbWUoJ2ltZycpWzBdLnNyYyA9IHVybDtcbiAgICAgICAgICAgIH0pO1xuICAgICAgICAgIH1cbiAgICAgICAgfSBlbHNlIHtcbiAgICAgICAgICBpZiAodGhpcy5pc0ltZykge1xuICAgICAgICAgICAgdGhpcy5yZXBsYWNlZCA9IHRydWU7XG4gICAgICAgICAgfVxuXG4gICAgICAgICAgdGhpcy5vcHRpb25zLmRhdGEgPSBudWxsO1xuICAgICAgICAgIHRoaXMudW5jcmVhdGUoKTtcbiAgICAgICAgICB0aGlzLmxvYWQodXJsKTtcbiAgICAgICAgfVxuICAgICAgfVxuXG4gICAgICByZXR1cm4gdGhpcztcbiAgICB9LFxuICAgIC8vIEVuYWJ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XNEYXRhLmhlaWdodCA9IGRhdGEud2lkdGggLyBhc3BlY3RSYXRpbztcbiAgICAgICAgfSBlbHNlIGlmIChpc051bWJlcihkYXRhLmhlaWdodCkpIHtcbiAgICAgICAgICBjYW52YXNEYXRhLmhlaWdodCA9IGRhdGEuaGVpZ2h0O1xuICAgICAgICAgIGNhbnZhc0RhdGEud2lkdGggPSBkYXRhLmhlaWdodCAqIGFzcGVjdFJhdGlvO1xuICAgICAgICB9XG5cbiAgICAgICAgdGhpcy5yZW5kZXJDYW52YXModHJ1ZSk7XG4gICAgICB9XG5cbiAgICAgIHJldHVybiB0aGlzO1xuICAgIH0sXG5cbiAgICAvKipcbiAgICAgKiBHZXQgdGhlIGNyb3AgYm94IHBvc2l0aW9uIGFuZCBzaXplIGRhdGEuXG4gICAgICogQHJldHVybnMge09iamVjdH0gVGhlIHJlc3VsdCBjcm9wIGJveCBkYXRhLlxuICAgICAqL1xuICAgIGdldENyb3BCb3hEYXRhOiBmdW5jdGlvbiBnZXRDcm9wQm94RGF0YSgpIHtcbiAgICAgIHZhciBjcm9wQm94RGF0YSA9IHRoaXMuY3JvcEJveERhdGE7XG4gICAgICB2YXIgZGF0YTtcblxuICAgICAgaWYgKHRoaXMucmVhZHkgJiYgdGhpcy5jcm9wcGVkKSB7XG4gICAgICAgIGRhdGEgPSB7XG4gICAgICAgICAgbGVmdDogY3JvcEJveERhdGEubGVmdCxcbiAgICAgICAgICB0b3A6IGNyb3BCb3hEYXRhLnRvcCxcbiAgICAgICAgICB3aWR0aDogY3JvcEJveERhdGEud2lkdGgsXG4gICAgICAgICAgaGVpZ2h0OiBjcm9wQm94RGF0YS5oZWlnaHRcbiAgICAgICAgfTtcbiAgICAgIH1cblxuICAgICAgcmV0dXJuIGRhdGEgfHwge307XG4gICAgfSxcblxuICAgIC8qKlxuICAgICAqIFNldCB0aGUgY3JvcCBib3ggcG9zaXRpb24gYW5kIHNpemUgd2l0aCBuZXcgZGF0YS5cbiAgICAgKiBAcGFyYW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cm9wKSB7XG4gICAgICAgICAgdGhpcy5jcm9wKCk7XG4gICAgICAgIH1cblxuICAgICAgICB0aGlzLnNldERhdGEob3B0aW9ucy5kYXRhKTtcblxuICAgICAgICBpZiAoaXNGdW5jdGlvbihvcHRpb25zLnJlYWR5KSkge1xuICAgICAgICAgIGFkZExpc3RlbmVyKGVsZW1lbnQsIEVWRU5UX1JFQURZLCBvcHRpb25zLnJlYWR5LCB7XG4gICAgICAgICAgICBvbmNlOiB0cnVlXG4gICAgICAgICAgfSk7XG4gICAgICAgIH1cblxuICAgICAgICBkaXNwYXRjaEV2ZW50KGVsZW1lbnQsIEVWRU5UX1JFQURZKTtcbiAgICAgIH1cbiAgICB9LCB7XG4gICAgICBrZXk6IFwidW5idWlsZFwiLFxuICAgICAgdmFsdWU6IGZ1bmN0aW9uIHVuYnVpbGQoKSB7XG4gICAgICAgIGlmICghdGhpcy5yZWFkeSkge1xuICAgICAgICAgIHJldHVybjtcbiAgICAgICAgfVxuXG4gICAgICAgIHRoaXMucmVhZHkgPSBmYWxzZTtcbiAgICAgICAgdGhpcy51bmJpbmQoKTtcbiAgICAgICAgdGhpcy5yZXNldFByZXZpZXcoKTtcbiAgICAgICAgdGhpcy5jcm9wcGVyLnBhcmVudE5vZGUucmVtb3ZlQ2hpbGQodGhpcy5jcm9wcGVyKTtcbiAgICAgICAgcmVtb3ZlQ2xhc3ModGhpcy5lbGVtZW50LCBDTEFTU19ISURERU4pO1xuICAgICAgfVxuICAgIH0sIHtcbiAgICAgIGtleTogXCJ1bmNyZWF0ZVwiLFxuICAgICAgdmFsdWU6IGZ1bmN0aW9uIHVuY3JlYXRlKCkge1xuICAgICAgICBpZiAodGhpcy5yZWFkeSkge1xuICAgICAgICAgIHRoaXMudW5idWlsZCgpO1xuICAgICAgICAgIHRoaXMucmVhZHkgPSBmYWxzZTtcbiAgICAgICAgICB0aGlzLmNyb3BwZWQgPSBmYWxzZTtcbiAgICAgICAgfSBlbHNlIGlmICh0aGlzLnNpemlu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fVxuICAgIH1dKTtcblxuICAgIHJldHVybiBDcm9wcGVyO1xuICB9KCk7XG5cbiAgYXNzaWduKENyb3BwZXIucHJvdG90eXBlLCByZW5kZXIsIHByZXZpZXcsIGV2ZW50cywgaGFuZGxlcnMsIGNoYW5nZSwgbWV0aG9kcyk7XG5cbiAgcmV0dXJuIENyb3BwZXI7XG5cbn0pKSk7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/cropperjs/dist/cropper.js\n"); /***/ }), /***/ "./node_modules/lodash/_Symbol.js": /*!****************************************!*\ !*** ./node_modules/lodash/_Symbol.js ***! \****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var root = __webpack_require__(/*! ./_root */ \"./node_modules/lodash/_root.js\");\n\n/** Built-in value references. */\nvar Symbol = root.Symbol;\n\nmodule.exports = Symbol;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19TeW1ib2wuanM/OWU2OSJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxXQUFXLG1CQUFPLENBQUMsK0NBQVM7O0FBRTVCO0FBQ0E7O0FBRUEiLCJmaWxlIjoiLi9ub2RlX21vZHVsZXMvbG9kYXNoL19TeW1ib2wuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgcm9vdCA9IHJlcXVpcmUoJy4vX3Jvb3QnKTtcblxuLyoqIEJ1aWx0LWluIHZhbHVlIHJlZmVyZW5jZXMuICovXG52YXIgU3ltYm9sID0gcm9vdC5TeW1ib2w7XG5cbm1vZHVsZS5leHBvcnRzID0gU3ltYm9sO1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/lodash/_Symbol.js\n"); /***/ }), /***/ "./node_modules/lodash/_baseGetTag.js": /*!********************************************!*\ !*** ./node_modules/lodash/_baseGetTag.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var Symbol = __webpack_require__(/*! ./_Symbol */ \"./node_modules/lodash/_Symbol.js\"),\n getRawTag = __webpack_require__(/*! ./_getRawTag */ \"./node_modules/lodash/_getRawTag.js\"),\n objectToString = __webpack_require__(/*! ./_objectToString */ \"./node_modules/lodash/_objectToString.js\");\n\n/** `Object#toString` result references. */\nvar nullTag = '[object Null]',\n undefinedTag = '[object Undefined]';\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\nfunction baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n}\n\nmodule.exports = baseGetTag;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19iYXNlR2V0VGFnLmpzPzM3MjkiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsYUFBYSxtQkFBTyxDQUFDLG1EQUFXO0FBQ2hDLGdCQUFnQixtQkFBTyxDQUFDLHlEQUFjO0FBQ3RDLHFCQUFxQixtQkFBTyxDQUFDLG1FQUFtQjs7QUFFaEQ7QUFDQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQSxXQUFXLEVBQUU7QUFDYixhQUFhLE9BQU87QUFDcEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL2xvZGFza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IDogb2JqZWN0VG9TdHJpbmcodmFsdWUpO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IGJhc2VHZXRUYWc7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/_baseGetTag.js\n"); /***/ }), /***/ "./node_modules/lodash/_freeGlobal.js": /*!********************************************!*\ !*** ./node_modules/lodash/_freeGlobal.js ***! \********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("/* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */\nvar freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\nmodule.exports = freeGlobal;\n\n/* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../webpack/buildin/global.js */ \"./node_modules/webpack/buildin/global.js\")))//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19mcmVlR2xvYmFsLmpzPzU4NWEiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7QUFDQTs7QUFFQSIsImZpbGUiOiIuL25vZGVfbW9kdWxlcy9sb2Rhc2gvX2ZyZWVHbG9iYWwuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKiogRGV0ZWN0IGZyZWUgdmFyaWFibGUgYGdsb2JhbGAgZnJvbSBOb2RlLmpzLiAqL1xudmFyIGZyZWVHbG9iYWwgPSB0eXBlb2YgZ2xvYmFsID09ICdvYmplY3QnICYmIGdsb2JhbCAmJiBnbG9iYWwuT2JqZWN0ID09PSBPYmplY3QgJiYgZ2xvYmFsO1xuXG5tb2R1bGUuZXhwb3J0cyA9IGZyZWVHbG9iYWw7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/_freeGlobal.js\n"); /***/ }), /***/ "./node_modules/lodash/_getRawTag.js": /*!*******************************************!*\ !*** ./node_modules/lodash/_getRawTag.js ***! \*******************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var Symbol = __webpack_require__(/*! ./_Symbol */ \"./node_modules/lodash/_Symbol.js\");\n\n/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/** Used to check objects for own properties. */\nvar hasOwnProperty = objectProto.hasOwnProperty;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/** Built-in value references. */\nvar symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n/**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\nfunction getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n}\n\nmodule.exports = getRawTag;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19nZXRSYXdUYWcuanM/MDBmZCJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxhQUFhLG1CQUFPLENBQUMsbURBQVc7O0FBRWhDO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLFdBQVcsRUFBRTtBQUNiLGFBQWEsT0FBTztBQUNwQjtBQUNBO0FBQ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yp9IHZhbHVlIFRoZSB2YWx1ZSB0byBxdWVyeS5cbiAqIEByZXR1cm5zIHtzdHJpbmd9IFJldHVybnMgdGhlIHJhdyBgdG9TdHJpbmdUYWdgLlxuICovXG5mdW5jdGlvbiBnZXRSYXdUYWcodmFsdWUpIHtcbiAgdmFyIGlzT3duID0gaGFzT3duUHJvcGVydHkuY2FsbCh2YWx1ZSwgc3ltVG9TdHJpbmdUYWcpLFxuICAgICAgdGFnID0gdmFsdWVbc3ltVG9TdHJpbmdUYWddO1xuXG4gIHRyeSB7XG4gICAgdmFsdWVbc3ltVG9TdHJpbmdUYWddID0gdW5kZWZpbmVkO1xuICAgIHZhciB1bm1hc2tlZCA9IHRydWU7XG4gIH0gY2F0Y2ggKGUpIHt9XG5cbiAgdmFyIHJlc3VsdCA9IG5hdGl2ZU9iamVjdFRvU3RyaW5nLmNhbGwodmFsdWUpO1xuICBpZiAodW5tYXNrZWQpIHtcbiAgICBpZiAoaXNPd24pIHtcbiAgICAgIHZhbHVlW3N5bVRvU3RyaW5nVGFnXSA9IHRhZztcbiAgICB9IGVsc2Uge1xuICAgICAgZGVsZXRlIHZhbHVlW3N5bVRvU3RyaW5nVGFnXTtcbiAgICB9XG4gIH1cbiAgcmV0dXJuIHJlc3VsdDtcbn1cblxubW9kdWxlLmV4cG9ydHMgPSBnZXRSYXdUYWc7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/_getRawTag.js\n"); /***/ }), /***/ "./node_modules/lodash/_objectToString.js": /*!************************************************!*\ !*** ./node_modules/lodash/_objectToString.js ***! \************************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("/** Used for built-in method references. */\nvar objectProto = Object.prototype;\n\n/**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\nvar nativeObjectToString = objectProto.toString;\n\n/**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\nfunction objectToString(value) {\n return nativeObjectToString.call(value);\n}\n\nmodule.exports = objectToString;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19vYmplY3RUb1N0cmluZy5qcz8yOWYzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsV0FBVyxFQUFFO0FBQ2IsYUFBYSxPQUFPO0FBQ3BCO0FBQ0E7QUFDQTtBQUNBOztBQUVBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL2xvZGFzaC9fb2JqZWN0VG9TdHJpbmcuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyIvKiogVXNlZCBmb3IgYnVpbHQtaW4gbWV0aG9kIHJlZmVyZW5jZXMuICovXG52YXIgb2JqZWN0UHJvdG8gPSBPYmplY3QucHJvdG90eXBlO1xuXG4vKipcbiAqIFVzZWQgdG8gcmVzb2x2ZSB0aGVcbiAqIFtgdG9TdHJpbmdUYWdgXShodHRwOi8vZWNtYS1pbnRlcm5hdGlvbmFsLm9yZy9lY21hLTI2Mi83LjAvI3NlYy1vYmplY3QucHJvdG90eXBlLnRvc3RyaW5nKVxuICogb2YgdmFsdWVzLlxuICovXG52YXIgbmF0aXZlT2JqZWN0VG9TdHJpbmcgPSBvYmplY3RQcm90by50b1N0cmluZztcblxuLyoqXG4gKiBDb252ZXJ0cyBgdmFsdWVgIHRvIGEgc3RyaW5nIHVzaW5nIGBPYmplY3QucHJvdG90eXBlLnRvU3RyaW5nYC5cbiAqXG4gKiBAcHJpdmF0ZVxuICogQHBhcmFtIHsqfSB2YWx1ZSBUaGUgdmFsdWUgdG8gY29udmVydC5cbiAqIEByZXR1cm5zIHtzdHJpbmd9IFJldHVybnMgdGhlIGNvbnZlcnRlZCBzdHJpbmcuXG4gKi9cbmZ1bmN0aW9uIG9iamVjdFRvU3RyaW5nKHZhbHVlKSB7XG4gIHJldHVybiBuYXRpdmVPYmplY3RUb1N0cmluZy5jYWxsKHZhbHVlKTtcbn1cblxubW9kdWxlLmV4cG9ydHMgPSBvYmplY3RUb1N0cmluZztcbiJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./node_modules/lodash/_objectToString.js\n"); /***/ }), /***/ "./node_modules/lodash/_root.js": /*!**************************************!*\ !*** ./node_modules/lodash/_root.js ***! \**************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var freeGlobal = __webpack_require__(/*! ./_freeGlobal */ \"./node_modules/lodash/_freeGlobal.js\");\n\n/** Detect free variable `self`. */\nvar freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n/** Used as a reference to the global object. */\nvar root = freeGlobal || freeSelf || Function('return this')();\n\nmodule.exports = root;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL19yb290LmpzPzJiM2UiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsaUJBQWlCLG1CQUFPLENBQUMsMkRBQWU7O0FBRXhDO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQSIsImZpbGUiOiIuL25vZGVfbW9kdWxlcy9sb2Rhc2gvX3Jvb3QuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgZnJlZUdsb2JhbCA9IHJlcXVpcmUoJy4vX2ZyZWVHbG9iYWwnKTtcblxuLyoqIERldGVjdCBmcmVlIHZhcmlhYmxlIGBzZWxmYC4gKi9cbnZhciBmcmVlU2VsZiA9IHR5cGVvZiBzZWxmID09ICdvYmplY3QnICYmIHNlbGYgJiYgc2VsZi5PYmplY3QgPT09IE9iamVjdCAmJiBzZWxmO1xuXG4vKiogVXNlZCBhcyBhIHJlZmVyZW5jZSB0byB0aGUgZ2xvYmFsIG9iamVjdC4gKi9cbnZhciByb290ID0gZnJlZUdsb2JhbCB8fCBmcmVlU2VsZiB8fCBGdW5jdGlvbigncmV0dXJuIHRoaXMnKSgpO1xuXG5tb2R1bGUuZXhwb3J0cyA9IHJvb3Q7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/_root.js\n"); /***/ }), /***/ "./node_modules/lodash/debounce.js": /*!*****************************************!*\ !*** ./node_modules/lodash/debounce.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var isObject = __webpack_require__(/*! ./isObject */ \"./node_modules/lodash/isObject.js\"),\n now = __webpack_require__(/*! ./now */ \"./node_modules/lodash/now.js\"),\n toNumber = __webpack_require__(/*! ./toNumber */ \"./node_modules/lodash/toNumber.js\");\n\n/** Error message constants. */\nvar FUNC_ERROR_TEXT = 'Expected a function';\n\n/* Built-in method references for those with the same name as other `lodash` methods. */\nvar nativeMax = Math.max,\n nativeMin = Math.min;\n\n/**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\nfunction debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n}\n\nmodule.exports = debounce;\n//# sourceURL=[module]\n//# sour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0aW1lcklkID0gc2V0VGltZW91dCh0aW1lckV4cGlyZWQsIHdhaXQpO1xuICAgICAgICByZXR1cm4gaW52b2tlRnVuYyhsYXN0Q2FsbFRpbWUpO1xuICAgICAgfVxuICAgIH1cbiAgICBpZiAodGltZXJJZCA9PT0gdW5kZWZpbmVkKSB7XG4gICAgICB0aW1lcklkID0gc2V0VGltZW91dCh0aW1lckV4cGlyZWQsIHdhaXQpO1xuICAgIH1cbiAgICByZXR1cm4gcmVzdWx0O1xuICB9XG4gIGRlYm91bmNlZC5jYW5jZWwgPSBjYW5jZWw7XG4gIGRlYm91bmNlZC5mbHVzaCA9IGZsdXNoO1xuICByZXR1cm4gZGVib3VuY2VkO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IGRlYm91bmNlO1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/lodash/debounce.js\n"); /***/ }), /***/ "./node_modules/lodash/isObject.js": /*!*****************************************!*\ !*** ./node_modules/lodash/isObject.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("/**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\nfunction isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n}\n\nmodule.exports = isObject;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL2l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IDNdKTtcbiAqIC8vID0+IHRydWVcbiAqXG4gKiBfLmlzT2JqZWN0KF8ubm9vcCk7XG4gKiAvLyA9PiB0cnVlXG4gKlxuICogXy5pc09iamVjdChudWxsKTtcbiAqIC8vID0+IGZhbHNlXG4gKi9cbmZ1bmN0aW9uIGlzT2JqZWN0KHZhbHVlKSB7XG4gIHZhciB0eXBlID0gdHlwZW9mIHZhbHVlO1xuICByZXR1cm4gdmFsdWUgIT0gbnVsbCAmJiAodHlwZSA9PSAnb2JqZWN0JyB8fCB0eXBlID09ICdmdW5jdGlvbicpO1xufVxuXG5tb2R1bGUuZXhwb3J0cyA9IGlzT2JqZWN0O1xuIl0sInNvdXJjZVJvb3QiOiIifQ==\n//# sourceURL=webpack-internal:///./node_modules/lodash/isObject.js\n"); /***/ }), /***/ "./node_modules/lodash/isObjectLike.js": /*!*********************************************!*\ !*** ./node_modules/lodash/isObjectLike.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports) { eval("/**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\nfunction isObjectLike(value) {\n return value != null && typeof value == 'object';\n}\n\nmodule.exports = isObjectLike;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL2lzT2JqZWN0TGlrZS5qcz8xMzEwIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUN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1ZSA9PSAnb2JqZWN0Jztcbn1cblxubW9kdWxlLmV4cG9ydHMgPSBpc09iamVjdExpa2U7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/isObjectLike.js\n"); /***/ }), /***/ "./node_modules/lodash/isSymbol.js": /*!*****************************************!*\ !*** ./node_modules/lodash/isSymbol.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var baseGetTag = __webpack_require__(/*! ./_baseGetTag */ \"./node_modules/lodash/_baseGetTag.js\"),\n isObjectLike = __webpack_require__(/*! ./isObjectLike */ \"./node_modules/lodash/isObjectLike.js\");\n\n/** `Object#toString` result references. */\nvar symbolTag = '[object Symbol]';\n\n/**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\nfunction isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n}\n\nmodule.exports = isSymbol;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL2lzU3ltYm9sLmpzP2ZmZDYiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsaUJBQWlCLG1CQUFPLENBQUMsMkRBQWU7QUFDeEMsbUJBQW1CLG1CQUFPLENBQUMsNkRBQWdCOztBQUUzQztBQUNBOztBQUVBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsV0FBVyxFQUFFO0FBQ2IsYUFBYSxRQUFRO0FBQ3JCO0FBQ0E7QUFDQTtBQUNBO0F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nRzID0gaXNTeW1ib2w7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/isSymbol.js\n"); /***/ }), /***/ "./node_modules/lodash/now.js": /*!************************************!*\ !*** ./node_modules/lodash/now.js ***! \************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var root = __webpack_require__(/*! ./_root */ \"./node_modules/lodash/_root.js\");\n\n/**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\nvar now = function() {\n return root.Date.now();\n};\n\nmodule.exports = now;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL25vdy5qcz80MDhjIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLFdBQVcsbUJBQU8sQ0FBQywrQ0FBUzs7QUFFNUI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGFBQWEsT0FBTztBQUNwQjtBQUNBO0FBQ0E7QUFDQTtBQUNBLElBQUk7QUFDSjtBQUNBO0FBQ0E7QUFDQTtBQUNBOztBQUVBIiwiZmlsZSI6Ii4vbm9kZV9tb2R1bGVzL2xvZGFzaC9ub3cuanMuanMiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgcm9vdCA9IHJlcXVpcmUoJy4vX3Jvb3QnKTtcblxuLyoqXG4gKiBHZXRzIHRoZSB0aW1lc3RhbXAgb2YgdGhlIG51bWJlciBvZiBtaWxsaXNlY29uZHMgdGhhdCBoYXZlIGVsYXBzZWQgc2luY2VcbiAqIHRoZSBVbml4IGVwb2NoICgxIEphbnVhcnkgMTk3MCAwMDowMDowMCBVVEMpLlxuICpcbiAqIEBzdGF0aWNcbiAqIEBtZW1iZXJPZiBfXG4gKiBAc2luY2UgMi40LjBcbiAqIEBjYXRlZ29yeSBEYXRlXG4gKiBAcmV0dXJucyB7bnVtYmVyfSBSZXR1cm5zIHRoZSB0aW1lc3RhbXAuXG4gKiBAZXhhbXBsZVxuICpcbiAqIF8uZGVmZXIoZnVuY3Rpb24oc3RhbXApIHtcbiAqICAgY29uc29sZS5sb2coXy5ub3coKSAtIHN0YW1wKTtcbiAqIH0sIF8ubm93KCkpO1xuICogLy8gPT4gTG9ncyB0aGUgbnVtYmVyIG9mIG1pbGxpc2Vjb25kcyBpdCB0b29rIGZvciB0aGUgZGVmZXJyZWQgaW52b2NhdGlvbi5cbiAqL1xudmFyIG5vdyA9IGZ1bmN0aW9uKCkge1xuICByZXR1cm4gcm9vdC5EYXRlLm5vdygpO1xufTtcblxubW9kdWxlLmV4cG9ydHMgPSBub3c7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/now.js\n"); /***/ }), /***/ "./node_modules/lodash/toNumber.js": /*!*****************************************!*\ !*** ./node_modules/lodash/toNumber.js ***! \*****************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("var isObject = __webpack_require__(/*! ./isObject */ \"./node_modules/lodash/isObject.js\"),\n isSymbol = __webpack_require__(/*! ./isSymbol */ \"./node_modules/lodash/isSymbol.js\");\n\n/** Used as references for various `Number` constants. */\nvar NAN = 0 / 0;\n\n/** Used to match leading and trailing whitespace. */\nvar reTrim = /^\\s+|\\s+$/g;\n\n/** Used to detect bad signed hexadecimal string values. */\nvar reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n/** Used to detect binary string values. */\nvar reIsBinary = /^0b[01]+$/i;\n\n/** Used to detect octal string values. */\nvar reIsOctal = /^0o[0-7]+$/i;\n\n/** Built-in method references without a dependency on `root`. */\nvar freeParseInt = parseInt;\n\n/**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\nfunction toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n}\n\nmodule.exports = toNumber;\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbG9kYXNoL3RvTnVtYmVyLmpzP2I0YjAiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsZUFBZSxtQkFBTyxDQUFDLHFEQUFZO0FBQ25DLGVBQWUsbUJBQU8sQ0FBQyxxREFBWTs7QUFFbkM7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTs7QUFFQTtBQUNBOztBQUVBO0FBQ0E7O0FBRUE7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxXQUFXLEVBQUU7QUFDYixhQUFhLE9BQU87QUFDcEI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO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yZVRyaW0sICcnKTtcbiAgdmFyIGlzQmluYXJ5ID0gcmVJc0JpbmFyeS50ZXN0KHZhbHVlKTtcbiAgcmV0dXJuIChpc0JpbmFyeSB8fCByZUlzT2N0YWwudGVzdCh2YWx1ZSkpXG4gICAgPyBmcmVlUGFyc2VJbnQodmFsdWUuc2xpY2UoMiksIGlzQmluYXJ5ID8gMiA6IDgpXG4gICAgOiAocmVJc0JhZEhleC50ZXN0KHZhbHVlKSA/IE5BTiA6ICt2YWx1ZSk7XG59XG5cbm1vZHVsZS5leHBvcnRzID0gdG9OdW1iZXI7XG4iXSwic291cmNlUm9vdCI6IiJ9\n//# sourceURL=webpack-internal:///./node_modules/lodash/toNumber.js\n"); /***/ }) }]);
/** * Copyright IBM Corp. 2019, 2020 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. * * Code generated by @carbon/icon-build-helpers. DO NOT EDIT. */ 'use strict'; function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Icon = require('../Icon-e8f71a9c.js'); require('@carbon/icon-helpers'); require('prop-types'); var React = _interopDefault(require('react')); var _ref2 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M30 15L17 15 17 2 15 2 15 15 2 15 2 17 15 17 15 30 17 30 17 17 30 17 30 15z" }); var _ref3 = /*#__PURE__*/ /*#__PURE__*/ React.createElement("path", { d: "M25.586 20L27 21.414 23.414 25 27 28.586 25.586 30 20.586 25 25.586 20zM11 30H3a1 1 0 01-.8945-1.4473l4-8a1.0412 1.0412 0 011.789 0l4 8A1 1 0 0111 30zM4.6182 28H9.3818L7 23.2363zM28 12H22a2.0023 2.0023 0 01-2-2V4a2.0023 2.0023 0 012-2h6a2.0023 2.0023 0 012 2v6A2.0023 2.0023 0 0128 12zM22 4v6h6.001L28 4zM7 12a5 5 0 115-5A5.0059 5.0059 0 017 12zM7 4a3 3 0 103 3A3.0033 3.0033 0 007 4z" }); var TypePattern20 = /*#__PURE__*/React.forwardRef(function TypePattern20(_ref, ref) { var children = _ref.children, rest = Icon._objectWithoutProperties(_ref, ["children"]); return /*#__PURE__*/React.createElement(Icon.Icon, Icon._extends({ width: 20, height: 20, viewBox: "0 0 32 32", xmlns: "http://www.w3.org/2000/svg", fill: "currentColor", ref: ref }, rest), _ref2, _ref3, children); }); module.exports = TypePattern20;
module.exports = (array) => { let i = 0; while (i < array.length) { if (Array.isArray(array[i])) { array.splice(...[i, 1].concat(array[i])); } else { i += 1; } } return array; };
import React, {Component} from 'react'; import {PropTypes} from 'prop-types'; import {connect} from 'react-redux'; import {bindActionCreators} from 'redux'; import * as actionCreators from '../../actions/lottery'; import ProgressButton from 'react-progress-button'; import './ticket-page.css'; import 'progress_css'; @connect(mapStateToProps, mapDispatchToProps) export default class TicketPage extends Component { static propTypes = { actions: PropTypes.object.isRequired, generateState: PropTypes.shape({ isPending: PropTypes.bool.isRequired, success: PropTypes.string, error: PropTypes.string }).isRequired, ticketState: PropTypes.shape({ isPending: PropTypes.bool.isRequired, ticket: PropTypes.array, error: PropTypes.string }).isRequired, }; componentDidMount() { const {actions} = this.props; actions.load(); }; render() { const {ticketState, actions} = this.props; const {ticket, isPending, error} = ticketState; let content; if (isPending) { content = TicketPage.renderProgress() } else if (error) { content = TicketPage.renderError(error); } else if (ticket) { content = TicketPage.renderTicket(ticket); } return ( <div> {content} <div className='ticket_generate_container'> <ProgressButton onClick={() => actions.generate(actions) } state={this.progressButtonState()}> Generate </ProgressButton> </div> </div> ); }; progressButtonState() { const {isPending, success, error} = this.props.generateState; if (isPending) { return 'loading'; } else if (error) { return 'error'; } else if (success) { return 'success'; } else { return ''; } }; static renderTicket(ticket) { return ( <div className='ticket'> {ticket.join(' ')} </div> ); }; static renderError(error) { return ( <div className='ticket'> {error} </div> ); }; static renderProgress() { return ( <div className='ticket'> Progress... </div> ) }; } function mapStateToProps(state) { return { generateState: state.generate, ticketState: state.ticket }; } function mapDispatchToProps(dispatch) { return {actions: bindActionCreators(actionCreators, dispatch)}; }
import React from 'react'; import PropTypes from 'prop-types'; import { Box } from '@strapi/design-system/Box'; import Cross from '@strapi/icons/Cross'; import { Tag } from '@strapi/design-system/Tag'; import { useIntl } from 'react-intl'; const AttributeTag = ({ attribute, filter, onClick, operator, value }) => { const { formatMessage, formatDate, formatTime, formatNumber } = useIntl(); const handleClick = () => { onClick(filter); }; const { fieldSchema } = attribute; const type = fieldSchema?.mainField?.schema.type || fieldSchema.type; let formattedValue = value; if (type === 'date') { formattedValue = formatDate(value, { dateStyle: 'full' }); } if (type === 'datetime') { formattedValue = formatDate(value, { dateStyle: 'full', timeStyle: 'short' }); } if (type === 'time') { const [hour, minute] = value.split(':'); const date = new Date(); date.setHours(hour); date.setMinutes(minute); formattedValue = formatTime(date, { numeric: 'auto', style: 'short', }); } if (['float', 'integer', 'biginteger', 'decimal'].includes(type)) { formattedValue = formatNumber(value); } const content = `${attribute.metadatas.label || attribute.name} ${formatMessage({ id: `components.FilterOptions.FILTER_TYPES.${operator}`, defaultMessage: operator, })} ${operator !== '$null' && operator !== '$notNull' ? formattedValue : ''}`; return ( <Box padding={1} onClick={handleClick}> <Tag icon={<Cross />}>{content}</Tag> </Box> ); }; AttributeTag.propTypes = { attribute: PropTypes.shape({ name: PropTypes.string.isRequired, fieldSchema: PropTypes.object.isRequired, metadatas: PropTypes.shape({ label: PropTypes.string.isRequired }).isRequired, }).isRequired, filter: PropTypes.object.isRequired, onClick: PropTypes.func.isRequired, operator: PropTypes.string.isRequired, value: PropTypes.string.isRequired, }; export default AttributeTag;
'use strict'; /* jshint ignore:start */ /** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ /* jshint ignore:end */ var Q = require('q'); /* jshint ignore:line */ var _ = require('lodash'); /* jshint ignore:line */ var util = require('util'); /* jshint ignore:line */ var InviteList = require('./channel/invite').InviteList; var MemberList = require('./channel/member').MemberList; var MessageList = require('./channel/message').MessageList; var Page = require('../../../../base/Page'); /* jshint ignore:line */ var deserialize = require( '../../../../base/deserialize'); /* jshint ignore:line */ var serialize = require('../../../../base/serialize'); /* jshint ignore:line */ var values = require('../../../../base/values'); /* jshint ignore:line */ var ChannelList; var ChannelPage; var ChannelInstance; var ChannelContext; /* jshint ignore:start */ /** * Initialize the ChannelList * * @constructor Twilio.Chat.V1.ServiceContext.ChannelList * * @param {Twilio.Chat.V1} version - Version of the resource * @param {string} serviceSid - * The unique id of the [Service][service] this channel belongs to. */ /* jshint ignore:end */ ChannelList = function ChannelList(version, serviceSid) { /* jshint ignore:start */ /** * @function channels * @memberof Twilio.Chat.V1.ServiceContext# * * @param {string} sid - sid of instance * * @returns {Twilio.Chat.V1.ServiceContext.ChannelContext} */ /* jshint ignore:end */ function ChannelListInstance(sid) { return ChannelListInstance.get(sid); } ChannelListInstance._version = version; // Path Solution ChannelListInstance._solution = {serviceSid: serviceSid}; ChannelListInstance._uri = _.template( '/Services/<%= serviceSid %>/Channels' // jshint ignore:line )(ChannelListInstance._solution); /* jshint ignore:start */ /** * create a ChannelInstance * * @function create * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {object} [opts] - Options for request * @param {string} [opts.friendlyName] - A human-readable name for the Channel. * @param {string} [opts.uniqueName] - A unique, addressable name for the Channel. * @param {string} [opts.attributes] - * An optional metadata field you can use to store any data you wish. * @param {channel.channel_type} [opts.type] - * The visibility of the channel - public or private. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelListInstance.create = function create(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'FriendlyName': _.get(opts, 'friendlyName'), 'UniqueName': _.get(opts, 'uniqueName'), 'Attributes': _.get(opts, 'attributes'), 'Type': _.get(opts, 'type') }); var promise = this._version.create({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new ChannelInstance( this._version, payload, this._solution.serviceSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Streams ChannelInstance records from the API. * * This operation lazily loads records as efficiently as possible until the limit * is reached. * * The results are passed into the callback function, so this operation is memory * efficient. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function each * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {object} [opts] - Options for request * @param {channel.channel_type|list} [opts.type] - The type * @param {number} [opts.limit] - * Upper limit for the number of records to return. * each() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no pageSize is defined but a limit is defined, * each() will attempt to read the limit with the most efficient * page size, i.e. min(limit, 1000) * @param {Function} [opts.callback] - * Function to process each record. If this and a positional * callback are passed, this one will be used * @param {Function} [opts.done] - * Function to be called upon completion of streaming * @param {Function} [callback] - Function to process each record */ /* jshint ignore:end */ ChannelListInstance.each = function each(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; if (opts.callback) { callback = opts.callback; } if (_.isUndefined(callback)) { throw new Error('Callback function must be provided'); } var done = false; var currentPage = 1; var currentResource = 0; var limits = this._version.readLimits({ limit: opts.limit, pageSize: opts.pageSize }); function onComplete(error) { done = true; if (_.isFunction(opts.done)) { opts.done(error); } } function fetchNextPage(fn) { var promise = fn(); if (_.isUndefined(promise)) { onComplete(); return; } promise.then(function(page) { _.each(page.instances, function(instance) { if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) { done = true; return false; } currentResource++; callback(instance, onComplete); }); if ((limits.pageLimit && limits.pageLimit <= currentPage)) { onComplete(); } else if (!done) { currentPage++; fetchNextPage(_.bind(page.nextPage, page)); } }); promise.catch(onComplete); } fetchNextPage(_.bind(this.page, this, _.merge(opts, limits))); }; /* jshint ignore:start */ /** * Lists ChannelInstance records from the API as a list. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function list * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {object} [opts] - Options for request * @param {channel.channel_type|list} [opts.type] - The type * @param {number} [opts.limit] - * Upper limit for the number of records to return. * list() guarantees never to return more than limit. * Default is no limit * @param {number} [opts.pageSize] - * Number of records to fetch per request, * when not set will use the default value of 50 records. * If no page_size is defined but a limit is defined, * list() will attempt to read the limit with the most * efficient page size, i.e. min(limit, 1000) * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ ChannelListInstance.list = function list(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var allResources = []; opts.callback = function(resource, done) { allResources.push(resource); if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) { done(); } }; opts.done = function(error) { if (_.isUndefined(error)) { deferred.resolve(allResources); } else { deferred.reject(error); } }; if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } this.each(opts); return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single page of ChannelInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function page * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {object} [opts] - Options for request * @param {channel.channel_type|list} [opts.type] - The type * @param {string} [opts.pageToken] - PageToken provided by the API * @param {number} [opts.pageNumber] - * Page Number, this value is simply for client state * @param {number} [opts.pageSize] - Number of records to return, defaults to 50 * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ ChannelListInstance.page = function page(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'Type': serialize.map(_.get(opts, 'type'), function(e) { return e; }), 'PageToken': opts.pageToken, 'Page': opts.pageNumber, 'PageSize': opts.pageSize }); var promise = this._version.page({uri: this._uri, method: 'GET', params: data}); promise = promise.then(function(payload) { deferred.resolve(new ChannelPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Retrieve a single target page of ChannelInstance records from the API. * * The request is executed immediately. * * If a function is passed as the first argument, it will be used as the callback * function. * * @function getPage * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {string} [targetUrl] - API-generated URL for the requested results page * @param {function} [callback] - Callback to handle list of records * * @returns {Promise} Resolves to a list of records */ /* jshint ignore:end */ ChannelListInstance.getPage = function getPage(targetUrl, callback) { var deferred = Q.defer(); var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl}); promise = promise.then(function(payload) { deferred.resolve(new ChannelPage(this._version, payload, this._solution)); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * Constructs a channel * * @function get * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @param {string} sid - The sid * * @returns {Twilio.Chat.V1.ServiceContext.ChannelContext} */ /* jshint ignore:end */ ChannelListInstance.get = function get(sid) { return new ChannelContext(this._version, this._solution.serviceSid, sid); }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Chat.V1.ServiceContext.ChannelList# * * @returns Object */ /* jshint ignore:end */ ChannelListInstance.toJSON = function toJSON() { return this._solution; }; ChannelListInstance[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; return ChannelListInstance; }; /* jshint ignore:start */ /** * Initialize the ChannelPage * * @constructor Twilio.Chat.V1.ServiceContext.ChannelPage * * @param {V1} version - Version of the resource * @param {Response<string>} response - Response from the API * @param {ChannelSolution} solution - Path solution * * @returns ChannelPage */ /* jshint ignore:end */ ChannelPage = function ChannelPage(version, response, solution) { // Path Solution this._solution = solution; Page.prototype.constructor.call(this, version, response, this._solution); }; _.extend(ChannelPage.prototype, Page.prototype); ChannelPage.prototype.constructor = ChannelPage; /* jshint ignore:start */ /** * Build an instance of ChannelInstance * * @function getInstance * @memberof Twilio.Chat.V1.ServiceContext.ChannelPage# * * @param {ChannelPayload} payload - Payload response from the API * * @returns ChannelInstance */ /* jshint ignore:end */ ChannelPage.prototype.getInstance = function getInstance(payload) { return new ChannelInstance(this._version, payload, this._solution.serviceSid); }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Chat.V1.ServiceContext.ChannelPage# * * @returns Object */ /* jshint ignore:end */ ChannelPage.prototype.toJSON = function toJSON() { let clone = {}; _.forOwn(this, function(value, key) { if (!_.startsWith(key, '_') && ! _.isFunction(value)) { clone[key] = value; } }); return clone; }; ChannelPage.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; /* jshint ignore:start */ /** * Initialize the ChannelContext * * @constructor Twilio.Chat.V1.ServiceContext.ChannelInstance * * @property {string} sid - * A 34 character string that uniquely identifies this resource. * @property {string} accountSid - * The unique id of the [Account][/console] responsible for this channel. * @property {string} serviceSid - * The unique id of the [Service][service] this channel belongs to. * @property {string} friendlyName - The human-readable name of this channel. * @property {string} uniqueName - The unique, addressable name of this channel. * @property {string} attributes - * An optional string metadata field you can use to store any data you wish. * @property {channel.channel_type} type - * The visibility of this channel - either public or private * @property {Date} dateCreated - The date that this resource was created. * @property {Date} dateUpdated - The date that this resource was last updated. * @property {string} createdBy - Identity of the channel's creator. * @property {number} membersCount - The members_count * @property {number} messagesCount - The messages_count * @property {string} url - An absolute URL for this channel. * @property {string} links - * Absolute URLs to access the [Members][members] and [Messages][messages] for this channel. * * @param {V1} version - Version of the resource * @param {ChannelPayload} payload - The instance payload * @param {sid} serviceSid - * The unique id of the [Service][service] this channel belongs to. * @param {sid_like} sid - The sid */ /* jshint ignore:end */ ChannelInstance = function ChannelInstance(version, payload, serviceSid, sid) { this._version = version; // Marshaled Properties this.sid = payload.sid; // jshint ignore:line this.accountSid = payload.account_sid; // jshint ignore:line this.serviceSid = payload.service_sid; // jshint ignore:line this.friendlyName = payload.friendly_name; // jshint ignore:line this.uniqueName = payload.unique_name; // jshint ignore:line this.attributes = payload.attributes; // jshint ignore:line this.type = payload.type; // jshint ignore:line this.dateCreated = deserialize.iso8601DateTime(payload.date_created); // jshint ignore:line this.dateUpdated = deserialize.iso8601DateTime(payload.date_updated); // jshint ignore:line this.createdBy = payload.created_by; // jshint ignore:line this.membersCount = deserialize.integer(payload.members_count); // jshint ignore:line this.messagesCount = deserialize.integer(payload.messages_count); // jshint ignore:line this.url = payload.url; // jshint ignore:line this.links = payload.links; // jshint ignore:line // Context this._context = undefined; this._solution = {serviceSid: serviceSid, sid: sid || this.sid, }; }; Object.defineProperty(ChannelInstance.prototype, '_proxy', { get: function() { if (!this._context) { this._context = new ChannelContext(this._version, this._solution.serviceSid, this._solution.sid); } return this._context; } }); /* jshint ignore:start */ /** * fetch a ChannelInstance * * @function fetch * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelInstance.prototype.fetch = function fetch(callback) { return this._proxy.fetch(callback); }; /* jshint ignore:start */ /** * remove a ChannelInstance * * @function remove * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelInstance.prototype.remove = function remove(callback) { return this._proxy.remove(callback); }; /* jshint ignore:start */ /** * update a ChannelInstance * * @function update * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @param {object} [opts] - Options for request * @param {string} [opts.friendlyName] - A human-readable name for the Channel. * @param {string} [opts.uniqueName] - A unique, addressable name for the Channel. * @param {string} [opts.attributes] - * An optional metadata field you can use to store any data you wish. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelInstance.prototype.update = function update(opts, callback) { return this._proxy.update(opts, callback); }; /* jshint ignore:start */ /** * Access the members * * @function members * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @returns {Twilio.Chat.V1.ServiceContext.ChannelContext.MemberList} */ /* jshint ignore:end */ ChannelInstance.prototype.members = function members() { return this._proxy.members; }; /* jshint ignore:start */ /** * Access the messages * * @function messages * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @returns {Twilio.Chat.V1.ServiceContext.ChannelContext.MessageList} */ /* jshint ignore:end */ ChannelInstance.prototype.messages = function messages() { return this._proxy.messages; }; /* jshint ignore:start */ /** * Access the invites * * @function invites * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @returns {Twilio.Chat.V1.ServiceContext.ChannelContext.InviteList} */ /* jshint ignore:end */ ChannelInstance.prototype.invites = function invites() { return this._proxy.invites; }; /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Chat.V1.ServiceContext.ChannelInstance# * * @returns Object */ /* jshint ignore:end */ ChannelInstance.prototype.toJSON = function toJSON() { let clone = {}; _.forOwn(this, function(value, key) { if (!_.startsWith(key, '_') && ! _.isFunction(value)) { clone[key] = value; } }); return clone; }; ChannelInstance.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; /* jshint ignore:start */ /** * Initialize the ChannelContext * * @constructor Twilio.Chat.V1.ServiceContext.ChannelContext * * @property {Twilio.Chat.V1.ServiceContext.ChannelContext.MemberList} members - * members resource * @property {Twilio.Chat.V1.ServiceContext.ChannelContext.MessageList} messages - * messages resource * @property {Twilio.Chat.V1.ServiceContext.ChannelContext.InviteList} invites - * invites resource * * @param {V1} version - Version of the resource * @param {sid} serviceSid - The service_sid * @param {sid_like} sid - The sid */ /* jshint ignore:end */ ChannelContext = function ChannelContext(version, serviceSid, sid) { this._version = version; // Path Solution this._solution = {serviceSid: serviceSid, sid: sid, }; this._uri = _.template( '/Services/<%= serviceSid %>/Channels/<%= sid %>' // jshint ignore:line )(this._solution); // Dependents this._members = undefined; this._messages = undefined; this._invites = undefined; }; /* jshint ignore:start */ /** * fetch a ChannelInstance * * @function fetch * @memberof Twilio.Chat.V1.ServiceContext.ChannelContext# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelContext.prototype.fetch = function fetch(callback) { var deferred = Q.defer(); var promise = this._version.fetch({uri: this._uri, method: 'GET'}); promise = promise.then(function(payload) { deferred.resolve(new ChannelInstance( this._version, payload, this._solution.serviceSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * remove a ChannelInstance * * @function remove * @memberof Twilio.Chat.V1.ServiceContext.ChannelContext# * * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelContext.prototype.remove = function remove(callback) { var deferred = Q.defer(); var promise = this._version.remove({uri: this._uri, method: 'DELETE'}); promise = promise.then(function(payload) { deferred.resolve(payload); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; /* jshint ignore:start */ /** * update a ChannelInstance * * @function update * @memberof Twilio.Chat.V1.ServiceContext.ChannelContext# * * @param {object} [opts] - Options for request * @param {string} [opts.friendlyName] - A human-readable name for the Channel. * @param {string} [opts.uniqueName] - A unique, addressable name for the Channel. * @param {string} [opts.attributes] - * An optional metadata field you can use to store any data you wish. * @param {function} [callback] - Callback to handle processed record * * @returns {Promise} Resolves to processed ChannelInstance */ /* jshint ignore:end */ ChannelContext.prototype.update = function update(opts, callback) { if (_.isFunction(opts)) { callback = opts; opts = {}; } opts = opts || {}; var deferred = Q.defer(); var data = values.of({ 'FriendlyName': _.get(opts, 'friendlyName'), 'UniqueName': _.get(opts, 'uniqueName'), 'Attributes': _.get(opts, 'attributes') }); var promise = this._version.update({uri: this._uri, method: 'POST', data: data}); promise = promise.then(function(payload) { deferred.resolve(new ChannelInstance( this._version, payload, this._solution.serviceSid, this._solution.sid )); }.bind(this)); promise.catch(function(error) { deferred.reject(error); }); if (_.isFunction(callback)) { deferred.promise.nodeify(callback); } return deferred.promise; }; Object.defineProperty(ChannelContext.prototype, 'members', { get: function() { if (!this._members) { this._members = new MemberList(this._version, this._solution.serviceSid, this._solution.sid); } return this._members; } }); Object.defineProperty(ChannelContext.prototype, 'messages', { get: function() { if (!this._messages) { this._messages = new MessageList(this._version, this._solution.serviceSid, this._solution.sid); } return this._messages; } }); Object.defineProperty(ChannelContext.prototype, 'invites', { get: function() { if (!this._invites) { this._invites = new InviteList(this._version, this._solution.serviceSid, this._solution.sid); } return this._invites; } }); /* jshint ignore:start */ /** * Provide a user-friendly representation * * @function toJSON * @memberof Twilio.Chat.V1.ServiceContext.ChannelContext# * * @returns Object */ /* jshint ignore:end */ ChannelContext.prototype.toJSON = function toJSON() { return this._solution; }; ChannelContext.prototype[util.inspect.custom] = function inspect(depth, options) { return util.inspect(this.toJSON(), options); }; module.exports = { ChannelList: ChannelList, ChannelPage: ChannelPage, ChannelInstance: ChannelInstance, ChannelContext: ChannelContext };